<?php

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

/*
 *  kasjer
 */
$user=array();
$r=$GLOBALS['db']->query("select u.first_name,u.last_name,u.id from users as u join ecmcashs_ecmkpkw as rel on rel.user_id=u.id group by u.id");
while($dn = $GLOBALS['db']->fetchByAssoc($r))
    $user[]=$dn;

/**
 *  pobiera imie i nazwisko wybranego kasjera
 *  
 */
$us=new User;
$us->retrieve($_GET['kasjer']);

/**
 * EcmNewKpkws report DATE format
 */
require_once('include/utils.php');
global $db,$app_strings;

$stop = new DateTime('NOW');

$start = new DateTime(date('01.m.Y'));

$currentTo = @$_GET['date_to'] ? : $stop->format('t.m.Y');
$currentFrom = @$_GET['date_from'] ? : $start->format('01.m.Y');
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));

/*
 *  generate query
 * 
 */
$additionalWhereConditions = array(
    '\'' . $start->format('Y-m-01') . '\'',
    '\'' . $stop->format('Y-m-t') . '\'',
);

if($from = @$_GET['date_from']) {
    $fromDate = new DateTime($from);
    $additionalWhereConditions[0] = '\'' . $fromDate->format('Y-m-d') . '\'';
}


if($to = @$_GET['date_to']) {
    $toDate = new DateTime($to);
    $additionalWhereConditions[1] = '\'' . $toDate->format('Y-m-d') . '\'';
}
if($_GET['ecmcash_id']!=''){
    $additionalWhereConditions[2]='cash_id=\'' . $_GET['ecmcash_id'] . '\'';
}
if($_GET['kasjer']!=''){
	$kasjer=" and `created_by`='".$_GET['kasjer']."'";
} 
	

$additionalWhere = '`date_entered` BETWEEN ' . implode(' AND ', $additionalWhereConditions)." ".$kasjer;


$query = '
    SELECT

	`description`,`description`,`amount`,`document_no`,
	`parent_address_street`,`parent_address_city`,`parent_address_postalcode`,
	`parent_address_country`,`parent_contact_name`,`parent_contact_title`,
	`date_entered`,`type_id`,`parent_name`

    FROM `ecmnewkpkws`

    WHERE
    ' . (additionalWhere ? ($additionalWhere) : '') . '

    ORDER BY

    `date_entered` ASC;
';

$result = $db->query($query);
$query_bo = "SELECT SUM(IF(type_id = 0, amount, -amount)) AS `sum` FROM `ecmnewkpkws` WHERE `date_entered` < ".$additionalWhereConditions[0]." ".$kasjer;

$result_bo = $db->query($query_bo);
if($row_bo = $db->fetchByAssoc($db->query($query_bo)))
	{
		$bo = $row_bo["sum"];
	
	}
$date=array();	
$i=1;
while($row = $db->fetchByAssoc($result)){
    $row['type_id']==0 ? $date['in']+=$row['amount'] : $date['out']+=$row['amount'];
    $i%2 ? $row['class']='even' : $row['class']='odd'; 
    $row['number']=$i;
    $date[]=$row;
    $i++;
}

// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;


$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $date );
$smarty->assign ( "CASH_BEFORE", $bo );
$smarty->assign ( "CASH_NOW",(($bo+$date['in'])-$date['out']));
$smarty->assign ( "STOCKS", $datastocks );
$smarty->assign ( "PARAMS", $_GET);
$smarty->assign ( "USER_NAME",$us->full_name);
$smarty->assign ( "USERS", $user);
$smarty->assign ( "currentTo", $currentTo);
$smarty->assign ( "currentFrom", $currentFrom);
$smarty -> assign("dateFormat", $Calendar_daFormat);

if( $_GET['toPDF'] == '1' ) {
    if( $_GET['to_xls'] == '1' ) {
        

        $header=array();
        $header[]='numer dokumentu';
        $header[]='data';
         $header[]='tytuł';
        $header[]='kontrahent';
        $header[]='przychód';
        $header[]='rozchód';
      
                     $filename='modules/Home/Files/raport_kasowy_'.date('d_m-Y').'.csv';
        $fp=fopen($filename,'w');
            foreach ($header as $k=>$v){

           $header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
        }
        fwrite($fp, implode(";",$header).PHP_EOL);
	foreach ($date as $key=>$val){
            if($val['type_id']!=''){
           
            $line=array();
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['document_no']))).'"""';
            $line[]=$val['date_entered'];
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['description']))).'"""';
                    $line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_name'])));
            if($poz.type_id==0){
                 $line[]=str_replace(".",",",$val['amount']);
                     $line[]=str_replace(".",",",$val['wartosc']);
            } else {
                 $line[]=str_replace(".",",",$val['wartosc']);
                     $line[]=str_replace(".",",",$val['amount']);
            }
           
               foreach ($line as $k=>$v){
             $line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
        }
            fwrite($fp, implode(";",$line).PHP_EOL);
            }
                }
 
            
        
        header("Location: ". $filename);
    } else {
    $output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/kpkwReport.tpl' );
    include_once ("include/MPDF57/mpdf.php");
    unset($smarty);
    $p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 26, 10, 5, 5 );
    $p->setFooter('Strona {PAGENO}  z {nbpg}');
    $kasa=$_GET['cash_name']!='' ? '<br>Kasa: '.$_GET['cash_name'] : '';
    $usr=$_GET['kasjer']!='' ? '<br>Kasjer: '.$us->full_name : '';
    $p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">Saas SystemS Sp. z o.o.<br>
Raport kasowy<br>Raport od '.date('d.m.Y',strtotime($currentFrom)).' do '.date('d.m.Y',strtotime($currentTo)).' <br>Data wydruku: '.date("d.m.Y").' '.$kasa.' '.$usr.'</p>');
    //$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
    //echo $output;
    $p->writeHTML( $output );
     
    $p->Output ();
    }
} else {
    $smarty->display ( 'modules/EcmReports/tpls/kpkwReport.tpl' );
}

?>