<?php
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/EcmPurchaseOrders/EcmPurchaseOrder.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/EcmPurchaseOrders/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 EcmPurchaseOrder ();

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 {
	$new_number=true;
	//dates
	$ac=new Account();
	$ac->retrieve('36');
	$address=$ac->getPositionList(true);
	//var_dump($address);
	$focus->parent_shipping_address_name=$ac->name;
	$focus->parent_shipping_address_street=$address[2]['street'];
	$focus->parent_shipping_address_city=$address[2]['city'];
	$focus->parent_shipping_address_postalcode=$address[2]['postalcode'];
	$focus->parent_shipping_address_country=$address[2]['country'];
	$focus->parent_shipping_address_nip=$ac->to_vatid;
	$focus->parent_shipping_name=$ac->name;
	$focus->parent_shipping_id=$ac->id;
	$focus->register_date = date("d.m.Y");
	$OPT ['check_parent_id'] = false;

	// add mz@bim-it.pl 17.03.2023
	if ($_REQUEST['fromProductsBySalesReport']) {
		if (isset($_POST['componentsToOrder'])) {
			$productsToOrder = explode('*', $_POST['componentsToOrder']);
		} else if (isset($_POST['rawMaterialsToOrder'])) {
			$productsToOrder = explode('*', $_POST['rawMaterialsToOrder']);
		}
		$products = [];
		$suppliers = [];
		if (is_array($productsToOrder)) {
			foreach ($productsToOrder as $p) {
				$row = [];
				$row['id'] = create_guid();
				$row['product_component'] = 0;
				$tmp = explode('|',$p);
				$row['ecmproduct_id'] = $tmp[0];
				$row['product_id'] = $tmp[0];
				$row['quantity'] = (!empty($tmp[1])) ? $tmp[1] : 0;
				$res = $db->fetchByAssoc($db->query("
					SELECT name, code, unit_id, usage_unit_name, vat_id, vat_value, vat_name
						FROM ecmproducts WHERE id='".$row['ecmproduct_id']."'"));				
				$row['name'] = $res['name'];
				$row['product_code'] = $res['code'];
				$row['ecmvat_id'] = $res['vat_id'];
				$row['ecmvat_name'] = $res['vat_name'];
				$row['ecmvat_value'] = $res['vat_value'];
				$row['unit_id'] = $res['unit_id'];
				$row['unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$res['unit_id']];
				$row['unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$res['unit_id']];
				// try to get price from PZ
				$price = $db->fetchByAssoc($db->query("select price from ecmstockdocinitems where ecmproduct_id='".$row['ecmproduct_id']."' order by date_entered desc limit 0,1"));
				if (!isset($price)) {
					// try from PW
					$price = $db->fetchByAssoc($db->query("select price from ecmstockdocinsideinitems where ecmproduct_id='".$row['ecmproduct_id']."' order by date_entered desc limit 0,1"));
				}
				if (isset($price)) {
					$row['price_start'] = $price['price'];
				}
				// check last supplier
				$supplier = $db->fetchByAssoc($db->query("SELECT d.parent_id, d.parent_name
															FROM ecmstockdocinitems AS i
															INNER JOIN ecmstockdocins AS d
															ON d.id = i.ecmstockdocin_id
															WHERE i.ecmproduct_id = '".$row['ecmproduct_id']."'
															ORDER BY d.register_date DESC 
															LIMIT 0,1"));
				if ($supplier && supplierExists($suppliers, $supplier['parent_id']) == null) {
					$a = $db->fetchByAssoc($db->query("SELECT id, name, to_vatid, billing_address_street, billing_address_city,
														billing_address_postalcode, billing_address_country, currency_id
														FROM accounts WHERE id='".$supplier['parent_id']."'"));
					$suppliers[] = $a;
				}
				$products[] = $row;
			}
		}
		if (count($suppliers) == 1) {
			$focus->parent_id = $suppliers[0]['id'];
			$focus->parent_name = $suppliers[0]['name'];
			$focus->parent_nip = $suppliers[0]['to_vatid'];
			$focus->parent_address_street = $suppliers[0]['billing_address_street'];
			$focus->parent_address_city = $suppliers[0]['billing_address_city'];
			$focus->parent_address_postalcode = $suppliers[0]['billing_address_postalcode'];
			$focus->parent_address_country = $suppliers[0]['billing_address_country'];
			$focus->currency_id = $suppliers[0]['currency_id'];
		}
	}
}

//get stocks
$res = $db->query("SELECT id, name FROM ecmstocks WHERE deleted = '0' ORDER BY name");
$stock_pw = '<select id="stock_pw" name="stock_pw"><option value=""></option>';
$stock_rw = '<select id="stock_rw" name="stock_rw"><option value=""></option>';
$stock_body = '';
while ($row = $db->fetchByAssoc($res)) 
	$stock_body.='<option value="'.$row['id'].'">'.$row['name'].'</option>';
$stock_pw.=$stock_body.'</select><input id="pw_stock_id" name="pw_stock_id" type="hidden"/>';
$stock_rw.=$stock_body.'</select><input id="rw_stock_id" name="rw_stock_id" type="hidden"/>';

// get employers
$earr=array(

        'Darek' => 'Darek',
        'Helena' => 'Helena',
        'Emila' => 'Emila',
        'Bogusia Serymoch' => 'Bogusia Serymoch',
        'Marcin Popławski' => 'Marcin Popławski',
);
foreach($earr as $ea){
    $eas.='<option value="'.$ea.'"';
    if(in_array($ea,explode("|",$rdoc['employers'])))$eas.=' selected';
    $eas.='>'.$ea.'</option>';
}


require_once ('include/MVC/View/SugarView.php');
require_once ('modules/EcmPurchaseOrders/views/EditView/view.edit.ecmpurchaseorders.php');
$edit = new ViewEditEcmPurchaseOrders ();
$edit->ss = new Sugar_Smarty ();
$edit->module = 'EcmPurchaseOrders';
$edit->bean = $focus;
$edit->tplFile = 'include/ECM/EcmViews/EditView/Tabs/EditView.tpl';
$edit->preDisplay ();
$edit->ss->assign ( "NEW_NUMBER", $new_number );
$edit->ss->assign("DUPLICATE", $duplicate);
$edit->ss->assign("STOCK_PW", $stock_pw);
$edit->ss->assign("STOCK_RW", $stock_rw);
$edit->ss->assign("EMPLOYERS", $eas);
if (isset($products)) {
	$edit->ss->assign("POSITION_LIST", str_replace('"', "'", json_encode($products)));
}
echo $edit->display ();
//loading view
echo '<link rel="stylesheet" type="text/css" href="modules/EcmPurchaseOrders/javascript/helper.css" media="screen" /><div class="loading_panel"></div>';

// helper
function supplierExists($array, $value) {
    for ($i=0; $i<count($array); $i++) {
        if ($array[$i]['parent_id'] == $value) {
            return true;
        }
    }
    return null;
}