<?php

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

global $sugar_config, $current_user, $mod_strings, $current_user, $app_list_strings;

// include_once('modules/EcmQuotes/EcmQuote.php');
require_once('modules/EcmKpkw/EcmKpkw.php');
// require_once('modules/EcmKpkw/Forms.php');
require_once('include/json_config.php');

$json_config = new json_config();

// $file = 'modules/EcmGroupKpkw/EcmGroupKpkw.php';
// if (file_exists($file)) {
    // $cc = array();
    // require_once($file);
    // $cc = EcmGroupKpkw::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'];
$OPT['check_parent_id'] = true;
$cq = $current_user->getPreference('confirm_quotes');
$OPT['user']['confirm_quotes'] = ((isset($cq) && $cq) ? 1 : 0);

$focus = new EcmKpkw();

$OPT['auto_commiting'] = $focus->ACLAccess('auto_commiting');
echo 'test'.$focus->table_name;

if (isset($_REQUEST['record'])) {



    $focus->retrieve($_REQUEST['record']);
    if (isset($focus->id) && $focus->id != '') {
        if ($focus->accepted == 1) {
		

            return;
        }

        $focus->format_all_fields();

        // $focus->position_list = str_replace('&quot;', '\'', $focus->getPositionList());
        // $focus->Kpkw_list = str_replace('&quot;', '\'', $focus->getKpkwPositionList());
        // $focus->income_list = str_replace('&quot;', '\'', $focus->getIncomePositionList());

        if (!isset($focus->status) || $focus->status == '')
            $focus->status = 's10';
        elseif ($focus->status = 's40')
            $focus->status = 's10';
            
        //$focus->deleteReservations();
        // $focus->unreserve();
        
        $OPT['save_temp_reservations'] = true;
    }
}
else {

    $OPT['new_number'] = true;
    $focus->status = 'registered';
}
$OPT['new_number'] = true;
if ($_REQUEST['ecmquote_id']) {
    $quo = new EcmQuote();
    $quo->retrieve($_REQUEST['ecmquote_id']);

    $arr = array('parent_id', 'parent_name', 'status', 'name', 'register_date', 'currency_id', 'template_id', 'validtill_date', 'is_vat_free', 'to_vatid', 'ecmlanguage', 'parent_address_street', 'parent_address_city', 'parent_address_postalcode', 'parent_address_country', 'parent_name_copy', 'parent_contact_name', 'parent_contact_title', 'show_primary_params', 'show_advanced_params');

    foreach ($arr as $a) {
        $focus->$a = $quo->$a;
    }
}

$OPT['user']['access']['send_email'] = $focus->ACLAccess('send_email');
$OPT['old_status'] = (isset($focus->status) && $focus->status != '') ? $focus->status : 'not_accepted';

if ($_REQUEST['isDuplicate'] == 'true') {
    $_POST['isDuplicate'] = true;
    $focus->id = '';
    $OPT['isDuplicate'] = true;
    $OPT['new_number'] = true;
}

if (!isset($focus->discount) || $focus->discount == '')
    $focus->discount = 0.00;

if ($OPT['new_number'] == true) {
    $datef = $current_user->getPreference('datef');

    if ($datef != '')
        $sugar_config['datef'];

    $focus->register_date = date($datef);
    $focus->payment_date = date($datef, mktime() + 30 * 24 * 60 * 60);
    $focus->sell_date = date($datef);
}

$tmp = $current_user->getPreference('num_grp_sep');
if (!isset($tmp) || $tmp == '' || $tmp == NULL)
    $tmp = $sugar_config['default_number_grouping_seperator'];

$OPT['sep_1000'] = $tmp;

$tmp = $current_user->getPreference('dec_sep');
if (!isset($tmp) || $tmp == '' || $tmp == NULL)
    $tmp = $sugar_config['default_decimal_seperator'];

$OPT['dec_sep'] = $tmp;

$tmp = $current_user->getPreference('default_currency_significant_digits');

if (!isset($tmp) || $tmp == '' || $tmp == NULL)
    $tmp = $sugar_config['default_currency_significant_digits'];

$OPT['dec_len'] = $tmp;

$OPT['default_unit'] = 'SZT.';
$OPT['default_vat'] = '23.00';
$OPT['default_category'] = '';
$OPT['default_currency'] = '-99';
$OPT['type'] = $focus->type;
$OPT['to_is_vat_free'] = $focus->to_is_vat_free;

require_once('modules/EcmTexts/EcmText.php');
foreach ($app_list_strings['ecmlanguages_dom'] as $key => $value) {
    $data = EcmText::LoadText(null, null, 'EcmKpkw', $key);
    if (isset($data[0]) && isset($data[0]['data']))
        $d = $data[0]['data']; else {
        $d = $PDFLL;
        if (!isset($d['labels']))
            $d['labels'] = $PDFLL['labels'];

        if (!isset($d['texts']['Contacts']['header_text']))
            $d['texts']['Contacts']['header_text'] = $mod_strings['LBL_DEFAULT_CONTACT_HEADER_TEXT'];

        if (!isset($d['texts']['Contacts']['footer_text']))
            $d['texts']['Contacts']['footer_text'] = $mod_strings['LBL_DEFAULT_CONTACT_FOOTER_TEXT'];

        if (!isset($d['texts']['Contacts']['ads_text']))
            $d['texts']['Contacts']['ads_text'] = $mod_strings['LBL_DEFAULT_CONTACT_ADS_TEXT'];

        if (!isset($d['texts']['Accounts']['header_text']))
            $d['texts']['Accounts']['header_text'] = $mod_strings['LBL_DEFAULT_ACCOUNT_HEADER_TEXT'];

        if (!isset($d['texts']['Accounts']['footer_text']))
            $d['texts']['Accounts']['footer_text'] = $mod_strings['LBL_DEFAULT_ACCOUNT_FOOTER_TEXT'];

        if (!isset($d['texts']['Accounts']['ads_text']))
            $d['texts']['Accounts']['ads_text'] = $mod_strings['LBL_DEFAULT_ACCOUNT_ADS_TEXT'];
    }
    $OPT['ecmlanguage'][$key]['texts'] = $d['texts'];
}
 

// $show_pdf = $current_user->getPreference('show_pdf_in_div');
// if (!isset($show_pdf)) {
    // require_once('modules/EcmGroupKpkw/EcmGroupKpkw.php');
    // $cc = EcmGroupKpkw::loadSettings();
    // $show_pdf = $cc['show_pdf_in_div_global'];
// }

$w = $GLOBALS[db]->query('select name,id,value from ecmvats where deleted=\'0\' order by name');
$nvats = mysql_num_rows($w);
while ($r = $GLOBALS[db]->fetchByAssoc($w)) {
    $VAT[$r['id']] = array(
        'id' => $r['id'],
        'name' => $r['name'],
        'value' => $r['value']
    );
}

//echo '<pre>' . var_export($OPT, true); exit;
$json = getJSONobj();
$scriptOpt = '
    <script language="javascript">
        var SHOW_PDF_IN_DIV = ' . ($show_pdf  ? : 'false') . ';
        var OPT = ' . str_replace('&quot;', '"', $json->encode($OPT)) . ';
        var MOD = ' . str_replace('&quot;', '"', $json->encode($mod_strings)) . ';
        var N, N2;
    </script>
    ';

echo $scriptOpt;

require_once('include/MVC/View/SugarView.php');
require_once('modules/EcmKpkw/views/EditView/view.edit.ecmkpkw.php');

$edit = new ViewEditEcmKpkw();
$edit->ss = new Sugar_Smarty();
$edit->module = 'EcmKpkw';
$edit->bean = $focus;
$edit->tplFile = 'include/ECM/EcmViews/EditView/Tabs/EditView.tpl';

// Build rw stock and pw stock option lists.
$w = $GLOBALS['db']->query("select name,id from ecmstocks where deleted='0' order by name asc");

$stock_id = ($focus->stock_id ? :  $GLOBALS['app_list_strings']['ecmKpkw_stock_id_dom']);
$pw_stock_id = ($focus->pw_stock_id ? :  $GLOBALS['app_list_strings']['ecmKpkw_pw_stock_id_dom']);

$stocks[] = $pw_stocks[] = '<option value="">' . $GLOBALS['app_list_strings']['stock_select'] . '</option>';

while ($r = $GLOBALS['db']->fetchByAssoc($w)) {
    $option = '<option value="'. $r['id'] . '"%s>' .  $r['name'] . '</option>';

    $stock_selected = $r['id'] == $stock_id;
    $pw_stock_selected = $r['id'] == $pw_stock_id;
    
    array_push($stocks , sprintf($option, $stock_selected ? ' selected' : ''));
    array_push($pw_stocks , sprintf($option, $pw_stock_selected ? ' selected' : ''));
}

$status = array();
foreach($app_list_strings['ecmKpkw_status_dom'] as $key => $value)
{
    $option = '<option value="'. $key . '"%s>' .  $value . '</option>';
    
    $selected = ($key == $focus->status);
    //var_dump($key, $value, $selected);
    
    array_push($status , sprintf($option, $selected ? ' selected' : ''));
}

$edit->ss->assign('STATUS', implode($status));

$repair_status = array();
foreach($app_list_strings['ecmKpkw_repair_status_dom'] as $key => $value) {
    $option = '<option value="' . $key . '"%s>' .  $value . '</option>';
    
    $selected = ($key == $focus->repair_status);
    
    array_push($repair_status, sprintf($option, $selected ? ' selected' : ''));
}

$edit->ss->assign('REPAIR_STATUS', implode($repair_status));

$focus->history = htmlspecialchars_decode($focus->history) ? : '[]';

//echo '<pre>' . var_export(strlen($focus->history), true) . '</pre>';
//echo '<pre>' . var_export(json_decode($focus->history, true), true) . '</pre>';

$edit->ss->assign('HISTORY', json_decode($focus->history, true));

$edit->ss->assign('STOCK', implode($stocks));
$edit->ss->assign('PW_STOCK', implode($pw_stocks));
$edit->ss->assign('OPT', $OPT);
$edit->preDisplay();

// Build templates option list.
// $arr_template = $focus->getTemplateList();

// $tt = array();

// foreach ($arr_template as $k => $v) {
    // $option = '<option value="'.  $k . '"%s>' .  $v . '</option>';

    // $selected = ($k == $focus->template_id);
    
    // array_push($tt , sprintf($option, $selected ? ' selected' : ''));
// }

// $edit->ss->assign('DOCUMENT_TEMPLATES_OPTIONS', implode($tt));

if (count($_REQUEST['check']) > 0) {
    foreach ($_REQUEST['check'] as $ch) {
        $r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query('select * from ecmquoteitems where id=' . $ch . ''));
        $pos = EcmQuote::getPosition($r);
        $pos['item_id'] = $ch;
        $ret[] = $pos;
    }
    //print_r($ret);die();
    $focus->position_list = $json->encode($ret);
}

if (!$focus->id)
    $temp_id = create_guid();
else
    $temp_id = $focus->id;
	
	 
    
$edit->ss->assign('TEMP_ID', $temp_id);

$pk = array(
    array(
        'wn' => 123.0,
        'amo' => 123.1,
        'ma' => 123.2,
    ),
);

$regisry = array(
    array(
        'wn' => 321.0,
        'amo' => 321.1,
        'ma' => 321.2,
    ),
);

$pkTemp = $json->encode($pk);
$registryTemp = $json->encode($regisry);

 

//echo '<pre>' . var_export($pkTemp, true) . '</pre>'; 
//echo '<pre>' . var_export($registryTemp, true) . '</pre>'; 
//exit;
if($focus->created_by==''){
$us=$current_user->id;
} else {
$us=$focus->created_by;
}
$r=$GLOBALS['db']->query("select c.name,c.id,c.currency_id from ecmcashs as c
join ecmcashs_ecmkpkw as rel on c.id=rel.ecmcash_id where rel.user_id='".$us."';
");
// kasy
$kasa='<select name="ecmcash_id" id="ecmcash_id" title="" tabindex="102" onChange="checkcash();">';
	while($dn = $GLOBALS['db']->fetchByAssoc($r)){
		if($dn['id']==$focus->ecmcash_id){$sel='selected';}else{$sel='';}
		$kasa.='<option label="'.$dn['name'].'" value="'.$dn['id'].'" '.$sel.'>'.$dn['name'].'</option>';

	}
$kasa.='</select>';

// end kasy
$edit->ss->assign('CASH', $kasa);
$edit->ss->assign('USER_ID', $us);
$edit->ss->assign('PK_LIST', $pkTemp);
$edit->ss->assign('REGISTRY_LIST', $registryTemp);
//$edit->ss->assign('foobar', "test");

// $edit->ss->assign('MFP', $focus->loadParserArray());

echo $edit->display();

//echo '<div id='subpanels'>';
//require_once('subpanels.php');
//echo '</div>';