<?php

require_once ('modules/EcmInvoiceOuts/EcmInvoiceOut.php');
global $mod_strings, $app_list_strings;
$db = $GLOBALS['db'];
$productCategoryList = getProductCategoryList();

$accountName = $_REQUEST["accountName"];
$accountId = $_REQUEST["accountId"];

$productName = $_REQUEST["productName"];
$productId = $_REQUEST["productId"];
if (isset($productId) && $productId != '') {
    $where['productId'] = $productId;
} else if (!isset($productId) && isset($productName) && strlen($productName) > 0) {
    $where['productName'] = $productName;
}

if (isset($accountId) && $accountId!='') {
    $where['accountId'] = $accountId;
} else if (!isset($accountId) && isset($accountName) && strlen($accountName) > 0) {
    $where['accountName'] = $accountName;
}

try {
    $tmp = new DateTime(date('Y-m-31'));
    $tmp2 = new DateTime(date('Y-m-01'));
    $tmp2->sub(new DateInterval('P1Y'));
	$where['register_date_to'] = $tmp->format('Y-m-d');
    $where['register_date_from'] = $tmp2->format('Y-m-d');
//	$where['register_date_to'] = '2015-07-31';
//    $where['register_date_from'] = '2015-07-01';

} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}
$relationsQuery = " FROM `ecminvoiceouts`
	INNER JOIN `accounts` ON
	(accounts.id = ecminvoiceouts.parent_id)

	INNER JOIN `ecminvoiceoutitems` ON
	(ecminvoiceoutitems.ecminvoiceout_id = ecminvoiceouts.id)

	INNER JOIN `ecmproducts` ON
	(ecmproducts.id = ecminvoiceoutitems.ecmproduct_id)

	" /*. $relationsQueryReceipts*/ . "
";

$stock_array = array(""=>"");
$stock_request = $db->query("SELECT id, name FROM ecmstocks WHERE deleted=0");
while($row = $db->fetchByAssoc($stock_request)){ $stock_array[$row['id']] = $row['name']; }
$group_ks_without_filter = [];
$group_ks_result_without_filter = $db->query("SELECT DISTINCT `ks_group` " . $relationsQuery . " ORDER BY `ks_group`");
while($row = $db->fetchByAssoc($group_ks_result_without_filter)) { 
	
	if($app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group']]!=NULL){
	$group_ks_without_filter[$row['ks_group']] = $app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group'] ];
} 

}
$group_ks_without_filter_2 = [];
$group_ks_result_without_filter_2 = $db->query("SELECT DISTINCT `ks_group2` " . $relationsQuery . " ORDER BY `ks_group2`");

while($row = $db->fetchByAssoc($group_ks_result_without_filter_2)) {

	
	if($app_list_strings['ecmproducts_group2_ks_dom'][ $row['ks_group2']]!=NULL){
		$group_ks_without_filter_2[$row['ks_group2']] = $app_list_strings['ecmproducts_group2_ks_dom'][ $row['ks_group2'] ];
	}
}


//$where['type'] = 'correct';
//$where['type'] = 'normal';

if(isset($_REQUEST['product_group']) && !empty($_REQUEST['product_group'])){
$where['product_group']=$_REQUEST['product_group'];
}
if(isset($_REQUEST['product_group_2']) && !empty($_REQUEST['product_group_2'])){
	$where['product_group_2']=$_REQUEST['product_group_2'];
}
if(isset($_REQUEST['stocks']) && !empty($_REQUEST['stocks'])){
$where['stocks']=$_REQUEST['stocks'];
}

$where['deleted'] = 0;
$where['canceled'] = 0;

if($_REQUEST['submit']){
$data = AnalysisProductSale($where);
$rows = array();
foreach ($data as $key => $value) {
    $rows['netto'][] = $value['total_netto'];
//    $rows['total_brutto'][] = $value['total_brutto'];
    $rows['ilosc'][] = $value['quantity'];
    $rows['srednia'][]=$value['total_netto']/$value['quantity'];
    $rows['marza'][] = $value['total_netto'] - $value['total_purchase'];
    $rows['marzaprocent'][] = (($value['total_netto'] - $value['total_purchase']) * 100) / $value['total_netto'];
}
}


$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $data);
$smarty->assign("ROWS", $rows);
$smarty->assign("stock_array", $stock_array);
$smarty->assign("product_group", $group_ks_without_filter);
$smarty->assign("product_group_2", $group_ks_without_filter_2);
$smarty->assign("productCategoryList", $productCategoryList);
$smarty->assign("productCategorySelected", $productCategorySelected);

$smarty->assign("accountName", $accountName);
$smarty->assign("accountId", $accountId);

$smarty->assign("productName", $productName);
$smarty->assign("productId", $productId);


if ($_GET ['to_pdf'] == '1') {
    $output = $smarty->fetch('modules/EcmReports/tpls/PDF/AnalysisPZ.tpl');

    include_once ("include/MPDF57/mpdf.php");
    $p = new mPDF('', 'A4', NULL, 'helvetica', 10, 10, 10, 10, 5, 5);
    $p->writeHTML($output);
    $p->Output('RaportSprzedazy.pdf', 'I');
} else {
    echo $smarty->display('modules/EcmReports/tpls/AnalysisPZ.tpl');
}

function AnalysisProductSale($where) {
    global $db;
    $query = "SELECT total_netto,  i.stock_id,p.price ,p.ecmstockdocin_id as ecminvoiceout_id, p.ecmproduct_id, p.code, p.name, p.quantity , i.register_date, i.currency_value, i.currency_id FROM ecmstockdocinitems p, ecmstockdocins i,ecmproducts s WHERE p.ecmstockdocin_id = i.id and s.id=p.ecmproduct_id";
    //die(1);
    if (isset($where) && is_array($where) && count($where) > 0) {

        $wherereturn = array();
       /* if(!array_key_exists('stocks',$where)){
        	 $wherereturn[] = "i.stock_id IN ('" . implode("','",$value) . "')";
        }*/
        foreach ($where as $key => $value) {
        	
        	
        	//print_r($key);print_r('<br><br>');
        	
        	//print_r($value);print_r('<br><br>');
        	
            switch ($key) {
                case 'register_date_from':
                    $wherereturn[] = "i.register_date>='" . $value . "'";
                    break;
                case 'register_date_to':
                    $wherereturn[] = "i.register_date<='" . $value . "'";
                    break;
                case 'accountName':
                    $wherereturn[] = "i.parent_name LIKE '%" . trim($value) . "%'";
                    $wherereturn[] = "i.parent_type ='Accounts'";
                    break;
                case 'product_group':
                    $wherereturn[] = "s.ks_group IN ('" . implode("','",$value) . "')";
                    break;
                    case 'product_group_2':
                    	$wherereturn[] = "s.ks_group2 IN ('" . implode("','",$value) . "')";
                    	break;
				case 'productId':
                    $wherereturn[] = "p.ecmproduct_id = '" . trim($value) . "'";
                    break;
				case 'accountId':
					$wherereturn[] = "i.parent_id = '" . trim($value) . "'";
					break;
				case 'stocks':
					 $wherereturn[] = "i.stock_id IN ('" . implode("','",$value) . "')";
                
					break;
                default:
                    $wherereturn[] = "i." . $key . " = '" . $value . "'";
                    break;
            }
        }
        if (count($wherereturn) > 0) {
            $query .= " AND " . implode(" AND ", $wherereturn);
        }
    }
  
    $query .= " ORDER BY i.register_date";
	//echo $query;
	//print_r($query);
    $result = $db->query($query);
   
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
        	//print_r($row);
			$currency = 1;
			if($row['type']!='K'){
				if($row['currency_value']!=''&& $row['currency_value']!='0'){
					$currency = $row['currency_value'];
				}elseif($row['currency_value_nbp']!=''){
					$currency = $row['currency_value_nbp'];
				}
			}
			if($row['type']==''){
				$return[substr($row['register_date'], 0, 7)]['total_netto'] += round($row['price']* $row['quantity'],2);
				$return[substr($row['register_date'], 0, 7)]['quantity'] += $row['quantity'];
				
			}else{
				$return[substr($row['register_date'], 0, 7)]['total_purchase'] += round($row['price_purchase'] * $row['quantity_corrected'] ,2);
				$return[substr($row['register_date'], 0, 7)]['total_netto'] += $row['total_netto_corrected']* $currency;
			}
        }
    } else {
        $return = NULL;
    }
	
	if(count($return)<12){
		try {
			$currentDate = new DateTime(date('Y-m-01'));
			$date = new DateTime(date('Y-m-01'));
			$date->sub(new DateInterval('P1Y'));
			$register_date_fill = $date->format('Y-m');
		} catch (Exception $e) {
			echo $e->getMessage();
			exit(1);
		}
		while(count($return)<12){
			if(!isset($return[$register_date_fill])){
				$return[$register_date_fill]['total_purchase'] = 0;
				$return[$register_date_fill]['total_netto'] = 0;
			}
			$date->add(new DateInterval('P1M'));
			$register_date_fill = $date->format('Y-m');
		}
	}
	
	ksort($return);
	
	$formated_return;
	foreach ($return as $data => $row){
		
		$split = split("-",$data);
		$formated_return[$split[1] .".".$split[0]] = $row;
	}
	
    return $formated_return;
}

function getProductCategoryList() {
    global $db;
    $resultArray = NULL;
    $query = "SELECT id, name FROM ecmproductcategories WHERE deleted=0 ORDER BY name, date_entered";
    $result = $db->query($query);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $resultArray[$row['id']] = $row['name'];
        };
    }
    return $resultArray;
}
?>
