<? 

global $db;
if(!$_GET['date_from'])$date_from=date("Y-m-d");
else $date_from=$GLOBALS['timedate']->to_db_date($_GET['date_from']);
$exp=explode("-",$date_from);
$date_from=date("Y-m-d",mktime(0,0,0,$exp[1],$exp[2],$exp[0])+24*3600);
if(!$date_from)$date_from=date("Y-m-d");

if(!$_GET['date_to'])$date_to=date("Y-m-d");
else $date_to=$GLOBALS['timedate']->to_db_date($_GET['date_to']);
$exp=explode("-",$date_to);
$date_to=date("Y-m-d",mktime(0,0,0,$exp[1],$exp[2],$exp[0])+24*3600);
if(!$date_to)$date_to=date("Y-m-d");

?>
<ul class="tablist" style="width:100%;">
<li>
	<a class="current" href="#">Wyszukiwanie</a>
</li>		
</ul>
<form action="index.php" method="get" name="SearchFormSales">
<input type="hidden" name="module" value="EcmReports" />
<input type="hidden" name="action" value="sales_by_accounts" />
<table style="border-top: 0px none; margin-bottom: 4px;width:100%" class="tabForm" border="0" cellpadding="0" cellspacing="0">
<tbody>
	<tr>			
		<td class="dataLabel" width="10%" nowrap="nowrap">
			Data		</td>
		<td class="dataField" width="30%" nowrap="nowrap">
			<input autocomplete="off" name="date_from" id="date_from" value="<? echo $GLOBALS['timedate']->to_display_date($date_from);?>" title="" tabindex="" size="11" maxlength="10" type="text">
			<img src="themes/default/images/jscalendar.gif" alt="Enter Date" id="date_from_trigger" align="absmiddle" border="0">
			<script type="text/javascript">
			Calendar.setup ({
			inputField : "date_from",
			daFormat : "<? echo str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));?>",
			button : "date_from_trigger",
			singleClick : true,
			dateStr : "",
			step : 1
			}
			);
			</script>
			&lt;&gt;
			<input autocomplete="off" name="date_to" id="date_to" value="<? echo $GLOBALS['timedate']->to_display_date($date_to);?>" title="" tabindex="" size="11" maxlength="10" type="text">
			<img src="themes/default/images/jscalendar.gif" alt="Enter Date" id="date_to_trigger" align="absmiddle" border="0">
			<script type="text/javascript">
			Calendar.setup ({
			inputField : "date_to",
			daFormat : "<? echo str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));?>",
			button : "date_to_trigger",
			singleClick : true,
			dateStr : "",
			step : 1
			}
			);
			</script>
	  	</td>
		<td class="dataLabel" width="10%" nowrap="nowrap">Kontrahent</td>
		<td class="dataField" nowrap="nowrap">
			<input name="account_name" tabindex="" id="account_name" size="" value="<?php echo $_REQUEST['account_name'];?>" title="" type="text">
			<input name="account_id" id="account_id" value="<?php echo $_REQUEST['account_id'];?>" type="hidden">
		<input name="btn_account_name" tabindex="" title="Select [Alt+T]" accesskey="T" class="button" value="Select" onclick='open_popup("Accounts", 600, 400, "", true, false, {"call_back_function":"set_return","form_name":"SearchFormSales","field_to_name_array":{"id":"account_id","name":"account_name"}}, "single", true);' type="button"></td>
		<td class="dataLabel" width="10%" nowrap="nowrap">Rodzaj FV</td>
		<td class="dataField" nowrap="nowrap">
			<select id="fv_type" name="fv_type">
				<option value="">Wszystkie</option>
				<option value="fv">Normalne</option>
				<option value="fvkor">Korekty</option>
			</select>
	 </tr>
</tbody>
</table>

<input type="hidden" id="process" name="process" value="1">
<input class="button" name="submit" value="Generuj" type="submit">
<input class="button" name="clear" value="Wyczyść" type="button" onclick="location.href='index.php?module=EcmReports&action=sales_by_accounts';">
</form><br />
<?php


if ($_REQUEST['process']!="1") return;

	$wh = array();
	if($date_from)$wh[]="register_date>='".$date_from."'";
	if($date_to)$wh[]="register_date<='".$date_to."'";
	if($_REQUEST['account_id']){
	  
	    $check=$db->query("select id from accounts where parent_id='".$_REQUEST['account_id']."'");
	    $parent_ids=array();
	    while($back=$db->fetchByAssoc($check)){
	        $parent_ids[]=$back['id'];
	    }
	    if(count($parent_ids)>0){
	        $wh[]="parent_id IN ('".implode("','",$parent_ids)."')";
	       // var_dump($wh);
	    } else {
	        $wh[]="parent_id='".$_REQUEST['account_id']."'";
	    }
	}

	
	//if($_REQUEST['account_name'])$wh[]="parent_name like '".$_REQUEST['account_name']."%'";
	if($_REQUEST['fv_type']) {
		if($_REQUEST['fv_type']=='fv')
		$wh[]="type = 'normal'";
		if($_REQUEST['fv_type']=='fvkor')
		$wh[]="type = 'correct'";
	}
	if(count($wh)>0)$where=" and ".implode(" and ",$wh);
	else $where="";
	$z="select document_no, id, parent_name, parent_id, type, total_brutto as total, total_netto as subtotal,register_date,currency_value from ecminvoiceouts where deleted='0' and canceled='0' ".$where;
	//echo $z;
	$w=$db->query($z);
	
	$result = array();
	$sum['subtotal'] = 0;
	$sum['total'] = 0;
	
	require_once('modules/EcmInvoiceOuts/EcmInvoiceOut.php');
	while ($row = $db->fetchByAssoc($w)) {
	
		if ($row['currency_value'] && floatval($row['currency_value']>0))
			$cv = $row['currency_value'];
		else
			$cv=1;
			
		if (!is_array($result[$row['parent_id']])) {
			$result[$row['parent_id']] = array();
			$result[$row['parent_id']]['invoices'] = array();
			//get account name
			$account = $db->fetchByAssoc($db->query("SELECT name FROM accounts WHERE id='".$row['parent_id']."'"));
			$result[$row['parent_id']]['parent_name'] = $account['name'];
		}		
	
		$tmp = array();
		$tmp['id'] = $row['id'];
		$tmp['document_no'] = $row['document_no'];
		$tmp['register_date'] = $row['register_date'];
		$tmp['total'] = $row['total']*$cv;
		$tmp['subtotal'] = $row['subtotal']*$cv;
		//$tmp['corrects'] = array();
		
		$sum['subtotal'] += $row['subtotal']*$cv;
		$sum['total'] += $row['total']*$cv;
	
		//search for corrects
		
		/*
		$cor = $db->query("SELECT id, document_no, total, subtotal FROM ecminvoiceouts WHERE ecminvoiceout_id='".$row['id']."' AND canceled='0' AND deleted='0'");
		while ($c_row = $db->fetchByAssoc($cor)) {
			$tmp2 = array();
			$tmp2['id'] = $c_row['id'];
			$tmp2['document_no'] = $c_row['document_no'];
			$tmp2['total'] = $c_row['total'];
			$tmp2['subtotal'] = $c_row['subtotal'];
			
			$tmp['corrects'][] = $tmp2;
			
			$sum['subtotal'] += $c_row['subtotal'];
			$sum['total'] += $c_row['total'];
		}
		*/
		
		$result[$row['parent_id']]['invoices'][] = $tmp;
		
	}
	
	
	$c1 = ' class="listViewTHS1" ';
	$c2 = ' class="oddListRowS1" style="text-align: left; width:120px;"';
	$c3 = ' class="oddListRowS1" style="text-align: right;"';
	$c4 = ' class="listViewTHS1" style="text-align: right;"';
	
	echo '<h2>Zakres dat  :'. $GLOBALS['timedate']->to_display_date($date_from) .' - '.$GLOBALS['timedate']->to_display_date($date_to).'</h2><br><br>';
	
	echo '<br><h2>Wartość sprzedaży</h2>';
	echo '<table><tr><td'.$c1.'>Netto</td><td'.$c1.'>Brutto</td></tr>';
	echo '<tr><td'.$c2.'>'.format_number($sum['subtotal']).'</td><td'.$c2.'>'.format_number($sum['total']).'</td></tr></table><br><br>';
	foreach ($result as $k =>$v) {
		$inv_total = 0; 
		$inv_subtotal = 0; 
		echo '<h2>'.$v['parent_name'].'</h2><br>';
		
		echo '<table><tr><td'.$c1.'>Numer</td><td>Data sprzedaży</td><td'.$c1.'>Netto</td><td'.$c1.'>Brutto</td>';
		foreach ($v['invoices'] as $vv) {
			echo '<tr><td'.$c2.'><a href="index.php?module=EcmInvoiceOuts&action=DetailView&record='.$vv['id'].'" target="new">'.$vv['document_no'].'</a></td><td>'.date("d.m.Y",strtotime($vv['register_date'])).'</td><td'.$c3.'>'.format_number($vv['subtotal']).'</td><td'.$c3.'>'.format_number($vv['total']).'</td></tr>';
			
			
			//var_dump($vv['corrects']);
			$corrects = false;
			$inv_total += $vv['total']; 
			$inv_subtotal += $vv['subtotal']; 
			/*
			foreach ($vv['corrects'] as $vvv) {
			$inv_total += $vvv['total']; 
			$inv_subtotal += $vvv['subtotal'];
				echo '<tr><td'.$c2.'>&nbsp&nbsp<a href="index.php?module=EcmInvoiceOuts&action=DetailView&record='.$vvv['id'].'" target="new">'.$vvv['document_no'].'</a></td><td'.$c3.'>'.format_number($vvv['subtotal']).'</td><td'.$c3.'>'.format_number($vvv['total']).'</td></tr>';
			}
			*/
		}
		echo '<tr><td'.$c1.'>Suma</td><td></td><td'.$c4.'>'.format_number($inv_subtotal).'</td><td'.$c4.'>'.format_number($inv_total).'</td></tr></table><br><br>';
		
	}
	//var_dump($result);
?>