<?php

if (!defined('sugarEntry') || !sugarEntry)
    die('Not A Valid Entry Point');

require_once('include/json_config.php');
$json_config = new json_config();
$ss = new Sugar_Smarty();

global $mod_strings;
$db = $GLOBALS['db'];

if ($_REQUEST['uid']) {
    //check parents
    $documents = explode(',', $_REQUEST['uid']);
    $pid = '';
    $stock_id = '';
    $first = true;
    $wh_doc = array();
    if (sizeof($documents) == 0) {
        echo 'No document selected';
        return;
    }
    foreach ($documents as $doc) {
        $r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT parent_id, stock_id FROM ecmservices WHERE id='" . $doc . "'"));
        if (!$first) {
            if ($r['parent_id'] != $pid && $r['stock_id'] != $sid) {
                echo 'Can\'t create: diffrent accounts.';
                return;
            }
        }
        else
            $pid = $r['parent_id'];
        $sid = $r['stock_id'];
        $stock_id = $r['stock_id'];
        $first = false;
        if ($doc != '')
            $wh_doc[] = "doc.id='" . $doc . "' ";
    }
    $query = "SELECT item.ecmproduct_id, item.id as itemid, item.name, item.code, item.price, item.discount, item.quantity, item.ecmservice_id, doc.document_no, doc.stock_id, item.product_type FROM ecmserviceitems as item INNER JOIN ecmservices as doc ON doc.id=item.ecmservice_id";
    if (isset($wh_doc))
        $query.=" AND (" . implode(" OR ", $wh_doc) . ")";
    $query.=' ORDER BY doc.document_no ASC';

    $result = $GLOBALS['db']->query($query);

    $temp_doc_id = create_guid();
    $result_table = array();
    $i = 0;
    while ($r = $GLOBALS['db']->fetchByAssoc($result)) {
        $tmp = array();
        $temp_item_id = create_guid();

        include_once("modules/EcmStockOperations/EcmStockOperation.php");
        $op = new EcmStockOperation();
        $tmp['stock'] = $op->getStock($r['ecmproduct_id'], $r['stock_id']);

        $tmp['res'] = $op->getServiceReservations($r['ecmservice_id'], $r['ecmproduct_id']);

        if ($r['quantity'] == $tmp['res']) {
            $qq = $r['quantity'];
        } else {
            if ($tmp['stock'] >= $r['quantity'] - $tmp['res']) {
                $qq = $r['quantity'];
                //temp reservation quantity - reservation
                $temp_res_qty = $r['quantity'] - $tmp['res'];
                $op->saveReservation($r['stock_id'], $r['ecmproduct_id'], $temp_doc_id, $temp_item_id, $temp_res_qty);
            } elseif ($tmp['stock'] < $r['quantity'] - $tmp['res'] && $tmp['stock'] > 0) {
                $qq = $tmp['res'] + $tmp['stock'];
                //temp reservation
                $temp_res_qty = $tmp['stock'];
                $op->saveReservation($r['stock_id'], $r['ecmproduct_id'], $temp_doc_id, $temp_item_id, $temp_res_qty);
            } else {
                //only reservation
                $qq = $r['res'];
            }
        }

        $tmp['id'] = $r['ecmproduct_id'];
        $tmp['code'] = $r['code'];
        $tmp['name'] = $r['name'];
        $tmp['price'] = $r['price'];
        $tmp['document_no'] = $r['document_no'];
        $tmp['quantity'] = $qq;
        $tmp['temp_item_id'] = $temp_item_id;
        $tmp['temp_date'] = date("Y-m-d H:i:s");
        $tmp['type'] = $r['product_type'];
        $tmp['service_qty'] = $r['quantity'] - $qq;
        $tmp['service_rq'] = $tmp['res'];
        $tmp['service_id'] = $r['ecmservice_id'];
        $tmp['service_item_id'] = $r['itemid'];
        $tmp['stock'] = $op->getStock($r['ecmproduct_id'], $r['stock_id']);
        $result_table[] = $tmp;
    }
    $file = 'modules/EcmGroupServices/EcmGroupService.php';
    if (file_exists($file)) {
        $cc = array();
        require_once($file);
        $cc = EcmGroupService::loadSettings();
    }
    $OPT = array();
    $OPT['row_item_height'] = $cc['row_item_height'];
    $OPT['row_item_height_selected'] = $cc['row_item_height_selected'];
    $OPT['rows_on_item_list'] = $cc['rows_on_item_list'];
    $OPT['position_table_height'] = $OPT['row_item_height'] * $OPT['rows_on_item_list'] + 40 + $OPT['rows_on_item_list'] * 4;
    $OPT['quick_product_item_adding'] = $cc['quick_product_item_adding'];
    $ss->assign("OPT", $OPT);
    $ss->assign("POSITION_LIST", $json->encode($result_table));
    $ss->assign("MOD", $mod_strings);
    $ss->assign("TEMP_ID", $temp_doc_id);
    $ss->assign("STOCK_ID", $stock_id);

    $scriptOpt = '<script language="javascript">
        var OPT = ' . str_replace('&quot;', '\"', $json->encode($OPT)) . ';
        var MOD = ' . str_replace('&quot;', '\"', $json->encode($mod_strings)) . ';
		var N;
   </script>';
    echo $scriptOpt;

    if (file_exists('modules/EcmServices/views/realizationList.tpl'))
        echo $ss->display('modules/EcmServices/views/realizationList.tpl');
    else
        echo 'Can\'t find template!';
}
?>