<? 

$db = $GLOBALS['db'];

$account=$_GET['account'];
$account_id=$_GET['account_id'];
$account_name=$_GET['account_name'];
$type=$_GET['type'];

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");

?>
<table cellspacing="0" cellpadding="0" border="0"><tr><td><img src="themes/Sugar/images/EcmProducts.gif" style="margin-top: 3px; margin-right: 3px;" alt="EcmProducts" width="16" border="0" height="16"></td><td><h2>Eksport Faktury </h2></td></tr></table><br />
<ul class="tablist" style="width:100%;">
<li>
	<a class="current" href="#">Podstawowe wyszukiwanie</a>
</li>		
</ul>
<form action="index.php" method="get" name="search_reports">
<input type="hidden" name="module" value="EcmReports" />
<input type="hidden" name="action" value="InvoiceTXT" />
<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="5%" nowrap="nowrap">
			Data od	</td>
		<td class="dataField" width="10%" 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>
	  	</td>	
		<td class="dataLabel" width="10%" nowrap="nowrap">
			Data do</td>
		<td class="dataField" width="30%" nowrap="nowrap">
			<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" width="30%" nowrap="nowrap">
			<!--<select name="account">
			<option value="">select</option>
			<?php
			$w=$db->query("select id,name from accounts where deleted='0' order by name asc");
			while($r=$db->fetchByAssoc($w)){
				echo '<option value="'.$r['id'].'"';
				if($account==$r['id'])echo ' selected';
				echo '>'.$r['name'].'</option>';
			}
			?>
			</select>-->
			<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="Wybierz" onclick='open_popup("Accounts", 600, 400, "", true, false, {"call_back_function":"set_return","form_name":"search_reports","field_to_name_array":{"id":"account_id","name":"account_name"}}, "single", true);' type="button">

	  	</td>
		<td class="dataLabel" width="10%" nowrap="nowrap">
			Typ dokumentu	</td>
		<td class="dataField" width="30%" nowrap="nowrap">
			<select name="type">
			<option value="" <? if($type=="")echo 'selected';?>>normalny i korekta</option>
			<option value="normal" <? if($type=="normal")echo 'selected';?>>normalny</option>
			<option value="correct" <? if($type=="correct")echo 'selected';?>>korekta</option>
			</select>
	  	</td>
	 </tr>
</tbody>
</table>

<input class="button" name="submit" value="Szukaj" type="submit">
<input class="button" name="clear" value="Wyczyść" type="button" onclick="location.href='index.php?module=EcmReports&action=ListDailySales';"><?
echo '&nbsp;<input type="button" class="button" name="CreateXLS" value="Otwórz XLS" onclick="location.href=\'index.php?module=EcmInvoiceOuts&action=CreateXLS&date_from='.$date_from.'&date_to='.$date_to.'&account_id='.$account_id.'&account_name='.$account_name.'&type='.$type.'\';">';

?>
<input class="button" name="txt" value="Utwórz TXT" type="submit">
</form><br />
<?php

$tds1='<td class="listViewThS1">';

$trs='<tr onMouseover="this.bgColor=\'#EEEEEE\'"onMouseout="this.bgColor=\'#FFFFFF\'">';
$tre='</tr>';

$tds='<td class="oddListRowS1">';
$tde='</td>';

$tbs='<table cellpadding="0" cellspacing="0" border="0" class="ListView" style="width:100%;">';
$tbe='</table>';

$t.=$tbs;
$t.=$trs;
	$t.=$tds1;
		$t.="Nr faktury";
	$t.=$tde;
	$t.=$tds1;
		$t.="Typ";
	$t.=$tde;
	$t.=$tds1;
		$t.="Kontrahent";
	$t.=$tde;
	$t.=$tds1;
		$t.="Data utworzenia";
	$t.=$tde;
	$t.=$tds1;
		$t.="Razem Brutto";
	$t.=$tde;
	$t.=$tds1;
		$t.="Razem Netto";
	$t.=$tde;
	$t.=$tds1;
		$t.="Koszt";
	$t.=$tde;
	$t.=$tds1;
		$t.="PLN Margin";
	$t.=$tde;
$t.=$tre;
$i=1;
$wh[]="deleted='0'";
$wh[]="canceled='0'";
if($type)$wh[]="type='".$type."'";
if($account_id)$wh[]="parent_id='".$account_id."'";
if($account_name)$wh[]="parent_name like '".$account_name."%'";
if($date_from)$wh[]="register_date>='".$date_from."'";
if($date_to)$wh[]="register_date<='".$date_to."'";
$where=implode(" and ",$wh);
$z="select purchase_price,total, subtotal,document_no,register_date,stock_id,payment_date,currency_id,id,parent_id,parent_name,sell_date,type,ecminvoiceout_id,currency_value,discount,to_nip from ecminvoiceouts where ".$where." order by type desc, register_date asc, name asc";
echo $z;
$w=$db->query($z);
echo '<br>'.$w->num_rows.'<br>';
echo mysql_error();
$sum_margin = 0;
$count_normal = 0;
$microtime=str_replace(".","",str_replace(" ","",microtime()));
$name='fakury_'.$microtime;
$fp = fopen('modules/EcmReports/TXT/'.$name.'.txt', 'w');
fwrite($fp, 'Faktura'."\n");
while($r=$db->fetchByAssoc($w)){
if(!$r['currency_value'])$currency_value=1;
else {
	$currency_value=$r['currency_value'];
	//echo $currency_value;
	}
	//$currency_value=1;
	$nip=$db->query("select to_vatid from accounts where id='".$r['parent_id']."'");
	$wal=$db->query("select name from currencies where id='".$r['currency_id']."'");
	$nip=$db->fetchByAssoc($nip);
	$waluta=$db->fetchByAssoc($wal);
	if($db->getRowCount($wal)==0) $waluta['name']='PLN';
	if($currency_value==1){
	$vat=$r['total']-$r['subtotal'];
	} else {$vat=0;}
	if($r['stock_id']==''){
	$stock='c7afd71a-4c3a-bde4-138d-4acaee1644e4';
	} else {
	$stock=$r['stock_id'];
	} if($r['currency_value']=="")$r['currency_value']='0';
	$total_pur=$r['purchase_price'];
	if($total_pur=='')$total_pur='0';
	fwrite($fp, $r['document_no'].' | '.$r['register_date'].' | '.$r['sell_date'].' | '.$r['parent_name'].' | '.$nip['to_vatid'].' | '.$r['parent_name'].' | '.$r['subtotal'].' | '.$vat.' | '.$r['total'].' | '.$total_pur.' | '.$r['payment_date'].' | '.$stock.' | '.$waluta['name'].' | '.$r['currency_value']."\n");
	$total_netto=$r['subtotal']*$currency_value;
	
	$total_brutto=$r['total']*$currency_value;
	$total_margin=0;
	
	if ($r['document_no']=='001/E/2013') echo $currency_value.'<br>'.$r['subtotal'].'<br>'.$total_netto;


	if($total_netto-$total_margin>0)$margin=100*$total_margin/($total_netto-$total_margin);
	else $margin=0;
	
	
	if ($r['type']=='normal') {
		$total_margin = (($total_netto-$total_pur)/$total_netto)*100;
		$count_normal++;
		$sum_margin+=$total_margin;		
	}
	
	if($r['discount']>0){
		$vr=$total_brutto/$total_netto;
		$total_brutto=$total_brutto-$r['discount'];
		$total_netto=$total_brutto/$vr;
	}
	


	$t.=$trs;
		$t.=$tds;
			$t.='<a href="index.php?module=EcmInvoiceOuts&action=DetailView&record='.$r['id'].'">'.$r['document_no'].'</a>';
		$t.=$tde;
		$t.=$tds;
			$t.=$r['type'];
		$t.=$tde;
		$t.=$tds;
			$t.='<a href="index.php?module=Accounts&action=DetailView&record='.$r['parent_id'].'">'.$r['parent_name'].'</a>';
		$t.=$tde;
		$t.=$tds;
			$t.=$GLOBALS['timedate']->to_display_date($r['register_date']);
		$t.=$tde;
		$t.=$tds;
			$t.=format_number($total_brutto);
		$t.=$tde;
		$t.=$tds;
			$t.=format_number($total_netto);
		$t.=$tde;
		$t.=$tds;
			$t.=format_number($total_pur);
		$t.=$tde;
		$t.=$tds;
			$t.=format_number($total_margin)."%";
		$t.=$tde;
	$t.=$tre;
	
	$sum_total_netto+=$total_netto;
	$sum_total_pur+=$total_pur;
	$sum_total_brutto+=$total_brutto;
	$sum_total_margin+=$total_margin;
	
	$i++;
}
fclose($fp);

$t.=$trs;
	//if($sum_total_netto-$sum_total_margin>0)$sum_margin=100*$sum_total_margin/($sum_total_netto-$sum_total_margin);
	//else $sum_margin=0;
	$t.=$tds1;
		$t.="&nbsp;";
	$t.=$tde;
	$t.=$tds1;
		$t.="&nbsp;";
	$t.=$tde;
	$t.=$tds1;
		$t.="&nbsp;";
	$t.=$tde;
	$t.=$tds1;
		$t.="&nbsp;";
	$t.=$tde;
	$t.=$tds1;
		$t.=format_number($sum_total_brutto);
	$t.=$tde;
	$t.=$tds1;
		$t.=format_number($sum_total_netto);
	$t.=$tde;
	$t.=$tds1;
		$t.=format_number($sum_total_pur);
	$t.=$tde;
	$t.=$tds1;
		$t.=format_number($sum_margin/$count_normal)."%";
	$t.=$tde;
$t.=$tre;

$t.=$tbe;
//echo $t;
if(isset($_REQUEST['txt'])){


// send the right headers
 header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename('modules/EcmReports/TXT/'.$name.'.txt'));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize('modules/EcmReports/TXT/'.$name.'.txt'));

        ob_clean();
        flush();
        readfile('modules/EcmReports/TXT/'.$name.'.txt');
        exit;
// dump the picture and stop the script
}
?>