<?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/EcmInsideOrders/EcmInsideOrder.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>';

// $cq=$current_user->getPreference('confirm_quotes');

$new_number = false;
$duplicate = false;
$focus = new EcmInsideOrder ();

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
	$focus->register_date = date("d.m.Y");
	$OPT ['check_parent_id'] = false;

    // add mz@bim-it.pl 11.11.2023
    $products = [];
	if ($_REQUEST['fromProductsBySalesReport']) {
        $requestProducts = explode('*', $_POST['insideOrderProducts']);
        if (is_array($requestProducts)) {
            $position = 0;
			foreach ($requestProducts as $p) {
				$row = [];
				$row['id'] = create_guid();
				$row['product_component'] = 0;
				$tmp = explode('|',$p);
				$row['product_id'] = $tmp[0];
                $row['position'] = $position;
                $position++;
				$row['quantity'] = (!empty($tmp[1])) ? floatval($tmp[1]) : 0;
                $prodQty = $row['quantity'];
                $row['quantity_comp'] = 0;

				$res = $db->fetchByAssoc($db->query("
					SELECT name, code, unit_id, product_category_id 
						FROM ecmproducts WHERE id='".$row['product_id']."'"));	
                    
				$row['name'] = $res['name'];
				$row['product_code'] = $res['code'];
                $row['ecmproductcategory_id'] = $res['product_category_id'];
				$row['unit_id'] = $res['unit_id'];
                $row['unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$row['unit_id']];
                $products[] = $row;

                $components = $db->query("SELECT * FROM ecmproductcomponents WHERE deleted=0 AND ecmproduct_id='".$row['product_id']."'");
                while ($c = $db->fetchByAssoc($components)) {
                    $row = [];
                    $row['id'] = create_guid();
                    $row['product_component'] = 1;
                    $tmp = explode('|',$p);
                    $row['product_id'] = $c['ecmcomponent_id'];
                    $row['position'] = $position;
                    $position++;
                    $row['quantity_comp'] = floatval($c['quantity']);
                    $row['quantity'] = $prodQty * $row['quantity_comp'];
                        
                    $res = $db->fetchByAssoc($db->query("
                        SELECT name, code, unit_id, product_category_id 
                            FROM ecmproducts WHERE id='".$row['product_id']."'"));	
                        
                    $row['name'] = $res['name'];
                    $row['product_code'] = $res['code'];
                    $row['ecmproductcategory_id'] = $res['product_category_id'];
                    $row['unit_id'] = $res['unit_id'];
                    $row['unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$row['unit_id']];
                    $products[] = $row;
                }
            }
        }
    }
}

//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 = '';
$stock_body2 = '';
while ($row = $db->fetchByAssoc($res)){
    if($focus->rw_stock_id==$row['id']){
        $s='selected';
    } else {
        $s='';
    }
    if($focus->pw_stock_id==$row['id']){
        $s2='selected'; 
    } else {
        $s2='';
    }
	$stock_body.='<option value="'.$row['id'].'" '.$s2.'>'.$row['name'].'</option>';
	$stock_body2.='<option value="'.$row['id'].'" '.$s.'>'.$row['name'].'</option>';
}
$stock_pw.=$stock_body.'</select><input id="pw_stock_id" name="pw_stock_id" type="hidden"/>';
$stock_rw.=$stock_body2.'</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/EcmInsideOrders/views/EditView/view.edit.ecminsideorders.php');
$edit = new ViewEditEcmInsideOrders ();
$edit->ss = new Sugar_Smarty ();
$edit->module = 'EcmInsideOrders';
$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/EcmInsideOrders/javascript/helper.css" media="screen" /><div class="loading_panel"></div>';