<?php
//error_reporting(0);
set_time_limit(99999999);
define('RELATIVE_PATH','include/html2fpdf/');
define('FPDF_FONTPATH','include/html2fpdf/font/');
require_once("include/html2fpdf/html2fpdf.php");
require_once("modules/EcmPriceKopias/ListHelper.php");

$_SESSION['pricebook_images']=$_REQUEST['images'];
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name,exchange_rate_id,description,ecmlanguage,currency_value from ecmpricekopias where id='".$_SESSION['pricebook_id']."'"));
$name=$r['name'];
$description=$r['description'];
$exchange_rate_id=$r['exchange_rate_id'];
$lang=$_REQUEST['langs'];
//echo $lang;
//die($lang);
$er_value=$r['currency_value'];
if(!$er_value){
require_once('modules/Currencies/Currency.php');
$currency  = new Currency();
$currency->retrieve($exchange_rate_id);
$er_value=$currency->conversion_rate;
}
$result = $GLOBALS['db']->query("select * from ecmpricekopias_customview where id='".$_COOKIE['customview_id']."'");
$row=$GLOBALS['db']->fetchByAssoc($result);
$c=explode("||",$row['columns']);
$t=explode("||",$row['titles']);
$lc=0;
foreach($t as $tt)
{
	if($tt!="")$lc++;
}
if($lc>3)
{
	$width=1100;
	$widthl=1020;
	$or="L";
	$title_width=$width-500;
	if($_REQUEST['images']=="true" || (!$_REQUEST['images'] && $_SESSION['pricebook_images_pdf']))
	{
		$l=5;
		$height=100;
		$product_name_width=400;
		if ($lc>=4) $product_name_width = 300;
	}
	else
	{
		$l=8;
		$height=50;
		$product_name_width=500;
	}
}
elseif($lc==0){
	$width=720;
	$widthl=670;
	$or="P";
	$title_width=$width-500;
	if($_REQUEST['images']=="true" || (!$_REQUEST['images'] && $_SESSION['pricebook_images_pdf']))
	{
		$l=8;
		$height=100;
		$product_name_width=620;
	}
	else
	{
		$l=16;
		$height=50;
		$product_name_width=720;
	}
}
else 
{
	$width=720;
	$widthl=670;
	$or="P";
	$title_width=$width-500;
	if($_REQUEST['images']=="true" || (!$_REQUEST['images'] && $_SESSION['pricebook_images_pdf']))
	{
		$l=8;
		$height=100;
		$product_name_width=200;
	}
	else
	{
		$l=16;
		$height=50;
		$product_name_width=300;
	}
}
//if(in_array($c,"name"))@$col_width=($width-$product_name_width)/($lc-1);
//else 
$isname=false;
foreach($c as $ccc){
	if($ccc=="name"){
		$isname=true;
		break;
	}
}
if($isname){
	if($_REQUEST['images']=="true")@$col_width=($width-100-$product_name_width)/($lc-1);
	else @$col_width=($width-$product_name_width)/($lc-1);
}
else{
	if($_REQUEST['images']=="true")@$col_width=($width-100)/$lc;
	else @$col_width=($width)/$lc;
}

$pdf = new HTML2FPDF($or);
$pdf->lMargin = 3; 
$pdf->rMargin = 0; 
$pdf->tMargin = 0; 
$pdf->bMargin = 0; 
$where="";
if(count($_SESSION['pricebook_check'][$_SESSION['pricebook_id']])>0)
{
	foreach($_SESSION['pricebook_check'][$_SESSION['pricebook_id']] as $key=>$value){
		if($_SESSION['pricebook_check'][$_SESSION['pricebook_id']][$key]!="true" && $_SESSION['pricebook_check'][$_SESSION['pricebook_id']]['all']=="true"){
			$where_clauses[]="ecmpricekopias_ecmproducts.id!='".$key."'";
			$orand=' and ';
		}
		elseif($_SESSION['pricebook_check'][$_SESSION['pricebook_id']][$key]=="true" && $_SESSION['pricebook_check'][$_SESSION['pricebook_id']]['all']!="true"){
			$where_clauses[]="ecmpricekopias_ecmproducts.id='".$key."'";
			$orand=' or ';
		}
	}
	if(count($where_clauses)>0)$where="(".implode($orand,$where_clauses).") and ";
	elseif($_SESSION['pricebook_check'][$_SESSION['pricebook_id']]['all']!="true" && count($where_clauses)==0)$where="ecmpricekopias_ecmproducts.id='9999999999999999' and ";
}
else $where="ecmpricekopias_ecmproducts.id='9999999999999999' and ";
//print $where;
$z="select 
ecmpricekopias_ecmproducts.price as price,
ecmpricekopias_ecmproducts.recipient_code as recipient_code,
ecmpricekopias_ecmproducts.id as idp,
ecmpricekopias_ecmproducts.remarks_pl as remarks_pl,
ecmpricekopias_ecmproducts.remarks_en as remarks_en,
ecmpricekopias_ecmproducts.remarks_de as remarks_de,


ecmproducts.*,
if(ecmpricekopias_ecmproducts.price>0,(100-(100*ecmproducts.purchase_price/ecmpricekopias_ecmproducts.price)),0) as margin_rate,

ecmproduct_language_pl_view.ean as ean_pl, 
ecmproduct_language_pl_view.short_description as short_description_pl, 
ecmproduct_language_pl_view.long_description as long_description_pl, 
ecmproduct_language_pl_view.remarks as default_remarks_pl, 

ecmproduct_language_en_view.ean as ean_en, 
ecmproduct_language_en_view.short_description as short_description_en, 
ecmproduct_language_en_view.long_description as long_description_en, 
ecmproduct_language_en_view.remarks as default_remarks_en, 

ecmproduct_language_de_view.ean as ean_de, 
ecmproduct_language_de_view.short_description as short_description_de, 
ecmproduct_language_de_view.long_description as long_description_de, 
ecmproduct_language_de_view.remarks as default_remarks_de 

from ecmpricekopias_ecmproducts

left join ecmproduct_language_pl_view on ecmproduct_language_pl_view.ecmproduct_id=ecmpricekopias_ecmproducts.ecmproduct_id
left join ecmproduct_language_en_view on ecmproduct_language_en_view.ecmproduct_id=ecmpricekopias_ecmproducts.ecmproduct_id
left join ecmproduct_language_de_view on ecmproduct_language_de_view.ecmproduct_id=ecmpricekopias_ecmproducts.ecmproduct_id

left join ecmproducts on ecmproducts.id=ecmpricekopias_ecmproducts.ecmproduct_id 

where ".$where." ecmpricekopias_ecmproducts.ecmpricekopia_id='".$_SESSION['pricebook_id']."' and ecmpricekopias_ecmproducts.deleted='0'";

//$z.="order by ecmproducts.product_category_name asc,ecmpricekopias_ecmproducts.price asc";
if($_SESSION['pricebook_order'])$z.=" order by ".$_SESSION['pricebook_order'];
else
$z.=" order by ecmpricekopias_ecmproducts.position";
$result = $GLOBALS['db']->query($z);
//print mysql_error();
$j=0;
$k=0;
$st=0;
$ile=1 + ceil(($result->num_rows-$l)/($l+1));
while($row=$GLOBALS['db']->fetchByAssoc($result))
{
	$stop[$row['count']]=false;
	$stop[$row['code']]=false;
	$sale30="";
	$qty30="";
	$sale90="";
	$qty90="";
	$sale180="";
	$qty180="";
	if($j==0)
	{
		if ($st==0) {

		$html.='<table border="0" width="'.$width.'"><tr height="140" width="'.$width.'">';
		$html.='<td style="padding-right:0px" height="140" align="center" width="900"><img src="modules/EcmPriceKopias/card_images/topper.jpg" border="0" width="800" height="100"></td>';
		$html.='<td height="140" align="center" width="150"><font color="#808080">'.iconv("UTF-8","ISO-8859-2",$description).'</font></td>';
		$html.='</tr></table>';
		} else {
			$html.='<table border="0" width="'.$width.'"><tr height="40" width="'.$width.'">';
			$html.='<td style="padding-right:0px" height="40" align="center" width="900"><img src="modules/EcmPriceKopias/card_images/cennik.jpg" border="0" width="30" height="30"></td>';
			$html.='<td height="40" align="center" width="150"></td>';
			$html.='</tr></table>';
		}
		if ($st==1) $l++;
		$html.='<table border=1><tr align="center" height="30" width="'.$width.'">';
		if($_REQUEST['images']=="true" || (!$_REQUEST['images'] && $_SESSION['pricebook_images_pdf']))$html.='<td bgcolor="#008CD1" height="30" width="80">&nbsp;</td>';
		//$html.='<td bgcolor="#FF6600" align="center" height="30" width="'.$product_name_width.'"><font color="#ffffff">Product name</font></td>';
		
		for($i=0;$i<count($t);$i++)
		{
			if($c[$i]=="name")$html.='<td bgcolor="#008CD1" align="center" height="30" width="'.$product_name_width.'"><font color="#ffffff">'.$t[$i].'</font></td>';
			elseif($t[$i])$html.='<td bgcolor="#008CD1" align="center" height="30" width="'.$col_width.'"><font color="#ffffff">'.iconv("UTF-8","ISO-8859-2",$t[$i]).'</font></td>';
		}
		$html.='</tr>';
	}
	
	//if ($j % 2 == 1) $bg = 'bgcolor="#EBEDED"'; else $bg='';

	$html.='<tr height="'.$height.'" width="'.$width.'">';
	if($_REQUEST['images']=="true")$html.='<td '.$bg.'  height="'.$height.'" align="left" width="100">';
	if($_REQUEST['images']=="true" && (substr($row['product_picture'],-3,3)=="jpg" || substr($row['product_picture'],-3,3)=="png" || substr($row['product_picture'],-3,3)=="gif" || substr($row['product_picture'],-4,4)=="jpeg") && file_exists("modules/EcmProducts/upload/images/".$row['product_picture']) && $row['product_picture']){
		
		$image_big='modules/EcmProducts/upload/images/'.$row['product_picture'];
		$image_thumb='modules/EcmProducts/upload/images/thumbs/'.$row['product_picture'];
		
		if(!file_exists($image_thumb)){
			$imgo=@GetImageSize($image_big);
			resizeImage($image_big,100,100,$image_thumb,100);
		}
		/*
		$imgo=@GetImageSize($image_big);
		$is=90;
		if($imgo[0]>=$is){
			$widtho=$is;
			$heighto=$imgo[1]*$widtho/$imgo[0];
			if($heighto>$is){
				$heighto=$is;
				$widtho=$imgo[0]*$heighto/$imgo[1];
			}
		}
		else{
			$widtho=$imgo[0];
			$heighto=$imgo[1];
		}*/
		$widtho=90;
		$heighto=84;
		if(file_exists('modules/EcmProducts/upload/images/thumbs/'.$row['product_picture']))$html.='<img src="modules/EcmProducts/upload/images/thumbs/'.$row['product_picture'].'" width='.$widtho.' height='.$heighto.'>';
		else $html.="o";
	}
	if($_REQUEST['images']=="true")$html.='</td>';
	//$html.='<td valign="top" height="'.$height.'" width="'.$product_name_width.'">'.iconv("UTF-8","ISO-8859-2",$row['name']).'</td>';
	/*
	$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select purchase_price from ecmproducts where id='".$row['id']."'"));
	$purchase_price=$rr['purchase_price'];
	@$margin=100-(100*$purchase_price/$row['price']);
	$margin=number_format($margin,2,",",".");*/
	
	for($i=0;$i<count($t);$i++)
	{
		if($t[$i])
		{	  
	  		if(($c[$i]=="sale_qty30" || $c[$i]=="sale_qty90" || $c[$i]=="sale_qty180" || $c[$i]=="sale_avg_price30" || $c[$i]=="sale_avg_price90" || $c[$i]=="sale_avg_price180") && $stop[$row['code']]==false){
				$w=$GLOBALS['db']->query("select ecmproducts_fk_list.price as price,ecmproducts_fk_list.quantity as quantity,ecmproducts_fk_list.date as date from ecmproducts_fk_list where ecmproducts_fk_list.code like '".$row['code']."'");
	  			//echo mysql_error();die();
	  			while($r=$GLOBALS['db']->fetchByAssoc($w)){
					$date=date("Y-m");
					$m=(int)date("m"); 
					$date1=date("Y-m",mktime(0,0,0,($m-1),1,date("Y")));
					$date2=date("Y-m",mktime(0,0,0,($m-2),1,date("Y")));
					$date3=date("Y-m",mktime(0,0,0,($m-3),1,date("Y")));
					$date4=date("Y-m",mktime(0,0,0,($m-4),1,date("Y")));
					$date5=date("Y-m",mktime(0,0,0,($m-5),1,date("Y")));
					$date6=date("Y-m",mktime(0,0,0,($m-6),1,date("Y")));

					$d=explode("-",$r['date']);
			
					$dd=$d[0]."-".$d[1];

					if($dd==$date || $dd==$date1){
	  					$sale30+=$r['price']*$r['quantity'];
						$qty30+=$r['quantity'];
						$aq30[$r['no']]+=$r['quantity'];
					}
					if($dd==$date || $dd==$date1 || $dd==$date2 || $dd==$date3){
	  					$sale90+=$r['price']*$r['quantity'];
						$qty90+=$r['quantity'];
						$aq390[$r['no']]+=$r['quantity'];
					}
					if($dd==$date || $dd==$date1 || $dd==$date2 || $dd==$date3 || $dd==$date4 || $dd==$date5 || $dd==$date6){
	  					$sale180+=$r['price']*$r['quantity'];
						$qty180+=$r['quantity'];
						$aq180[$r['no']]+=$r['quantity'];
					}
	  			}	  
	  			if($qty>0)$sq=round($sale/$qty,2);
	  			if($qty30>0)$sq30=round($sale30/$qty30,2);
	  			else $sq30="";
	  			if($qty90>0)$sq90=round($sale90/$qty90,2);
	  			else $sq90="";
	  			if($qty180>0)$sq180=round($sale180/$qty180,2);
	  			else $sq180="";
				$stop[$row['code']]=true;
	  		}
	  		
	  		//if ($j % 2 == 0) $bg = 'bgcolor="#EBEDED"';
		
			$tds='<td '.$bg.' valign="top" align="center" height="'.$height.'" width="'.$col_width.'">';
			$tde='</td>';
			
			if($c[$i]=="ordered")$html.=$tds.number_format($row['ordered'],0,"","").$tde;
			elseif($c[$i]=="sale_qty30")$html.=$tds.number_format($qty30,0,"","").$tde;
			elseif($c[$i]=="sale_qty90")$html.=$tds.number_format($qty90,0,"","").$tde;
			elseif($c[$i]=="sale_qty180")$html.=$tds.number_format($qty180,0,"","").$tde;
			elseif($c[$i]=="sale_avg_price30")$html.=$tds.number_format($sq30,2,",",".").$tde;
			elseif($c[$i]=="sale_avg_price90")$html.=$tds.number_format($sq90,2,",",".").$tde;
			elseif($c[$i]=="sale_avg_price180")$html.=$tds.number_format($sq180,2,",",".").$tde;
			elseif($c[$i]=="ems_qty_in_stock")$html.=$tds.number_format($row['ems_qty_in_stock'],2,"","").$tde;
			elseif($c[$i]=="list_price")$html.=$tds.iconv("UTF-8","ISO-8859-2",addExchangeRateValue($row['price'],$c[$i],$er_value)).$tde;
			elseif($c[$i]=="margin_rate")$html.=$tds.number_format($row['margin_rate'],2,",",".").$tde;
			elseif($c[$i]=="name"){
				if($lang=="en_us"){
					$html.='<td '.$bg.'  valign="top" height="'.$height.'" width="'.$product_name_width.'">'.iconv("UTF-8","ISO-8859-2",$row['short_description_en']).'</td>';
				}
				elseif($lang=="ge_ge"){
					$html.='<td '.$bg.'  valign="top" height="'.$height.'" width="'.$product_name_width.'">'.iconv("UTF-8","ISO-8859-2",$row['short_description_de']).'</td>';
				}
				else $html.='<td '.$bg.'  valign="top" height="'.$height.'" width="'.$product_name_width.'">'.iconv("UTF-8","ISO-8859-2",$row['name']).'</td>';
			}
			elseif($c[$i]=="product_category_name"){
				if($lang=="en_us"){
					$rrp=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name_en from ecmproductcategories where id='".$row['product_category_id']."'"));
					$html.=$tds.iconv("UTF-8","ISO-8859-2",$rrp['name_en']).$tde;
				}
				elseif($lang=="ge_ge"){
					$rrp=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name_de from ecmproductcategories where id='".$row['product_category_id']."'"));
					$html.=$tds.iconv("UTF-8","ISO-8859-2",$rrp['name_de']).$tde;
				}
				else $html.=$tds.iconv("UTF-8","ISO-8859-2",$row['product_category_name']).$tde;
			}
			else $html.=$tds.iconv("UTF-8","ISO-8859-2",addExchangeRateValue($row[$c[$i]],$c[$i],$er_value)).$tde;
		}
	}
	$html.='</tr>';
	$j++;
	$k++;

	if($j==$l || $result->num_rows==$k)
	{
		$st++;
		$html.='</table>';
		$html.='<table border="0" width="'.$width.'"><tr height="30" width="'.$width.'">';
		$html.='<td height="30" align="left" width="'.$widthl.'"><img src="modules/EcmPriceKopias/card_images/footer.jpg" width="300" height="50"/></td>';
		$html.='<td height="30" align="right" width="80">'.$st.'/'.$ile.'</td>';
		$html.='</tr></table>';
		$ohtml=$html;
		$html='';
		$pdf->AddPage();
		$pdf->WriteHTML($ohtml); 
		$j=0;
	}
}


if($_REQUEST['disposition']=="I")
{
	$pdf->Output("Products.pdf", "I");
}
elseif($_REQUEST['disposition']=="D")
{
	$pdf->Output("Products.pdf", "D");
}
else
{
	$microtime=str_replace(".","",str_replace(" ","",microtime()));
	$pdf->Output("cache/upload/Products".$microtime.".pdf", "F");
}
?>