<? 
session_start(); 

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

?>
		<link rel="stylesheet" href="include/jQuery/jquery-ui/themes/base/jquery-ui.css">
<script src="include/jQuery/jquery-2.1.0.min.js"></script>
<script src="include/jQuery/jquery-ui/ui/jquery-ui.js"></script>
<style>
#draggable { width: 150px; height: 150px; padding: 0.5em; }
#tab table, #tab td, #tab th  {border: 1px solid black; width:100%}


</style>
<script>
$(function() {
$( "div[name=lol]" ).draggable();
});
$("div[name=lol]").mousemove(function(e){
  var mousePos = {'x': e.layerX, 'y': e.layerY};
});
function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

function show(obj,event) {

    var el = document.getElementById(obj);
    el.style.display = 'block';
	var x=event.clientX;
	var y=event.clientY;
	x=x-300;
	
	el.style.position = "absolute";
	
    el.style.top = y+'px'; //or whatever 
    el.style.left = x+'px'; // or whatever

}
</script>	
<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>Raport sprzedaży po kategorii </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="InvoiceCatRap" />
<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">
			Kategoria	</td>
		<td class="dataField" width="30%" nowrap="nowrap">
			<select name="account[]" multiple=1>
			<option value="">Wybierz</option>
			<?php
			$w=$db->query("select id,name from ecmproductcategories where deleted='0' order by name asc");
			while($r=$db->fetchByAssoc($w)){
				echo '<option value="'.$r['id'].'"';
				   foreach ($account as $value)
					{
					if($r['id']==$value)echo ' selected';
					}
				if($account==$r['id'])echo ' selected';
				echo '>'.$r['name'].'</option>';
			}
			?>
			</select>
	
	  	</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';"><?
$ids='';
if(count($account)>0 && count($account)<2){
foreach ($account as $item){
$ids="&account[]=".$item."";
}
} else {

foreach ($account as $item){
$ids.="&account[]=".$item."";
}

}
echo '&nbsp;<input type="button" class="button" name="CreateXLS" value="Otwórz XLS" onclick="location.href=\'index.php?module=EcmProductCategories&action=createXLS&date_from='.$date_from.'&date_to='.$date_to.''.$ids.'&type='.$type.'\';">';
unset($ids);
?>
<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.="Produkt";
	$t.=$tde;
	$t.=$tds1;
		$t.="Kod";
	$t.=$tde;
	$t.=$tds1;
		$t.='<p style="text-align: right;">'."Ilość".'</p>';
	$t.=$tde;
	$t.=$tds1;
		$t.='<p style="text-align: right;">'."Kwota".'</p>';
	$t.=$tde;
	$t.=$tds1;
		$t.='<p style="text-align: right;">'."Szczegóły".'</p>';
	$t.=$tde;
		$t.=$tds1;
		$t.='<p style="text-align: right;">'."Kategoria".'</p>';
	$t.=$tde;
$t.=$tre;

$i=1;
$wh[]="fk.deleted='0'";
$wh[]="fk.canceled='0'";
if($type)$wh[]="fk.type='".$type."'";
//note that sel1[] is now $sel1
$ids=array();
unset($_SESSION);
if(count($account)>0 && count($account)<2){
foreach ($account as $item){
$wh[]="cat.id='".$item."'";
$_SESSION['zaznaczone'][]=$item;
}
} else {

foreach ($account as $item){
$ids[]="'".$item."'";
}
$ac=implode(",",$ids);
$wh[]='cat.id IN ('.$ac.')';
}

if($date_from)$wh[]="fk.register_date>='".$date_from."'";
if($date_to)$wh[]="fk.register_date<='".$date_to."'";
$where=implode(" and ",$wh);


//Print out the selection

$z="select fk.id,p.name,p.code,p.ecmproduct_id,		sum(
			CASE WHEN fk.type!='correct'
				THEN
					CASE WHEN fk.currency_value is null or fk.currency_value='' or fk.currency_value=0
						THEN
							p.subtotal
						ELSE
							p.subtotal*fk.currency_value
					END
				ELSE
					CASE WHEN p.old_subtotal IS null OR p.old_subtotal='' THEN
						0
					ELSE
						CASE WHEN fk.currency_value is null or fk.currency_value='' or fk.currency_value=0
							THEN
								p.subtotal-p.old_subtotal
							ELSE
								(p.subtotal-p.old_subtotal)*fk.currency_value
						END
				END				
			END
		) as razem,
	sum(
			CASE WHEN fk.type!='correct' 
				THEN 
					p.quantity
				ELSE 
					p.quantity-p.old_quantity 
			END
		) as quantity,p.subprice,cat.name as cname,cat.id as cid from ecminvoiceouts as fk
inner join ecminvoiceoutitems as p on p.ecminvoiceout_id=fk.id
inner join ecmproducts as pr on pr.id=p.ecmproduct_id
inner join ecmproductcategories as cat on cat.id=pr.product_category_id
where ".$where."
group by p.ecmproduct_id order by pr.product_category_id,razem desc;";
$w=$db->query($z);
echo '<br>'.$w->num_rows.'<br>';
echo mysql_error();
$ilosc=0;
$razem=0;
$microtime=str_replace(".","",str_replace(" ","",microtime()));
$name='fakury_'.$microtime;
$fp = fopen('modules/EcmReports/TXT/'.$name.'.txt', 'w');
fwrite($fp, 'RaportCat'."\n");
$abc=0;
$note="";
$sum=array();
while($r=$db->fetchByAssoc($w)){
	$z2="select fk.id,p.name,p.code,p.ecmproduct_id,		sum(
			CASE WHEN fk.type!='correct'
				THEN
					CASE WHEN fk.currency_value is null or fk.currency_value='' or fk.currency_value=0
						THEN
							p.subtotal
						ELSE
							p.subtotal*fk.currency_value
					END
				ELSE
					CASE WHEN p.old_subtotal IS null OR p.old_subtotal='' THEN
						0
					ELSE
						CASE WHEN fk.currency_value is null or fk.currency_value='' or fk.currency_value=0
							THEN
								p.subtotal-p.old_subtotal
							ELSE
								(p.subtotal-p.old_subtotal)*fk.currency_value
						END
				END				
			END
		) as razem,
	sum(
			CASE WHEN fk.type!='correct' 
				THEN 
					p.quantity
				ELSE 
					p.quantity-p.old_quantity 
			END
		) as quantity,p.subprice,fk.parent_id,fk.parent_name 
from ecminvoiceouts as fk 
inner join ecminvoiceoutitems as p on p.ecminvoiceout_id=fk.id
 inner join ecmproducts as pr on pr.id=p.ecmproduct_id
 inner join ecmproductcategories as cat on cat.id=pr.product_category_id 
where ".$where." and p.ecmproduct_id='".$r['ecmproduct_id']."'
group by fk.parent_id order by razem desc;";
$w2=$db->query($z2);
$note.='<div id="draggable'.$abc.'" name="lol" class="ui-widget-content" style="display:none; width:300px;z-index: '.$abc.';">
    <img border="0" src="themes/Sugar/images/close_inline.gif" onmousedown="hide(\'draggable'.$abc.'\')"></img>'.$r['name'].'<br>'.$r['code'].'<br><table id="tab"><tr><td>Kontrahent</td><td><p style="text-align: right;">Ilość</p></td><td><p style="text-align: right;">Kwota</p></td></tr>';

while($r2=$db->fetchByAssoc($w2)){
	$note.='<tr><td><a href="index.php?module=Accounts&action=DetailView&record='.$r2['parent_id'].'">'.$r2['parent_name'].'</a></td><td><p style="text-align: right;">'.format_number($r2['quantity']).'</p></td><td><p style="text-align: right;">'.format_number($r2['razem']).'</p></tr></tr>';
}
$note.='</table></div>';
			$b=$r['cid'];
			$sum[$b]['total']+=$r['razem'];
			$sum[$b]['quantity']+=$r['quantity'];
			$sum[$b]['cat']=$r['cname'];
			$sum[$b]['c']=0;
			
foreach($sum as $k=>$v ){

	if(($k!=$r['cid'] && $sum[$k]['c']==0)){
		
	$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.="Podsumowanie ".$sum[$k]['cat'];
		$t.=$tde;
		$t.=$tds1;
			$t.="";
		$t.=$tde;
		$t.=$tds1;
			$t.='<p style="text-align: right;">'.format_number($sum[$k]['quantity']).'</p>';
		$t.=$tde;
		$t.=$tds1;
			$t.='<p style="text-align: right;">'.format_number($sum[$k]['total']).'</p>';
		$t.=$tde;
		$t.=$tds;
			$t.='';
		$t.=$tde;
	$t.=$tre;

	$sum[$k]['c']=1;
	}
	}
	$t.=$trs;
		$t.=$tds;
			$t.='<a href="index.php?module=EcmProducts&action=DetailView&record='.$r['ecmproduct_id'].'">'.$r['name'].'</a>';
		$t.=$tde;
		$t.=$tds;
			$t.=$r['code'];

		$t.=$tde;
		$t.=$tds;
			$t.='<p style="text-align: right;">'.format_number($r['quantity']).'</p>';
		$t.=$tde;
		$t.=$tds;
			$t.='<p style="text-align: right;">'.format_number($r['razem']).'</p>';
		$t.=$tde;
		$t.=$tds;
		$show='<p style="text-align: right;"><a href="#" onClick="show(\'draggable'.$abc.'\',event)"><img src="themes/Sugar5/images/info_inline.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"></a></p>';
			$t.=$show;
		$t.=$tde;
				$t.=$tds;
			$t.='<p style="text-align: right;">'.$r['cname'].'</p>';
		$t.=$tde;
	$t.=$tre;
	$ilosc+=$r['quantity'];
	$razem+=$r['razem'];
	
	foreach($sum as $k=>$v ){

	if(($w->num_rows==$i && $sum[$k]['c']==0)){
		
	$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.="Podsumowanie ".$sum[$k]['cat'];
		$t.=$tde;
		$t.=$tds1;
			$t.="";
		$t.=$tde;
		$t.=$tds1;
			$t.='<p style="text-align: right;">'.format_number($sum[$k]['quantity']).'</p>';
		$t.=$tde;
		$t.=$tds1;
			$t.='<p style="text-align: right;">'.format_number($sum[$k]['total']).'</p>';
		$t.=$tde;
		$t.=$tds;
			$t.='';
		$t.=$tde;
	$t.=$tre;

	$sum[$k]['c']=1;
	}
	}
	$i++;
	$abc++;
}
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.="Podsumowanie";
	$t.=$tde;
	$t.=$tds1;
		$t.="&nbsp;";
	$t.=$tde;
	$t.=$tds1;
		$t.='<p style="text-align: right;">'.format_number($ilosc).'</p>';
	$t.=$tde;
	$t.=$tds1;
		$t.='<p style="text-align: right;">'.format_number($razem).'</p>';
	$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
}
echo $note;
?>
