<?
set_time_limit(50);
require_once("modules/EcmPriceBooks/ListHelper.php");
//$GLOBALS['db']->query("SET NAMES 'utf8' COLLATE 'utf8_polish_ci'");

$result = $GLOBALS['db']->query("select * from ecmpricebooks_customview where id='".$_GET['customview_id']."'");
$row=$GLOBALS['db']->fetchByAssoc($result);
$c=explode("||",$row['columns']);
$t=explode("||",$row['titles']);
$o=explode("||",$row['orders']);

if($_COOKIE['customview_id']!=$_GET['customview_id'] || $_SESSION['customview_id']=="" || !$_GET['order_by'])
{
	$pbo=array();
	for($i=0;$i<=8;$i++)
	{
		if($o[$i])
		{
			$exp=explode(" ",$o[$i]);
			$adesc=$exp[1];
			$ord=$exp[0];
			if($ord=="list_price")$pbo[]="ecmpricebooks_ecmproducts.price ".$adesc;
			else $pbo[]="ecmproducts.".$ord." ".$adesc;
		}
	}
	$_SESSION['pricebook_order']=implode(",",$pbo);
}
setcookie('customview_id',$_GET['customview_id'],time()+60*24*60*3600);

$order=$_SESSION['pricebook_order'];
$order=str_replace("ecmproducts.margin_rate","margin_rate",$order);
if($_REQUEST['order_by']){
	$order=str_replace($_REQUEST['order_by']." desc",$_REQUEST['order_by']." ".$_REQUEST['sorder'],$order);
	$order=str_replace($_REQUEST['order_by']." asc",$_REQUEST['order_by']." ".$_REQUEST['sorder'],$order);
}

$_SESSION['pricebook_order']=$order;

if($_REQUEST['order_by'] && $_REQUEST['sorder'])$_SESSION['pricebook_order']=$_REQUEST['order_by']." ".$_REQUEST['sorder'];

//if($_REQUEST['order_by'])$_SESSION['pricebook_order_by']=$_SESSION['pricebook_order']=$_REQUEST['order_by'];
//$_SESSION['pricebook_sorder']=$_REQUEST['sorder'];
$_SESSION['pricebook_sorder']=$_REQUEST['sorder'];
$_COOKIE['pricebook_id']=$_REQUEST['pricebook_id'];


$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name,exchange_rate_id,ecmlanguage,currency_value from ecmpricebooks where id='".$_COOKIE['pricebook_id']."'"));
$name=$r['name'];
$exchange_rate_id=$r['exchange_rate_id'];
$lang=$r['ecmlanguage'];
$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;
}
$sorder=$_REQUEST['sorder'];
$result = $GLOBALS['db']->query("select ecmpricebooks_ecmproducts.price as price,ecmpricebooks_ecmproducts.id as idp,ecmproducts.* from ecmpricebooks_ecmproducts left join ecmproducts on ecmproducts.id=ecmpricebooks_ecmproducts.ecmproduct_id where ecmpricebooks_ecmproducts.ecmpricebook_id='".$_COOKIE['pricebook_id']."' and ecmpricebooks_ecmproducts.deleted='0'");
$checkc='';
	$checkc.='if(document.getElementById(\'checkin\').checked==true)
	{
		mintajaxget(\'index.php?to_pdf=1&module=EcmPriceBooks&action=checkAllProducts&pricebook_id='.$_REQUEST['pricebook_id'].'&value=true\',\'checkin\');
	}
	else
	{
		mintajaxget(\'index.php?to_pdf=1&module=EcmPriceBooks&action=checkAllProducts&pricebook_id='.$_REQUEST['pricebook_id'].'&value=false\',\'checkin\');
	}';
while($ro=$GLOBALS['db']->fetchByAssoc($result))
{
	
	$checkc.='if(document.getElementById(\'checkin\').checked==true)
	{
		document.getElementById(\'checkc'.$ro['idp'].'\').checked=true;
	}
	else
	{
		document.getElementById(\'checkc'.$ro['idp'].'\').checked=false;
	}
	';
}
print '</tr>';
$z="select 
ecmpricebooks_ecmproducts.price as price,
ecmpricebooks_ecmproducts.popular as popular,
ecmpricebooks_ecmproducts.recipient_code as recipient_code,
ecmpricebooks_ecmproducts.id as idp,
ecmpricebooks_ecmproducts.margin_rate,
ecmpricebooks_ecmproducts.position as position,
ecmpricebooks_ecmproducts.remarks_pl as remarks_pl,
ecmpricebooks_ecmproducts.remarks_en as remarks_en,
ecmpricebooks_ecmproducts.remarks_de as remarks_de,
ecmproducts.*,

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 ecmpricebooks_ecmproducts

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

left join ecmproducts on ecmproducts.id=ecmpricebooks_ecmproducts.ecmproduct_id 

where ecmpricebooks_ecmproducts.ecmpricebook_id='".$_REQUEST['pricebook_id']."' and ecmpricebooks_ecmproducts.deleted='0'";

$tmp = substr(trim($_SESSION['pricebook_order']), -1);
if ($tmp!='.')
		if($_SESSION['pricebook_order'])$z.=" order by ".$_SESSION['pricebook_order'];

//$z.=" COLLATE utf8_polish_ci";
//print $z;


if ($_REQUEST['customview_id']=='4cf54ba0-db9b-dc0d-e781-522f24a92e60') {
$ttttt = '
		<br><br>
<form action="index.php?module=EcmPriceBooks&action=updatePrices&record='.$_REQUEST['pricebook_id'].'" method="post">
Marża:&nbsp<input id="margin" name="margin" type="text" value="0"/>&nbsp
Rabat:&nbsp<input id="discount" name="discount" type="text" value="0"/>&nbsp
Cena z VAT:&nbsp<input id="with_tax" name="with_tax" type="checkbox"/>&nbsp
Rodzaj przeliczania:
<select id="type" name="type"/>
<option value="1">Od dołu</option>
<option value="2">Od góry</option>
</select> 
<input type="submit" value="Przelicz ceny"/>
<br><br>
</form>
';
echo $ttttt;
}

$result = $GLOBALS['db']->query($z);
include_once("modules/EcmProductReports/vtigerConnector.php");
$count = $result->num_rows;
while($row=$GLOBALS['db']->fetchByAssoc($result))
{
if ($licz%100==0 && $licz>0) {
print '</table>';
print '<input type="submit" name="save_prices" class="button" value="Save">';
print '</form>';
}
if ($licz%100==0) {
print '<form action="index.php?module=EcmPriceBooks&action=SavePrices&record='.$_REQUEST['pricebook_id'].'" method="post">';
print '<table cellpadding="0" cellspacing="0" width="100%" border="0" class="ListView"><tr>';
print '<td class="listViewThS1" width="1%"><input type="checkbox" id="checkin" value="true" onclick="'.$checkc.'"';
if($_SESSION['pricebook_check'][$_REQUEST['pricebook_id']]['all']=="true"){print ' checked';}
print '></td>';
print '<td class="listViewThS1">'.sortLink("ecmpricebooks_ecmproducts.position",$sorder,"Pos.").'</td>';
//print  mysql_error();
$t[1]='Nazwa';
$t[2]='Kategoria';
for($i=0;$i<count($t);$i++)
{
	$corder_by="ecmproducts.".$c[$i];
	if($c[$i]=="list_price")$corder_by="ecmpricebooks_ecmproducts.price";
	
	if($c[$i]=="ean_pl")$corder_by="ecmproduct_language_pl_view.ean";
	if($c[$i]=="short_description_pl")$corder_by="ecmproduct_language_pl_view.short_description";
	if($c[$i]=="long_description_pl")$corder_by="ecmproduct_language_pl_view.long_description";
	if($c[$i]=="default_remarks_pl")$corder_by="ecmproduct_language_pl_view.remarks";
	
	if($c[$i]=="remarks_pl")$corder_by="ecmpricebooks_ecmproducts.remarks_pl";
	
	if($c[$i]=="ean_en")$corder_by="ecmproduct_language_en_view.ean";
	if($c[$i]=="short_description_en")$corder_by="ecmproduct_language_en_view.short_description";
	if($c[$i]=="long_description_en")$corder_by="ecmproduct_language_en_view.long_description";
	if($c[$i]=="default_remarks_en")$corder_by="ecmproduct_language_en_view.remarks";
	
	if($c[$i]=="remarks_en")$corder_by="ecmpricebooks_ecmproducts.remarks_en";
	
	if($c[$i]=="ean_de")$corder_by="ecmproduct_language_de_view.ean";
	if($c[$i]=="short_description_de")$corder_by="ecmproduct_language_de_view.short_description";
	if($c[$i]=="long_description_de")$corder_by="ecmproduct_language_de_view.long_description";
	if($c[$i]=="default_remarks_de")$corder_by="ecmproduct_language_de_view.remarks";
	
	if($c[$i]=="remarks_de")$corder_by="ecmpricebooks_ecmproducts.remarks_de";
	
	if($c[$i]=="margin_rate")$corder_by="margin_rate";
	
	if($c[$i]=="sale_qty30")$corder_by="name";
	if($c[$i]=="sale_qty90")$corder_by="name";
	if($c[$i]=="sale_qty180")$corder_by="name";
	if($c[$i]=="sale_avg_price30")$corder_by="name";
	if($c[$i]=="sale_avg_price90")$corder_by="name";
	if($c[$i]=="sale_avg_price180")$corder_by="name";

	
	
	if($t[$i])print '<td class="listViewThS1">'.sortLink($corder_by,$sorder,$t[$i]).'</td>';
}
$mm=$mod_strings;
print '<td class="listViewThS1" width="1%">Popularność</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_UNIT_PRICE'].'</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_MARGIN'].'</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_LIST_PRICE_PRICEBOOK'].'</td>';
print '<td class="listViewThS1" width="1%">Cena brutto</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_RECIPIENT_CODE'].'</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_REMARKS_PL'].'</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_REMARKS_EN'].'</td>';
print '<td class="listViewThS1" width="1%">'.$mm['LBL_REMARKS_DE'].'</td>';
print '<td class="listViewThS1" width="1%">&nbsp;</td>';
print '<td class="listViewThS1" width="1%">&nbsp;</td>';
print '<td class="listViewThS1" width="1%">&nbsp;</td>';
}

	$stop[$row['code']]=false;
	$sale30="";
	$qty30="";
	$sale90="";
	$qty90="";
	$sale180="";
	$qty180="";
	if($_SESSION['EcmPriceBooks_high'][$row['idp']])$color="#cccccc";
	else $color="";
	$licz++;
	print '<tr id="row'.$row['idp'].'" style="background:'.$color.'">';

	print '<td class="oddListRowS1"><input type="hidden" id="check'.$row['idp'].'"><input id="checkc'.$row['idp'].'" onclick="mintajaxget(\'index.php?to_pdf=1&module=EcmPriceBooks&action=checkProduct&record='.$row['idp'].'&pricebook_id='.$_REQUEST['pricebook_id'].'&value=\'+this.checked,\'check'.$row['idp'].'\');" type="checkbox" name="check[]" value="'.$row['idp'].'"';
	if($_SESSION['pricebook_check'][$_REQUEST['pricebook_id']]['all']=="true" || $_SESSION['pricebook_check'][$_REQUEST['pricebook_id']][$row['idp']]=="true")print ' checked';
	print '></td>';
	print '<td class="oddListRowS1">'.($row['position']).'</td>';
	//print '<td class="oddListRowS1"><a href="index.php?module=EcmProducts&action=DetailView&record='.$row['id'].'">'.$row['name'].'</a></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){
				$ddate=date("Y-m-d",mktime()-200*24*3600);

				$w=$GLOBALS['db']->query("select ecminvoiceoutitems.price as price,ecminvoiceoutitems.quantity as quantity,ecminvoiceouts.register_date as date from ecminvoiceoutitems inner join ecminvoiceouts on ecminvoiceoutitems.ecminvoiceout_id=ecminvoiceouts.id where ecminvoiceoutitems.ecmproduct_id='".$row['id']."' and ecminvoiceouts.type!='correct' and ecminvoiceouts.register_date>'".$ddate."'");
	  			while($r=$GLOBALS['db']->fetchByAssoc($w)){
	  				$sale+=$r['price']*$r['quantity'];
					$qty+=$r['quantity'];
					$aq[$r['no']]+=$r['quantity'];
					
					$date=date("Y-m");
			
					$date1=date("Y-m",mktime()-1*24*3600*31);
					$date2=date("Y-m",mktime()-2*24*3600*31);
					$date3=date("Y-m",mktime()-3*24*3600*31);
					$date4=date("Y-m",mktime()-4*24*3600*31);
					$date5=date("Y-m",mktime()-5*24*3600*31);
					$date6=date("Y-m",mktime()-6*24*3600*31);

					$d=explode("-",$r['date']);
			
					$dd=$d[0]."-".$d[1];
					if($dd==$date6){
						//echo 3;
						$qty_6+=$r['quantity'];
					}
			
					if($dd==$date5){
						//echo 3;
						$qty_5+=$r['quantity'];
					}
			
					if($dd==$date4){
						//echo 3;
						$qty_4+=$r['quantity'];
					}
			
					if($dd==$date3){
						//echo 3;
						$qty_3+=$r['quantity'];
					}
			
					if($dd==$date2){
						//echo 2;
						$qty_2+=$r['quantity'];
					}
			
					if($dd==$date1){
						//echo 1;
						$qty_1+=$r['quantity'];
					}

					if($dd==$date){
	  					$sale0+=$r['price']*$r['quantity'];
						$qty0+=$r['quantity'];
						$aq0[$r['no']]+=$r['quantity'];
					}
					if($dd==$date1){
	  					$sale30+=$r['price']*$r['quantity'];
						$qty30+=$r['quantity'];
						$aq30[$r['no']]+=$r['quantity'];
					}
					if($dd==$date1 || $dd==$date2 || $dd==$date3){
	  					$sale90+=$r['price']*$r['quantity'];
						$qty90+=$r['quantity'];
						$aq90[$r['no']]+=$r['quantity'];
					}
					if($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'];
					}
			    }
	  
	  
	 			@$trend_6_5=$qty_5/$qty_6;
	  			@$trend_5_4=$qty_4/$qty_5;
	  			@$trend_4_3=$qty_3/$qty_4;
	  			@$trend_3_2=$qty_2/$qty_3;
	 			@$trend_2_1=$qty_1/$qty_2;
		
				$trend=($qty_1+$qty_2+$qty_3)/3;
			
				$qty__1=$trend;
				$qty__2=$trend;
				$qty__3=$trend;
			
	  			if($qty__1<0)$qty__1=0;
	  			if($qty__2<0)$qty__2=0;
	  			if($qty__3<0)$qty__3=0;
				
				$stop[$row['code']]=true;
	  		}
		
		
			print '<td class="oddListRowS1">';
			if($c[$i]=="ordered")print number_format($row['ordered'],0,"","");
			elseif($c[$i]=="sale_qty30")print number_format($qty30,0,"","");
			elseif($c[$i]=="sale_qty90")print number_format($qty90/3,0,"","");
			elseif($c[$i]=="sale_qty180")print number_format($qty180/6,0,"","");
			elseif($c[$i]=="sale_avg_price30")print number_format($sale30,2,",",".");
			elseif($c[$i]=="sale_avg_price90")print number_format($sale90,2,",",".");
			elseif($c[$i]=="sale_avg_price180")print number_format($sale180,2,",",".");
			elseif($c[$i]=="ems_qty_in_stock")print number_format($row['ems_qty_in_stock'],0,"","");
			elseif($c[$i]=="list_price")print addExchangeRateValue($row['price'],$c[$i],$er_value);
			elseif($c[$i]=="margin_rate")print number_format($row['margin_rate'],2,",",".");
			elseif($c[$i]=="name"){
				if($lang=="en_us"){
					if($row['short_description_en'])print '<a href="index.php?module=EcmProducts&action=DetailView&record='.$row['id'].'">'.$row['short_description_en'].'</a>';
					else print '<a href="index.php?module=EcmProducts&action=DetailView&record='.$row['id'].'">none</a>';
				}
				elseif($lang=="ge_ge"){
					if($row['short_description_de'])print '<a href="index.php?module=EcmProducts&action=DetailView&record='.$row['id'].'">'.$row['short_description_de'].'</a>';
					else print '<a href="index.php?module=EcmProducts&action=DetailView&record='.$row['id'].'">none</a>';
				}
				else print '<a href="index.php?module=EcmProducts&action=DetailView&record='.$row['id'].'">'.$row['name'].'</a>';
			}
			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']."'"));
					if($rrp['name_en'])print $rrp['name_en'];
				}
				elseif($lang=="ge_ge"){
					$rrp=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name_de from ecmproductcategories where id='".$row['product_category_id']."'"));
					if($rrp['name_de'])print $rrp['name_de'];
				}
				else print $row['product_category_name'];
				print '&nbsp;<a target="_blank" href="index.php?record='.$_REQUEST['pricebook_id'].'&to_pdf=1&action=generateCategoryContent&module=EcmProducts&category_id='.$row['product_category_id'].'&category_name='.$row['product_category_name'].'&lang='.$lang.'"><img src="themes/default/images/PDFlanguages.gif" border="0" /></a>';
			}
			else print addExchangeRateValue($row[$c[$i]],$c[$i],$er_value);
			
			print '</td>';
		}
	}
	


	
	
	
 if($row['popular']==1)$po_checked="checked";
 else $po_checked="";
  print '<td>
  <input size="8" id="popular_'.$licz.'" name="popular_'.$licz.'" readonly type="checkbox" value="1" '.$po_checked.'/>
  </td>
  <td>
  <input size="8" id="purchase_price_'.$licz.'" name="purchase_price_'.$licz.'" readonly type="text" onchange="getPricePricebook();" onclick="getPricePricebook();" onblur="getPricePricebook();" value="'.number_format($row['purchase_price'],2,",",".").'" />
  </td>
  <td>
  <input size="4" id="margin_'.$licz.'" name="margin_'.$licz.'" type="text" onchange="getPricePricebook();" onclick="getPricePricebook();" onblur="getPricePricebook();" value="'.number_format($row['margin_rate'],2,",",".").'" />
  </td>
  <td>
  <input size="8" id="price_'.$licz.'" name="price_'.$licz.'" type="text" onchange="getPricePricebook();" onclick="getPricePricebook();" onblur="getPricePricebook();" value="'.number_format($row['price'],2,",",".").'" />
  </td>
  <td>
  <input size="8" id="price_brutto_'.$licz.'" name="price_brutto_'.$licz.'" type="text" onchange="getPricePricebook();" onclick="getPricePricebook();" onblur="getPricePricebook();" value="'.number_format(($row['price']*(1+$row['vat_value']/100)),2,",",".").'" />
  </td>
  <td>
  <input size="8" id="recipient_code_'.$licz.'" name="recipient_code_'.$licz.'" type="text" value="'.$row['recipient_code'].'" />
  </td>
  <td>
  <input size="8" id="remarks_pl_'.$licz.'" name="remarks_pl_'.$licz.'" type="text" value="'.$row['remarks_pl'].'" />
  </td>
  <td>
  <input size="8" id="remarks_en_'.$licz.'" name="remarks_en_'.$licz.'" type="text" value="'.$row['remarks_en'].'" />
  </td>
  <td>
  <input size="8" id="remarks_de_'.$licz.'" name="remarks_de_'.$licz.'" type="text" value="'.$row['remarks_de'].'" />
  </td>
  <td>
  <input id="product_id_'.$licz.'" name="product_id_'.$licz.'" type="hidden" value="'.$row['idp'].'" /></td>';	
	
	
	print '<td class="oddListRowS1">
	<a id="edit'.$row['id'].'" style="cursor:pointer;" onclick="document.getElementById(\'row'.$row['idp'].'\').style.background=\'#e6e6e6\';showdiv(\'edit'.$row['id'].'\',\'price-block\',80,240);showprice(\''.$row['id'].'\',\''.number_format($row['price'],2,",",".").'\',\''.number_format($row['purchase_price'],2,",",".").'\',\''.number_format($row['margin_rate'],2,",",".").'\',\''.$row['remarks_pl'].'\',\''.$row['remarks_en'].'\',\''.$row['remarks_de'].'\',\''.$_REQUEST['order_by'].'\',\''.$_REQUEST['sorder'].'\',\''.$row['recipient_code'].'\');"><img src="themes/Sugar/images/edit_inline.gif" border="0"></a>';
	print '<td class="oddListRowS1">
	<a id="delete'.$row['id'].'" style="cursor:pointer;" onclick="if(confirm(\''.$mod_strings['LBL_QUESTION_DELETE'].'\')){mintajaxget(\'index.php?to_pdf=1&module=EcmPriceBooks&action=deleteProductFromPriceBook&id='.$row['idp'].'\',\'row'.$row['idp'].'\');document.getElementById(\'row'.$row['idp'].'\').style.display=\'none\';}"><img src="themes/Sugar/images/delete_inline.gif" border="0"></a>
	</td>';
	print '</tr>';
if ($licz==$count) {
print '</table>';
print '<input type="submit" name="save_prices" class="button" value="Save">';
print '</form>';
}
}



//print '</table>';
print '<div style="text-align:left"><br><input class="button" value="Delete" name="delete" type="button" onclick="if(confirm(\'Are You sure?\'))location.href=\'index.php?module=EcmPriceBooks&action=DeleteFromPriceBook&but=1&return_id='.$_COOKIE['pricebook_id'].'\';"></div>';

?>
