<?php 
if(!defined('sugarEntry') || !sugarEntry) die('-1');
if (!$_POST['job'] || $_POST['job']=='') die ('-1');
switch ($_POST['job']) {
	case 'getParentInfo': getParentInfo($_POST['id'], $_POST['type']); break;
	case 'generateNumber': generateNumber(); break;
	case 'searchProducts': searchProducts($_POST['searchKey'], $_POST['searchCategory'], $_POST['searchStock'], $_POST['searchSort'], $_POST['searchStockId']); break;
	case 'getProduct': getProduct($_POST['id'], $_POST['pricebook'], $_POST['account_id'], $_POST['language']); break;
	case 'getItems': getItems($_POST['record']); break;
	case 'getItemsFromEdi': getItemsFromEdi($_POST['record']); break;
	case 'getItemsFromQuote': getItemsFromQuote($_POST['record']); break;
	case 'getCategoriesList': getCategoriesList(); break;
	case 'getTranslation': getTranslation($_POST['product_id'], $_POST['language'], $_REQUEST['unit_id']); break;
	case 'getPricesInfo': getPricesInfo($_POST['product_id'], $_POST['pricebook_id'], $_POST['account_id']); break;
	case 'getStockArray' : getStockArray($_POST['product_id']); break;
	case 'getPurchaseArray' : getPurchaseArray($_POST['product_id']); break;
	case 'calculateDate' : calculateDate($_POST['date']); break;
	case 'validateDate' : validateDate($_POST['date'],$_POST['date2']); break;
	case 'saveSaleItemDescription' : saveSaleItemDescription($_POST['saleItemId'], $_POST['description']); break;
}

function calculateDate($date){
	$date = new Datetime($date);
	$date->modify('-1 day');
	$tmp['date']=$date->format("d.m.Y");
	echo json_encode($tmp);
	return '';
}
function validateDate($date,$date2){
	$date = new Datetime($date);
	$date2= new Datetime($date2);
	
	if($date>$date2){
		echo json_encode(['error'=>true]);
	} else {
		echo json_encode(['error'=>false]);
	}
	return '';
}
function getParentInfo($id, $type) {
	if (!$id || $id == '') die('-1');
	
		$a = new Account();
		$a->retrieve($id);		
		$data = array();
		$data['name'] = $a->name;
		$data['parent_nip'] = $a->to_vatid;
		$data['parent_address_street'] = $a->billing_address_street;
		$data['parent_address_postalcode'] = $a->billing_address_postalcode;
		$data['parent_address_city'] = $a->billing_address_city;
		$data['parent_address_country'] = $a->billing_address_country;
		$data['invoice_type'] = $a->invoice_type;		
		$data['currency_id'] = $a->currency_id;	
		$data['iln'] = $a->iln;
		$data['parent_supplier_code'] = $a->supplier_code;
		if ($a->ecmpaymentcondition_id && $a->ecmpaymentcondition_id!='') {
			$pc = new EcmPaymentCondition();
			$pc->retrieve($a->ecmpaymentcondition_id);
			$data['ecmpaymentcondition_id'] = $pc->id;
			$data['ecmpaymentcondition_name'] = $pc->name;
		}
		if ($a->ecmdeliverycondition_id && $a->ecmdeliverycondition_id!='') {
			$pc = new EcmdeliveryCondition();
			$pc->retrieve($a->ecmdeliverycondition_id);
			$data['ecmdeliverycondition_id'] = $pc->id;
			$data['ecmdeliverycondition_name'] = $pc->name;
		}
		
		if ($a->ecmprice_id && $a->ecmprice_id!='') {
			$pr = new EcmPrice();
			$pr->retrieve($a->ecmprice_id);
			$data['ecmprice_id'] = $pr->id;
			$data['ecmprice_name'] = $pr->name;
		}
		//get pricebooks, ownership pricebooks
		$pricebooks = array();
		$db=$GLOBALS['db'];
		$res = $db->query("SELECT id, name FROM ecmpricebooks WHERE account_id IN ('".$a->id."','".$a->parent_id."') AND active='1' AND deleted='0'");
		while ($row = $db->fetchByAssoc($res)) {
			$tmp = array();
			$tmp['id'] = $row['id'];
			$tmp['name'] = $row['name'];
			$pricebooks[] =  $tmp;
			unset($tmp);
		}
		$data['pricebooks'] = $pricebooks;
		//document validation fields
		$data['document_recipient_code'] = $a->document_recipient_code;
		$data['document_parent_order_no'] = $a->document_parent_order_no;
		$data['document_delivery_address'] = $a->document_delivery_address;
		$data['document_parent_iln'] = $a->document_parent_iln;
		$data['document_shipping_iln'] = $a->document_shipping_iln;
		$data['document_parent_nip'] = $a->document_parent_nip;
		$data['document_shipping_nip'] = $a->document_shipping_nip;
		
		//delivery addresses && ownership addresses
		$addresses = array();
		//delivery
		$delivery = $a->getPositionList(true);
		foreach ($delivery as $d) {
			$address = array();
			$address['name'] = $d['name'];
			$address['street'] = $d['street'];
			$address['postalcode'] = $d['postalcode'];
			$address['city'] = $d['city'];
			$address['country'] = $d['country'];
			$addresses[] = $address;
			unset($address);
		}
		//ownership
		$res = $db->query("SELECT name, shipping_address_street, shipping_address_postalcode, shipping_address_city, shipping_address_country, iln, to_vatid  FROM accounts WHERE parent_id='$a->id'");
		while ($r = $db->fetchByAssoc($res)) {
			$address = array();
			$address['name'] = $r['name'];
			$address['street'] = $r['shipping_address_street'];
			$address['postalcode'] = $r['shipping_address_postalcode'];
			$address['city'] = $r['shipping_address_city'];
			$address['country'] = $r['shipping_address_country'];
			$address['iln'] = $r['iln'];
			$address['nip'] = $r['to_vatid'];
			$addresses[] = $address;
			unset($address);
		}
				
		$data['addresses'] = $addresses;
		unset($addresses);
		
		echo json_encode($data);
		unset($data);
		unset($a);
		unset($res);
		return;
}	
function generateNumber() {
	$data = array();
	$data['number'] = EcmSale::generateNumber();
	$data['document_no'] = EcmSale::formatNumber($data['number']);
	echo json_encode($data);
	unset($data);
	return;
}
function searchProducts($searchKey, $searchCategory, $searchStock, $searchSort,$stockid) {
	
	$db = $GLOBALS['db'];
	$q = "SELECT id, code, name FROM ecmproducts WHERE
					(UPPER(code) LIKE '%$searchKey%' OR
					UPPER(name) LIKE '%$searchKey%' OR
					ean LIKE '%$searchKey%' OR
					ean2 LIKE '%$searchKey%')
					AND deleted='0' ";
	if ($searchCategory && $searchCategory!="")
		$q.="AND product_category_id='$searchCategory' ";
	
	if ($searchSort=='1')
		$q.="ORDER BY code";
	else if ($searchSort=='2')
		$q.="ORDER BY code DESC";
	else if ($searchSort=='3')
		$q.="ORDER BY name";
	else if ($searchSort=='4')
		$q.="ORDER BY name DESC";
	
	$q.=" LIMIT 0,50";
	
	$res = $db->query($q);
	$result = array();
	
	if ($searchStock!='1') {
		//get main stock id
		$stock_res = $db->fetchByAssoc($db->query("SELECT id FROM ecmstocks WHERE main='1' LIMIT 0,1"));
		$stock_id = $stock_res['id'];
	}
	while ($row = $db->fetchByAssoc($res)) {
		$tmp = array();
		$tmp['id'] = $row['id'];
		$tmp['name'] = $row['name'];
		$tmp['code'] = $row['code'];
		
		//get stock if necessary
		if ($searchStock!='1') {
		    if($stockid!='')$stock_id=$stockid;
			$tmp['stock_state'] = EcmStockOperation::getStock($row['id'], $stock_id);
		}
		
		if ($searchStock=='3' && $tmp['stock_state']==0) continue; //don't show null stock
		
		$result[] = $tmp;
	}
	echo json_encode($result);
	return;
}
function getProduct($id, $pricebook_id, $account_id, $language) {
	$db = $GLOBALS['db'];
	$p = $db->fetchByAssoc($db->query("SELECT p.id, p.code, p.name, v.id as ecmvat_id, v.name as ecmvat_name, v.value as ecmvat_value, p.ean, p.ean2, p.unit_id, p.brand_label FROM ecmproducts as p INNER JOIN ecmvats as v ON v.id=p.vat_id WHERE p.id='$id'"));	
	global $app_list_strings;
	$p['unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$p['unit_id']];	
	//try get recipient_code and price from pricebook
	if ($pricebook_id && $pricebook_id!='') {
		$pr = $db->fetchByAssoc($db->query("SELECT price, recipient_code FROM ecmpricebooks_ecmproducts WHERE ecmpricebook_id='$pricebook_id' AND ecmproduct_id='$id' AND deleted='0'"));
		$p['price_start'] = $pr['price'];
		$p['recipient_code'] = $pr['recipient_code'];
	}
	if (!$p['price_start'] || floatval($p['price_start'])==0) {
		//try price from default prices
		$pr = $db->fetchByAssoc($db->query("SELECT pp.price FROM ecmprices_ecmproducts AS pp INNER JOIN ecmprices AS p ON pp.ecmprice_id=p.id INNER JOIN accounts AS a ON p.id=a.ecmprice_id WHERE a.id='$account_id' AND pp.ecmproduct_id='$id'"));
		$p['price_start'] = $pr['price'];
	}
	$ecmStockOperations = new EcmStockOperation();
	
	$p['reservation']=($ecmStockOperations->getRealStock($p ['id']));

	
	
	if ($language=='en_us') {
		$r = $db->fetchByAssoc($db->query("SELECT short_description FROM ecmproduct_language WHERE ecmproduct_id='$id' AND language='en'"));
		$p['name'] = htmlspecialchars_decode($r['short_description']);
		
		$lists = return_app_list_strings_language($language);
		$p['unit_name'] = $lists['ecmproducts_unit_dom'][$p['unit_id']];
		unset($lists);
	}
	echo json_encode($p);
	return;
}
function getItems($record) {
	$of = new EcmSale();
	$of->retrieve($record);
	$pl = $of->getPositionList(true);	
	unset($of);
	echo json_encode($pl);
	return;
}
function getItemsFromEdi($record) {
	require_once ('modules/EcmSales/readXML.php');
	$reader=New readXML();
	$reader->loadXMLFile($record);
	$pl = $reader->getPositionList(true);
	unset($reader);
	echo json_encode($pl);
	return;
}
function getItemsFromQuote($record) {
  
	$s = new EcmQuote();
	$s->retrieve($record);
	
	$pl = $s->getPositionList(true);
	unset($s);
	echo json_encode($pl);
	return;
}
function getCategoriesList() {
	$db = $GLOBALS['db'];
	$res = $db->query("SELECT id, name FROM ecmproductcategories WHERE deleted='0'");
	$result = array();
	while ($row = $db->fetchByAssoc($res)) {
		$tmp = array();
		$tmp['id'] = $row['id'];
		$tmp['name'] = $row['name'];
		$result[] = $tmp;
	}
	echo json_encode($result);
	return;
}
function getTranslation($product_id, $language, $unit_id) {
	$db = $GLOBALS['db'];
	$result = array();
	if ($language=='en_us') {
		$r = $db->fetchByAssoc($db->query("SELECT short_description FROM ecmproduct_language WHERE ecmproduct_id='$product_id' AND language='en'"));
		$result['name'] = htmlspecialchars_decode($r['short_description']);			
	} else if ($language=='pl_pl') {
		$p = new EcmProduct();
		$p->retrieve($product_id);
		$result['name'] = htmlspecialchars_decode($p->name);
		unset($p);
	}
	$lists = return_app_list_strings_language($language);
	$result['unit_name'] = $lists['ecmproducts_unit_dom'][$unit_id];
	unset($lists);
	
	echo json_encode($result);
	return;
}
function getPricesInfo($product_id, $pricebook_id, $account_id) {
	$db = $GLOBALS['db'];
	
	$result = array();
	if ($pricebook_id && $pricebook_id!='') {
		//try get price from pricebook
		$res = $db->fetchByAssoc($db->query("SELECT price FROM ecmpricebooks_ecmproducts WHERE ecmpricebook_id='$pricebook_id' AND ecmproduct_id='$product_id' AND deleted='0'"));
		if ($res['price'] && $res['price']!='' && $res['price']!=0) {
			$tmp = array();
			$tmp['name'] = 'pricebook';
			$tmp['price'] = $res['price'];			
			$result[] = $tmp;
		}
	}
	
	//get from ecmprices
	$res = $db->query("SELECT p.name, pp.price FROM ecmprices_ecmproducts AS pp 
					   INNER JOIN ecmprices AS p
					   ON p.id=pp.ecmprice_id
					   WHERE
					   pp.ecmproduct_id='$product_id'
					   AND pp.price!=0");
	while ($row = $db->fetchByAssoc($res)) {
		$tmp = array();
		$tmp['name'] = $row['name'];
		$tmp['price'] = $row['price'];
		$result[] = $tmp;
	}
	
	//get last invoice price
	if ($account_id && $account_id!='') {
		$res = $db->fetchByAssoc($db->query("SELECT ii.subprice, i.id, i.document_no FROM ecminvoiceoutitems AS ii
										     INNER JOIN ecminvoiceouts AS i
											 ON ii.ecminvoiceout_id=i.id
											 WHERE ii.ecmproduct_id='$product_id'
											 AND i.parent_id='$account_id'
											 AND ii.deleted='0'
											 AND i.deleted='0'
											 AND i.canceled='0'
											 ORDER BY i.register_date DESC
											 LIMIT 0,1"));
		if ($res && $res['subprice']!='') {
			$tmp = array();
			$tmp['name'] = $res['document_no'];
			$tmp['price'] = $res['subprice'];
			$result[] = $tmp;
		}
	}
	
	echo json_encode($result);
	return;
}
function getStockArray($product_id) {
	$o = new EcmStockOperation();
	echo json_encode($o->getStockArray($product_id));
	unset($o);
	return;
}
function getPurchaseArray($product_id) {
	$o = new EcmStockOperation();
	echo json_encode($o->getPurchaseArray($product_id));
	unset($o);
	return;
}
function saveSaleItemDescription($saleItemId, $description) {
	$db=$GLOBALS['db'];
	$description = mysql_escape_string($description);
	$db->query("UPDATE ecmsaleitems SET description='$description' WHERE id='$saleItemId'");
	echo "OK";
	return;
}