<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*****************************************************************************
 * The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
 * Version 1.1 ("License"); You may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/rpl.php. Software distributed under the
 * License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied.
 *
 * You may:
 * a) Use and distribute this code exactly as you received without payment or
 *    a royalty or other fee.
 * b) Create extensions for this code, provided that you make the extensions
 *    publicly available and document your modifications clearly.
 * c) Charge for a fee for warranty or support or for accepting liability
 *    obligations for your customers.
 *
 * You may NOT:
 * a) Charge for the use of the original code or extensions, including in
 *    electronic distribution models, such as ASP (Application Service
 *    Provider).
 * b) Charge for the original source code or your extensions other than a
 *    nominal fee to cover distribution costs where such distribution
 *    involves PHYSICAL media.
 * c) Modify or delete any pre-existing copyright notices, change notices,
 *    or License text in the Licensed Software
 * d) Assert any patent claims against the Licensor or Contributors, or
 *    which would in any way restrict the ability of any third party to use the
 *    Licensed Software.
 *
 * You must:
 * a) Document any modifications you make to this code including the nature of
 *    the change, the authors of the change, and the date of the change.
 * b) Make the source code for any extensions you deploy available via an
 *    Electronic Distribution Mechanism such as FTP or HTTP download.
 * c) Notify the licensor of the availability of source code to your extensions
 *    and include instructions on how to acquire the source code and updates.
 * d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
 *    reproduce, perform, modify, sublicense, and distribute your extensions.
 *
 * The Original Code is: CommuniCore
 *                       Olavo Farias
 *                       2006-04-7 olavo.farias@gmail.com
 *
 * The Initial Developer of the Original Code is CommuniCore.
 * Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
 * All Rights Reserved.
 ********************************************************************************/

require_once('modules/EcmProductB2Bs/EcmProductB2B.php');
require_once('include/formbase.php');
require_once('include/Upload.php');

function addLocalizedInformation($id)
{
	global $db;
	$lang=array("en","de","pl");
	foreach($lang as $l)
	{
		if (!$_REQUEST['short_description_'.$l] || $_REQUEST['short_description_'.$l]=='')
			$_REQUEST['short_description_'.$l] = '&nbsp';
		$result=$GLOBALS['db']->query("select ecmproduct_id from ecmproduct_language where ecmproduct_id='".$id."' and language like '".$l."'");
		if($result->num_rows>0)
		{
			$GLOBALS['db']->query("update ecmproduct_language set ean='".$_REQUEST['ean']."',remarks='".$_REQUEST['remarks_'.$l]."',short_description='".$_REQUEST['short_description_'.$l]."',long_description='".$_REQUEST['long_description_'.$l]."',modified_user_id='".$_SESSION['authenticated_user_id']."',date_modified='".date("Y-m-d H:i:s")."',price='".$_REQUEST['price_'.$l]."' where ecmproduct_id='".$id."' and language='".strtolower($l)."'");
		}
		else
		{
			$GLOBALS['db']->query("insert into ecmproduct_language set id='".create_guid()."',created_by='".$_SESSION['authenticated_user_id']."',modified_user_id='".$_SESSION['authenticated_user_id']."',date_entered='".date("Y-m-d H:i:s")."',date_modified='".date("Y-m-d H:i:s")."',deleted='0',ean='".$_REQUEST['ean']."',remarks='".$_REQUEST['remarks_'.$l]."',short_description='".$_REQUEST['short_description_'.$l]."',long_description='".$_REQUEST['long_description_'.$l]."',language='".strtolower($l)."',ecmproduct_id='".$id."',price='".$_REQUEST['price_'.$l]."'");
		}
	}
}
$focus = new EcmProductB2B();

$focus->retrieve($_POST['record']);
if(!$focus->ACLAccess('Save')){
		ACLController::displayNoAccess(true);
		sugar_cleanup(true);
}



//add mz 2012-04-10
//check ean
//include("/modules/EcmProductB2Bs/generateEAN.php");
//if ($_POST['newEan']=="1") $focus->ean=generateEAN();
//if ($_POST['newEan2']=="1") $focus->ean2=generateEAN();
//$_REQUEST['name']="test";

//categories
$pll = array();
$json = getJSONobj();
$exp=explode("||||",$_POST['position_list3']);
foreach($exp as $ep){
	if($ep){
		$pll[] = $json->decode(htmlspecialchars_decode($ep));
	}
}
$_POST['position_list3'] = $pll;

$pll = array();
$json = getJSONobj();
$exp=explode("||||",$_POST['position_list4']);
foreach($exp as $ep){
	if($ep){
		$pll[] = $json->decode(htmlspecialchars_decode($ep));
	}
}
$_POST['position_list4'] = $pll;



include('modules/EcmProductB2Bs/SimpleImage.php');
if($_FILES['product_picture']['name']){
	$_POST['product_picture']=upload_file("product_picture","modules/EcmProductB2Bs/upload/images/");
	$img="modules/EcmProductB2Bs/upload/images/".$_POST['product_picture'];
	copy($img,"modules/EcmProductB2Bs/upload/images/big/".$_POST['product_picture']);
	chmod("modules/EcmProductB2Bs/upload/images/big/".$_POST['product_picture'],0777);
	$size=getSize($img,125);
	$image = new SimpleImage();
	$image->load($img);
	$image->resize($size[0],$size[1]);
	$image->save($img);
	
}
chmod($img,0777);
if($_FILES['packing_front_picture']['name']){
	$_POST['packing_front_picture']=upload_file("packing_front_picture","modules/EcmProductB2Bs/upload/images/");
	$img="modules/EcmProductB2Bs/upload/images/".$_POST['packing_front_picture'];
	copy($img,"modules/EcmProductB2Bs/upload/images/big/".$_POST['packing_front_picture']);
	chmod("modules/EcmProductB2Bs/upload/images/big/".$_POST['packing_front_picture'],0777);
	$size=getSize($img,125);
	$image = new SimpleImage();
	$image->load($img);
	$image->resize($size[0],$size[1]);
	$image->save($img);
}
chmod($img,0777);
if($_FILES['driver_1']['name'])$_POST['driver_1']=upload_file("driver_1","modules/EcmProductB2Bs/upload/");
if($_FILES['driver_2']['name'])$_POST['driver_2']=upload_file("driver_2","modules/EcmProductB2Bs/upload/");
chmod("modules/EcmProductB2Bs/upload/".$_POST['driver_1'],0777);
chmod("modules/EcmProductB2Bs/upload/".$_POST['driver_2'],0777);

if($_REQUEST['delete_product_picture']){
	$_POST['product_picture']=$_REQUEST['product_picture']="";
}
if($_REQUEST['delete_packing_front_picture']){
	$_POST['packing_front_picture']=$_REQUEST['packing_front_picture']="";
}

if($_REQUEST['delete_driver_1']){
	$_POST['driver_1']=$_REQUEST['driver_1']="";
}
if($_REQUEST['delete_driver_2']){
	$_POST['driver_2']=$_REQUEST['driver_2']="";
}

if (!empty($_POST['assigned_user_id']) && ($focus->assigned_user_id != $_POST['assigned_user_id']) && ($_POST['assigned_user_id'] != $current_user->id)) {
	$check_notify = TRUE;
}else{
	$check_notify = FALSE;
}

foreach($focus->column_fields as $field){
	if(isset($_POST[$field])){
		$value = $_POST[$field];
		$focus->$field = $value;
	}
}
foreach($focus->additional_column_fields as $field){
	if(isset($_POST[$field])){
		$value = $_POST[$field];
		$focus->$field = $value;
	}
}

		if (!isset($_POST[product_active])) {
		 $focus->product_active = '0';
		}else{
		 $focus->product_active = '1';
		}
		if (!isset($_POST[certificate_of_origin])) {
		 $focus->certificate_of_origin = '0';
		}else{
		 $focus->certificate_of_origin = '1';
		}
		if (!isset($_POST[form_a])) {
		 $focus->form_a = '0';
		}else{
		 $focus->form_a = '1';
		}
		
//Added for Graduated Prices - Begin
	/*require_once('modules/EcmProductB2Bs/EcmProductB2BGraduatedPrices.php');
	$epgp = new EcmProductB2BGraduatedPrices();
	$epgp->setFromPost();
	$focus->graduated_prices = $epgp->toString();*/
//Added for Graduated Prices - End

require_once('modules/Currencies/Currency.php');
$currency = new Currency();
$currency_list = $currency->get_full_list('conversion_rate');
$currency->retrieve('-99');
if(is_array($currency_list))$currency_list = array_merge(Array($currency), $currency_list);
else $currency_list = Array($currency); 
$arr = array();
foreach($currency_list as $key=>$value)$arr[$value->id] = $value->conversion_rate;

$erv=$arr[$_REQUEST['exchange_rate_id']];
$focus->unformat_all_fields();

$focus->carton_volume_meter=$focus->carton_dimensions_1*$focus->carton_dimensions_2*$focus->carton_dimensions_3;

$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select local_transportation,abroad_transportation from ecmproductcategories where id='".$_REQUEST['product_category_id']."'"));
$lt=$r['local_transportation'];
$at=$r['abroad_transportation'];
if($focus->pieces_per_carton!=0)$pcscbm=$focus->carton_volume_meter/$focus->pieces_per_carton;
else $pcscbm=1;
if(!$_REQUEST['purchase_price']){

	$customduty=($focus->fob_price+$at*$pcscbm)*($erv*$focus->custom_duty_rate/100);
	$focus->purchase_price=$focus->fob_price*$erv+$customduty+$lt*$pcscbm;
}

if(!$_REQUEST['commission_rate']){
	$rv=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value from ecmvats where id='".$_REQUEST['vat_id']."'"));
	$focus->commission_rate=100*(($focus->srp_price/(1+$rv['value']/100)-$focus->purchase_price)/($focus->srp_price/(1+$rv['value']/100)));
}
$rpp=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select ems_price from ecmproducts where id='".$focus->id."'"));

$focus->save($check_notify);
$GLOBALS['db']->query("update ecmproducts set ems_price='".$rpp['ems_price']."' where id='".$focus->id."'");
$return_id = $focus->id;

if(isset($_POST['vat_id'])){
	$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value,name from ecmvats where id='".$_POST['vat_id']."'"));
	$GLOBALS['db']->query("update ecmproducts set ean='".$_REQUEST['ean']."',vat_value='".$r['value']."',vat_name='".$r['name']."',product_active='".$_REQUEST['product_active']."',status='".$_REQUEST['status']."' where id='".$return_id."'");
}
$models=base64_encode(serialize($_REQUEST['models']));
$GLOBALS['db']->query("update ecmproducts set models='".$models."',status='".$_REQUEST['status']."' where id='".$return_id."'");

addLocalizedInformation($return_id);

$image=true;
$desc=true;
if(!file_exists("modules/EcmProductB2Bs/upload/images/big/".$focus->product_picture) || !$focus->product_picture)$image=false;
if(!file_exists("modules/EcmProductB2Bs/upload/images/big/".$focus->packing_front_picture) || !$focus->packing_front_picture)$image=false;
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select ean,remarks,short_description,long_description,language,price from ecmproduct_language where language='pl' and ecmproduct_id='".$return_id."'"));
if(!$r['ean'] || !$r['short_description'] || !$r['long_description'] || !$r['price'])$desc=false;

if(!$image && !$desc)$type="images_and_description";
elseif(!$image && $desc)$type="images";
elseif($image && !$desc)$type="description";
else $type="ok";

$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select type from ecmproducts_log where ecmproduct_id='".$return_id."' and sent is null order by date_entered desc limit 1"));
if($r['type']!=$type){
$GLOBALS['db']->query("insert into ecmproducts_log(id,date_modified,date_entered,created_by,modified_user_id,ecmproduct_id,type) values('".create_guid()."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".$_SESSION['authenticated_user_id']."','".$_SESSION['authenticated_user_id']."','".$return_id."','".$type."');");
}
handleRedirect($return_id,'EcmProductB2Bs');

?>