<?php


//error_reporting(E_ALL);
if(!$_REQUEST['printed'])$_REQUEST['printed']="no";
if($_REQUEST['zip'] || $_REQUEST['status']){
	if($_REQUEST['type']=="zip"){
		require_once('include/pclzip/pclzip.lib.php');
		$zf='modules/EcmSales/upload_xml/archive'.time().'.zip';
  		$archive = new PclZip($zf);
  		if(count($_REQUEST['check'])>0){
			foreach($_REQUEST['check'] as $c){
				if($c)$files[]='/home/mz/edi/infinite-salesorders/orders/'.$c;
			}
		}
		$list=$archive->create($files,PCLZIP_OPT_REMOVE_ALL_PATH);
		//echo $archive->errorInfo(true);die();
		chmod($zf,0777);
		//header("Content-type: application/octet-stream");
		//header("Content-disposition: attachment; filename=archive.zip");
		//readfile($zf);
		header("Location: ".$zf);
	}
	else{
  		if(count($_REQUEST['check'])>0){
			foreach($_REQUEST['check'] as $c){
				$tmp=$GLOBALS['db']->query("select id from infinite_files where file like '".$c."'");
				if ($tmp->num_rows==0) {
					$GLOBALS['db']->query("insert into infinite_files set status='print',id='".create_guid()."',file='".$c."'");
				}
				else{
					$GLOBALS['db']->query("update infinite_files set status='print' where file='".$c."'");
				}
			}
		}
		header("Location: index.php?module=EcmSales&action=ListOrders");
	}
}
$tds1='<td valign="top" class="listViewThS1" style="vertical-align:top;">';
$trs='<tr>';
$tre='</tr>';
$tds='<td valign="top" class="oddListRowS1" style="vertical-align:top;">';
$tde='</td>';
$tbs='<table cellpadding="0" cellspacing="0" border="0" class="ListView" style="width:100%;">';
$tbe='</table>';

function sortableColumn($title,$order_by,$sorder){
	if($sorder=="asc")$sorder="desc";
	else $sorder="asc";
	return '<a href="index.php?module=EcmSales&action=ListOrders&order_by='.$order_by.'&sorder='.$sorder.'">'.$title.'</a>';
}
?>
<table cellspacing="0" cellpadding="0" border="0"><tr><td width="19"><img src="themes/Sugar/images/EcmSales.gif" style="margin-top: 3px; margin-right: 3px;" alt="EcmSales" width="16" border="0" height="16"></td>
<td width="544"><h2>Zamówienia sprzedaży: Skrzynka zleceń sprzedaży</h2></td></tr></table><br />
<ul class="tablist">
<li>
	<a class="current" href="#">Podstawowe wyszukiwanie</a>
</li>		
</ul>
<form action="index.php" method="get">
<input type="hidden" name="module" value="EcmSales" />
<input type="hidden" name="action" value="ListOrders" />
<table style="border-top: 0px none; margin-bottom: 4px;" class="tabForm" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
	<tr>
		<td class="dataLabel" width="10%" nowrap="nowrap">
			Wydrukowane</td>
		<td class="dataField" width="40%" nowrap="nowrap">
			<select name="printed">
			<option value="all"<? if($_REQUEST['printed']=="all")echo " selected";?>>All</option>
			<option value="yes"<? if($_REQUEST['printed']=="yes")echo " selected";?>>Yes</option>
			<option value="no"<? if($_REQUEST['printed']=="no")echo " selected";?>>No</option>
			</select>		
		</td>
		
		<td class="dataLabel" width="10%" nowrap="nowrap">
			Data		</td>
		<td class="dataField" width="30%" nowrap="nowrap">
			<input autocomplete="off" name="date" id="date" value="<? echo $GLOBALS['timedate']->to_display_date($date);?>" title="" tabindex="" size="11" maxlength="10" type="text">
			<img src="themes/default/images/jscalendar.gif" alt="Enter Date" id="date_trigger" align="absmiddle" border="0">
			<script type="text/javascript">
			Calendar.setup ({
			inputField : "date",
			daFormat : "<? echo str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));?>",
			button : "date_trigger",
			singleClick : true,
			dateStr : "",
			step : 1
			}
			);
			</script>
		</td>
		<td class="dataLabel" width="10%" nowrap="nowrap">
			Kontrahenci		</td>
		<td class="dataField" width="40%" nowrap="nowrap">
		<select name="account_id">
		<option value="">Wszyscy</option>
		<?php
		$w=$GLOBALS['db']->query("select id,name from accounts where deleted='0' and (parent_id=242 or parent_id=134) order by name asc");
		while($r=$GLOBALS['db']->fetchByAssoc($w)){
			echo '<option value="'.$r['id'].'"';
			if($_REQUEST['account_id']==$r['id'])echo ' selected';
			echo '>'.$r['name'].'</option>';
		}
		?>
		</select>
	  	</td>
	  </tr>
</table>

<input class="button" name="submit" value="Search" type="submit">&nbsp;
<input class="button" name="clear" value="Clear" type="button" onclick="location.href='index.php?module=EcmSales&action=ListOrders';">
</form>
<table class="h3Row" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
	<tr>
		<td nowrap="nowrap">
			<h3>Lista zamówień</h3>
		</td>
		<td width="100%">
			<img src="include/images/blank.gif" alt="" width="1" height="1">
		</td>
	</tr>
</tbody>
</table>
<?php
$d="/home/mz/edi/infinite-salesorders/orders/";
echo '<form method="post" action="index.php?module=EcmSales&action=ListOrders&to_pdf=1"><input type="hidden" value="zip" id="type" name="type" />'.$tbs;
echo $tdr;
echo $tds1.sortableColumn("Plik","file",$_REQUEST['sorder']).$tde;
echo $tds1.sortableColumn("Nr zamówienia","document_no",$_REQUEST['sorder']).$tde;
echo $tds1.sortableColumn("Status","status",$_REQUEST['sorder']).$tde;
echo $tds1.sortableColumn("Kontrahent","account_name",$_REQUEST['sorder']).$tde;
echo $tds1.sortableColumn("Data","date",$_REQUEST['sorder']).$tde;
echo $tds1.sortableColumn("Data dostawy","delivery_date",$_REQUEST['sorder']).$tde;
echo $tds1.sortableColumn("Razem","total",$_REQUEST['sorder']).$tde;
echo $tds1."&nbsp;".$tde;
echo $tds1."&nbsp;".$tde;
echo $tre;
require_once("include/ECM/EcmXml2Array/class.xml2array.php");
require_once("modules/EcmProducts/EcmProduct.php");
if(is_dir($d)) {
    if ($dh = opendir($d)) {
        while (($entry = readdir($dh)) !== false) {
			if($entry!="." && $entry!=".." && $entry!="invoice" && $entry!="orders" && !is_dir($d.$entry)){
				$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select status from infinite_files where file like '".$entry."'"));
				if($r['status'])$status="Printed";
				else $status="";
				
				if($_REQUEST['printed']=="yes"){
					if($status=="")continue;
				}
				if($_REQUEST['printed']=="no"){
					if($status=="Printed")continue;
				}			
				
				$xml_data = file_get_contents($d.$entry);
				$xmlObj    = new XmlToArray($xml_data);
				$ad = $xmlObj->createArray();
				
				$racc=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name,id from accounts where iln='".$ad['Document-Order']['Order-Parties'][0]['DeliveryPoint'][0]['ILN']."'"));
				if($_REQUEST['account_id'] && $_REQUEST['account_id']!=$racc['id'])continue;
				
				$pr=$ad['Document-Order']['Order-Lines'][0]['Line'];
				$total=0;
				foreach($pr as $prod){
			//if($ad['Document-Order']['Order-Header'][0]['OrderDate']!=$date)continue;
					$product_id="";
					$wwww=$GLOBALS['db']->query("select ecmproduct_language.ecmproduct_id from ecmproduct_language inner join ecmproducts on ecmproducts.id=ecmproduct_language.ecmproduct_id where ecmproduct_language.ean='".$prod['Line-Item'][0]['EAN']."' and ecmproducts.deleted='0' and ecmproduct_language.deleted='0' and ecmproducts.code NOT LIKE '%_w' and ecmproducts.code NOT LIKE '%_z' and ecmproducts.code NOT LIKE '%_W' and ecmproducts.code NOT LIKE '%_Z'");
					$rrrr=$GLOBALS['db']->fetchByAssoc($wwww);
					$product_id=$rrrr['ecmproduct_id'];

					$ecmp=new EcmProduct();
					$ecmp->retrieve($product_id);
					$product_code=$ecmp->code;
					$product_name=$ecmp->name;
					$vat_id=$ecmp->vat_id;
					$vat_name=$ecmp->vat_name;
					$vat_value=$ecmp->vat_value;
					
					if(eregi("Real",$racc['name'])){
						$rrr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select p.price from ecmpricebooks_ecmproducts as p inner join ecmpricebooks as e on e.id=p.ecmpricebook_id where e.id='b8c8cb50-4b60-5b02-5969-4b955880554a' and p.ecmproduct_id='".$product_id."'"));
						$prod['Line-Item'][0]['OrderedUnitNetPrice']=$rrr['price'];
					}
					$total+=$prod['Line-Item'][0]['OrderedQuantity']*$prod['Line-Item'][0]['OrderedUnitNetPrice']*(1+$vat_value/100);
				}
				$row[]=array(
					"status"=>$status,
					"account_name"=>$racc['name'],
					"account_id"=>$racc['id'],
					"file"=>$entry,
					"document_no"=>$ad['Document-Order']['Order-Header'][0]['OrderNumber'],
					"date"=>$ad['Document-Order']['Order-Header'][0]['OrderDate'],
					"delivery_date"=>$ad['Document-Order']['Order-Header'][0]['ExpectedDeliveryDate'],
					"total"=>$total,
				);
			}
		}
	}
}

include_once('modules/EcmCharts/chartHelper.php');
if(!$_REQUEST['order_by'])$order_by="date";
else $order_by=$_REQUEST['order_by'];
if(!$_REQUEST['sorder'])$sorder="desc";
else $sorder=$_REQUEST['sorder'];
$row=multisort($row,array(array('key'=>$order_by,'sort'=>$sorder)));
if(count($row)>0){
	foreach($row as $r){
		echo $trs.$tds.$r['file'].$tde;
		echo $tds.$r['document_no'].$tde;
		echo $tds.$r['status'].$tde;
		echo $tds.'<a href="index.php?module=Accounts&action=DetailView&record='.$r['account_id'].'">'.$r['account_name'].'</a>'.$tde;
		echo $tds.$timedate->to_display_date($r['date']).$tde;
		echo $tds.$timedate->to_display_date($r['delivery_date']).$tde;
		echo $tds.number_format($r['total'],2,",",".").$tde;
		echo $tds.'<a href="infinite-salesorders/orders/'.$r['file'].'">pokaż</a>'.$tde;
		echo $tds.'<input type="checkbox" value="'.$r['file'].'" name="check[]" />'.$tde.$tdr;
    }
}
echo $tbe.'<input type="submit" name="zip" onclick="document.getElementById(\'type\').value=\'zip\';" value="Utwórz ZIP" class="button" />&nbsp;<input type="submit" name="status" onclick="document.getElementById(\'type\').value=\'status\';" value="Wydrukowane" class="button" />&nbsp;<input type="submit" name="status" onclick="document.getElementById(\'type\').value=\'status_realisaed\';" value="Nie zrealizowane" class="button" /></form>';
?>