<?php
//ini_set('display_errors',1); 

if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( 'NotAValidEntryPoint' );

global $sugar_version, $sugar_config, $current_user, $app_strings, $mod_strings, $current_user, $app_list_strings;
require_once ('modules/EcmStockDocOuts/EcmStockDocOut.php');
require_once ('include/time.php');

$db = $GLOBALS['db'];

//add jquery
echo '<link rel="stylesheet" type="text/css" href="include/jQuery/jquery-table/jquery.appendGrid-1.3.1.css"/>';
echo '<link rel="stylesheet" type="text/css" href="include/jQuery/jquery-ui/themes/base/jquery-ui.css"/>';
echo '<script type="text/javascript"
src="include/jQuery/jquery-2.1.0.min.js"></script>';
echo '<script type="text/javascript"
src="include/jQuery/jquery-table/jquery.appendGrid-1.3.1.js"></script>';
echo '<script type="text/javascript"
src="include/jQuery/jquery-ui/ui/jquery-ui.js"></script>';
echo '<script type="text/javascript"
src="modules/EcmStockDocOuts/javascript/searchcolumndefs.js"></script>';
echo '<script type="text/javascript"
src="include/ECM/SearchProductTable.js"></script>';
echo '<script type="text/javascript"
src="include/ECM/tablenavigator.js"></script>';
// $cq=$current_user->getPreference('confirm_quotes');

$new_number = false;
$duplicate = false;
$focus = new EcmStockDocOut ();
require_once ('include/MVC/View/SugarView.php');
require_once ('modules/EcmStockDocOuts/views/EditView/view.edit.ecmstockdocouts.php');
$edit = new ViewEditEcmStockDocOuts ();
$edit->ss = new Sugar_Smarty ();
$edit->module = 'EcmStockDocOuts';
$edit->bean = $focus;
$edit->tplFile = 'include/ECM/EcmViews/EditView/Tabs/EditView.tpl';
$edit->preDisplay ();

if (isset ( $_REQUEST ['record'] ) && $_REQUEST['isDuplicate']=="false" ) {
	$focus->retrieve ( $_REQUEST ['record'] );	
	if (isset ( $focus->id ) && $focus->id != '') {
		$focus->format_all_fields ();		
	}
} 
else if ($_REQUEST['isDuplicate']=="true") {
	$new_number=true;
	$duplicate=true;
	//get data
	$focus->retrieve($_REQUEST['return_id']);
}
else if ($_REQUEST['parent_doc_type']!="true" && $_REQUEST['parent_doc_id']!="") {
	$new_number=true;
	$ecmsale=true;
	$s= New EcmSale();
	$s->retrieve($_REQUEST['parent_doc_id']);
	$focus->parent_name=$s->parent_name;
	$focus->parent_id=$s->parent_id;
	$focus->shipping_address_name=$s->shipping_address_name;
	$focus->shipping_address_street=$s->shipping_address_street;
	$focus->shipping_address_postalcode=$s->shipping_address_postalcode;
	$focus->shipping_address_city=$s->shipping_address_city;
	$focus->shipping_address_country=$s->shipping_address_country;
	$focus->parent_iln=$s->parent_iln;
	$focus->order_no=$s->parent_document_no;
	$focus->register_date = date("d.m.Y");
	$focus->delivery_date = $s->delivery_date;
	$focus->stock_id=$s->stock_id || '754a59d6-979f-7006-a202-57c96a3eb06b';;
	$focus->so_id=$_REQUEST['parent_doc_id'];

    if ($s->order_source == 'allegro') {
        $focus->stock_id = 'cf16804e-f698-5e09-2da3-6553588446ae';
    }
	
	//get data
	
} else if (isset($_REQUEST['ecommerceWZ'])) {
	$new_number=true;
	$focus->stock_id = 'cf16804e-f698-5e09-2da3-6553588446ae';
	$focus->register_date = date("d.m.Y");
	$focus->parent_id = 'b5612f7f-85e5-f930-293e-62cead14b424';
	$db = $GLOBALS['db'];
	$invoiceIds = $_SESSION[$_REQUEST['ecommerceWZ']];
	$i = $db->fetchByAssoc($db->query("SELECT register_date FROM ecommerce_invoices WHERE id = '$invoiceIds[0]'"));
	$focus->delivery_date = date('d.m.Y', strtotime($i['register_date']));

	$query = "
	SELECT ip.ecmproduct_id, SUM(ip.quantity) AS quantity, ip.price_netto, p.code, p.name, p.unit_id
FROM ecommerce_invoices_products AS ip
INNER JOIN ecmproducts AS p ON ip.ecmproduct_id = p.id
WHERE invoice_id IN ('".implode('\',\'', $invoiceIds)."')
AND ip.ecmproduct_id NOT IN ('', '165f364e-9301-25ac-5906-58e38f1de4ca')
GROUP BY ip.ecmproduct_id, ip.price_netto;
	";
	$res = $db->query($query);
	$products = array();
	$position = 1;
	while ($row = $db->fetchByAssoc($res)) {
		$products[] = array(
			'position' => $position++,
			'product_id' => $row['ecmproduct_id'],
			'product_code' => $row['code'],
			'name' => $row['name'],
			'quantity' => $row['quantity'],
			'price_netto' => $row['price_netto'],
			'unit_id' => $row['unit_id'],
			'unit_name' => $app_list_strings['ecmproducts_unit_dom'][$row['unit_id']],
			'ecmvat_name' => '23%',
			'ecmvat_value' => 23,
			'ecmvat_id' => '28079566-b825-e38f-9993-4ccc7b781de5',
		);
	}
	$edit->ss->assign('ECOMMERCE_PRODUCTS', json_encode($products));
	$edit->ss->assign('ECOMMERCE_INVOICES', json_encode($invoiceIds));
	$focus->ecommerce_invoices = $invoiceIds;

	$query = "SELECT document_no FROM ecommerce_invoices WHERE id IN ('".implode('\',\'', $invoiceIds)."')";
	$res = $db->query($query);
	$documentNos = array();
	while ($row = $db->fetchByAssoc($res)) {
		$documentNos[] = $row['document_no'];
	}
	$focus->pdf_text = "Dotyczy faktur: ".implode(', ', $documentNos);
} else if (isset($_REQUEST['amazonWZ'])) {
	$new_number=true;
	$focus->stock_id = 'add8ef6f-3d1f-5ccf-c486-64719142f096';
	$focus->register_date = date("d.m.Y");
	$focus->parent_id = '63cb11a5-5304-086e-bf87-651c216d5641';
	$focus->currency_id = '6336d9a0-ee5f-52e3-7d0c-4e6f1472b2bf';
	$db = $GLOBALS['db'];
	$products = $_SESSION[$_REQUEST['amazonWZ']];
	$edit->ss->assign('ECOMMERCE_PRODUCTS', json_encode($products));

} else if (isset($_REQUEST['fromPZ'])) {
	$new_number=true;
	$pz = new EcmStockDocIn();
	$pz->retrieve($_REQUEST['fromPZ']);
	$focus->parent_name=$pz->parent_name;
	$focus->parent_id=$pz->parent_id;
	$focus->stock_id=$pz->stock_id;
	$focus->register_date = date("d.m.Y");
	$focus->delivery_date = date("d.m.Y");
	$focus->pdf_text = "Dotyczy PZ: ".$pz->document_no;
	$pzPositions = $pz->getPositionList(true);
	$products = array();
	foreach ($pzPositions as $position) {
		$products[] = array(
			'position' => $position['position'],
			'product_id' => $position['product_id'],
			'product_code' => $position['product_code'],
			'name' => $position['name'],
			'quantity' => $position['quantity'],
			'price_netto' => $position['price'],
			'unit_id' => $position['unit_id'],
			'unit_name' => $position['unit_name'],
			'ecmvat_name' => $position['ecmvat_name'],
			'ecmvat_value' => $position['ecmvat_value'],
			'ecmvat_id' => $position['ecmvat_id'],
		);
	}
	$edit->ss->assign('ECOMMERCE_PRODUCTS', json_encode($products));
} else {
	$new_number=true;
	//dates
	$focus->stock_id=$current_user->stock_id;
	$focus->register_date = date("d.m.Y");
	$focus->stock_id=$current_user->stock_id;
	$OPT ['check_parent_id'] = false;
}

//get stocks
$res = $db->query("SELECT id, name FROM ecmstocks WHERE deleted = '0' ORDER BY name");
$stock = '<select id="stock" name="stock"><option value=""></option>';
$stock_body = '';
while ($row = $db->fetchByAssoc($res)) {
	if($row['id']==$focus->stock_id){$selected='selected';} else {
	$selected='';}
	$stock_body.='<option value="'.$row['id'].'" '.$selected.'>'.$row['name'].'</option>';
	}
$stock.=$stock_body.'</select><input id="stock_id" name="stock_id" type="hidden" value="'.$focus->stock_id.'"/>';
//includ OO VAT
$v = new EcmVat();
$v->retrieve('a8c52d5e-15df-2a13-c934-5578307bebd2');
$oo = array ('id' => 'a8c52d5e-15df-2a13-c934-5578307bebd2', 'name' => strtoupper($v->name), 'value' =>strtoupper($v->value));
echo '<script> var OO=\''.json_encode($oo).'\'</script>';


$edit->ss->assign ("NEW_NUMBER", $new_number );
$edit->ss->assign("DUPLICATE", $duplicate);
$edit->ss->assign("ECMSALE", $ecmsale);
$edit->ss->assign("ECMSALE_ID",$_REQUEST['parent_doc_id']);
$edit->ss->assign("STOCK", $stock);

echo $edit->display ();
//loading view
echo '<link rel="stylesheet" type="text/css" href="modules/EcmStockDocOuts/javascript/helper.css" media="screen" /><div class="loading_panel"></div>';