<?php

if (!defined('sugarEntry') || !sugarEntry)
    die('Not A Valid Entry Point');

global $current_user;
if ($current_user->is_admin || $current_user->id == '49584975-a4a4-6c28-3b31-54bcb71a8f2b') {
    
} else {
    ACLController::displayNoAccess(true);
    sugar_die();
}

/**
 * ********************* PREPARE ********************
 */
global $app_list_strings;
global $mod_strings;
$db = $GLOBALS ['db'];
$date_from = date("Y-01-01");
$date_to = date("Y-m-01");
$return = array();
$suma['netto'] = 0;
$suma['brutto'] = 0;
$query = "";


// Pobieranie danych z formularza
if (!$_GET['date_from']) {
    $date_from = date("Y-01-01");
} else {
    $date_from = $_GET['date_from'];
    $tmp = date_parse_from_format("d.m.Y", $_GET['date_from']);
    $date_from = date($tmp['year'] . "-" . $tmp['month'] . "-01");
}
if (!$_GET['date_to']) {
    $date_to = date("Y-m-d");
} else {
    $date_to = $_GET['date_to'];
}
//formatowanie daty
$Calendar_daFormat = str_replace("d", "%d", str_replace("m", "%m", str_replace("Y", "%Y", $GLOBALS['timedate']->get_date_format())));
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);


/** 	
 * ************* GET DATA FROM DB********************
 */
$query = "
SELECT 
    wc.worker_id worker_id,
    wc.worker_name work_name
FROM
    ecmworkcards_ecmaction wca,
    ecmworkcards wc
WHERE
    wca.ecmworkcards = wc.id
        AND wc.deleted = 0
		AND wc.date >= STR_TO_DATE('" . $date_from . "','%d.%m.%Y')
		AND wc.date <= STR_TO_DATE('" . $date_to . "','%d.%m.%Y')
GROUP BY wc.worker_id;";
$rows = $db->query($query);
if ($rows->num_rows == 0) {
    
} else {
    while ($r = $db->fetchByAssoc($rows)) {
        $row = array();
        $row['work_name'] = $r['work_name'];
        $row['class'] = 'parent';
        $row['actions'] = array();
        $wherequery = "
            SELECT 
                id
            FROM
                ecmworkcards
            WHERE
                deleted = 0
                AND date >= STR_TO_DATE('" . $date_from . "','%d.%m.%Y') 
                AND date <= STR_TO_DATE('" . $date_to . "','%d.%m.%Y') "
                . " AND worker_id = '" . $r['worker_id'] . "'";
        $actionquery = "
			SELECT 
				wca.ecmproduct ecmproduct,
				wca.ecmaction ecmaction,
				wca.quantity quantity,
				wca.ecmactioncost ecmactioncost,
				wca.costbrutto costbrutto,
				a.name actionname,
				a.indeks actioncode,
				p.name productname,
				p.code productcode
            FROM
                ecmworkcards_ecmaction wca,
                ecmactions a,
                ecmproducts p
            WHERE
                a.id = wca.ecmaction
                    AND wca.ecmproduct = p.id"
                . " AND wca.ecmworkcards IN (" . $wherequery . ")
				ORDER BY p.code, a.indeks";
        $actionrows = $db->query($actionquery);
        if ($actionrows->num_rows == 0) {
            $row['actions'] = null;
        } else {
            $sumkanetto = 0;
            $sumkabrutto = 0;
            while ($rr = $db->fetchByAssoc($actionrows)) {
                $test = false; //sprawdza czy dana czynnosc jest juz pod pracownikiem z danym produktem
                // jesli tak to dodaje do porzedniego rekordu, jesli nie to dodaje nowy
                foreach ($row['actions'] as $key => $value) {
                    if ($value['actioncode'] == $rr['actioncode'] && $value['productcode'] == $rr['productcode']) {
                        $row['actions'][$key]['quantity'] += $rr['quantity'];
                        $row['actions'][$key]['netto'] += round($rr['ecmactioncost'] * $rr['quantity'], 2);
                        $row['actions'][$key]['brutto'] += round($rr['costbrutto'] * $rr['quantity'], 2);
                        $test = true;
                        $sumkanetto += round($rr['ecmactioncost'] * $rr['quantity'], 2);
                        $sumkabrutto += round($rr['costbrutto'] * $rr['quantity'], 2);
                        break;
                    }
                }
                if (!$test) {
                    $rowaction = array();
                    $rowaction['actionname'] = $rr['actionname'];
                    $rowaction['actioncode'] = $rr['actioncode'];
                    $rowaction['productname'] = $rr['productname'];
                    $rowaction['ecmproduct'] = $rr['ecmproduct'];
                    $rowaction['productcode'] = $rr['productcode'];
                    $rowaction['netto'] = round($rr['ecmactioncost'] * $rr['quantity'], 2);
                    $rowaction['brutto'] = round($rr['costbrutto'] * $rr['quantity'], 2);
                    $rowaction['quantity'] = $rr['quantity'];
                    $rowaction['class'] = 'child';
                    $sumkanetto += round($rr['ecmactioncost'] * $rr['quantity'], 2);
                    $sumkabrutto += round($rr['costbrutto'] * $rr['quantity'], 2);
                    $row['actions'][] = $rowaction;
                }
            }
        }
        foreach ($row['actions'] as $key => $value) {
            $row['actions'][$key]['netto'] = number_format($row['actions'][$key]['netto'], 2, ",", ".");
            $row['actions'][$key]['brutto'] = number_format($row['actions'][$key]['brutto'], 2, ",", ".");
        }
        $row['netto'] = number_format($sumkanetto, 2, ",", ".");
        $row['brutto'] = number_format($sumkabrutto, 2, ",", ".");
        $suma['netto']+= $sumkanetto;
        $suma['brutto']+= $sumkabrutto;
        $return[] = $row;
    }
}

$suma['netto'] = number_format($suma['netto'], 2, ",", ".");
$suma['brutto'] = number_format($suma['brutto'], 2, ",", ".");
/**
 * ******************** SMARTY **********************
 */
$smarty = new Sugar_Smarty ();
$smarty->assign('MOD', $mod_strings);
$smarty->assign('data', $return);
$smarty->assign('suma', $suma);
$smarty->assign('date_from', $date_from);
$smarty->assign('date_to', $date_to);
$smarty->assign('dateFormat', $Calendar_daFormat);
echo $smarty->display('modules/EcmReports/tpls/ReportEcmWorkCards.tpl');
?>
