<?php

/**
 * Created by PhpStorm.
 * User: aziz
 * Date: 9/18/2018
 * Time: 10:41 PM
 */
require_once "Modul_Controller.php";

class _shoppingCart extends Modul_Controller
{
    // private $jenisTr;

    public function __construct()
    {
        parent::__construct();
        $this->load->library("MobileDetect");

    }

    public function viewCart()
    {

        $cCode = $this->cCode;
        $this->load->helper('he_angka');

        if (!isset($_SESSION[$cCode])) {
            $_SESSION[$cCode] = array("main" => array(),
                "items" => array(),
            );
        }
        if (isset($_SESSION[$cCode]['mode']['edit']) && sizeof($_SESSION[$cCode]['mode']['edit']) > 0) {
            $stepNumberTemp = isset($_SESSION[$cCode]['tableIn_master']['step_number']) ? $_SESSION[$cCode]['tableIn_master']['step_number'] : 1;
            $stepNumber = $stepNumberTemp > 1 ? $stepNumberTemp - 1 : $stepNumberTemp;
        }
        else {
            if (isset($_SESSION[$cCode]['mode']['cancel']) && sizeof($_SESSION[$cCode]['mode']['cancel']) > 0) {
                $stepNumberTemp = isset($_SESSION[$cCode]['tableIn_master']['step_number']) ? $_SESSION[$cCode]['tableIn_master']['step_number'] : 1;
                $stepNumber = $stepNumberTemp > 1 ? $stepNumberTemp - 1 : $stepNumberTemp;
            }
            else {
                $stepNumber = isset($_SESSION[$cCode]['tableIn_master']['step_number']) ? $_SESSION[$cCode]['tableIn_master']['step_number'] : 1;
            }
        }

        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        $inputLabels = array();

        $main = array();
        $items = array();
        $items2 = array();
        $items3 = array();
        $minValue = array();
        $itemLabels = array();
        $free_items = array();
        $shoppingCartFieldSrc = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array();
        $itemLabels = isset($this->configUi[$this->jenisTr]['shoppingCartFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFields'][$stepNumber] : array();

        $itemLabelsMobile = isset($this->configUi[$this->jenisTr]['shoppingCartFieldsMobile'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFieldsMobile'][$stepNumber] : array();

        $itemLabels2 = isset($this->configUi[$this->jenisTr]['shoppingCartFields2'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFields2'][$stepNumber] : array();
        $itemsLabelReplacer = isset($this->configUi[$this->jenisTr]['shopingCartFieldsReplacer']) ? $this->configUi[$this->jenisTr]['shopingCartFieldsReplacer'] : array();

        if (isset($_SESSION[$cCode]['main']['references']) || isset($_SESSION[$cCode]['main']['singleReference'])) {
            $itemLabels = isset($this->configUi[$this->jenisTr]['shoppingCartFieldsExt'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFieldsExt'][$stepNumber] : $itemLabels;
        }

        $shoppingCartFieldsSubItems = isset($this->configUi[$this->jenisTr]['shoppingCartFieldsSubItems'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFieldsSubItems'][$stepNumber] : array();
        $itemLabels3 = isset($this->configUi[$this->jenisTr]['shoppingCartFields3'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFields3'][$stepNumber] : array();
        $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber] : array();
        $itemNumLabels2 = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields2'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields2'][$stepNumber] : array();
        $itemNumLabels3 = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields3'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields3'][$stepNumber] : array();
        $editableFields = isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber] : array();
        $editableFields2 = isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields2'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields2'][$stepNumber] : array();
        $editableFieldsCompare = isset($this->configUi[$this->jenisTr]['shopingCartEditableCompare'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shopingCartEditableCompare'][$stepNumber] : array();
        $shoppingCartMainEditableFields = isset($this->configUi[$this->jenisTr]['shoppingCartMainEditableFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartMainEditableFields'][$stepNumber] : array();
        $shoppingCartAmountValue = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber] : array();

        $elementConfigs = isset($this->configUi[$this->jenisTr]['receiptElements']) ? $this->configUi[$this->jenisTr]['receiptElements'] : array();
        $elementItemsAutoConfigs = isset($this->configUi[$this->jenisTr]['receiptElementsItemsAuto']) ? $this->configUi[$this->jenisTr]['receiptElementsItemsAuto'] : array();
        $arrHeaderElement = isset($this->configUi[$this->jenisTr]['shoppingCartHeaderElement'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartHeaderElement'][$stepNumber] : array();
        $relElementConfigs = isset($this->configUi[$this->jenisTr]['relativeElements']) ? $this->configUi[$this->jenisTr]['relativeElements'] : array();
        $relOptionConfigs = isset($this->configUi[$this->jenisTr]['relativeOptions']) ? $this->configUi[$this->jenisTr]['relativeOptions'] : array();
        $addRowsConfigs = isset($this->configUi[$this->jenisTr]['additionalRows']) ? $this->configUi[$this->jenisTr]['additionalRows'] : array();
        $editHandlerMethod = isset($this->configUi[$this->jenisTr]['editHandlerMethod']) ? $this->configUi[$this->jenisTr]['editHandlerMethod'] : "blabla";
        $editHandlerMethod2 = isset($this->configUi[$this->jenisTr]['editHandlerMethod2']) ? $this->configUi[$this->jenisTr]['editHandlerMethod2'] : "";
        $editMainHandlerMethod = isset($this->configUi[$this->jenisTr]['editMainHandlerMethod']) ? $this->configUi[$this->jenisTr]['editMainHandlerMethod'] : NULL;
        $editMainHandlerMethod2 = isset($this->configUi[$this->jenisTr]['editMainHandlerMethod2']) ? $this->configUi[$this->jenisTr]['editMainHandlerMethod2'] : NULL;

        $noteEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteEnabled']) && $this->configUi[$this->jenisTr]['shoppingCartNoteEnabled'] == true ? true : false;
        $noteType = isset($this->configUi[$this->jenisTr]['shoppingCartNoteType']) ? $this->configUi[$this->jenisTr]['shoppingCartNoteType'] : "text";
        $imageEnable = isset($this->configUi[$this->jenisTr]['shoppingCartImageEnabled']) ? $this->configUi[$this->jenisTr]['shoppingCartImageEnabled'] : false;
        $showScheme = isset($this->configUi[$this->jenisTr]['shoppingCartShowScheme']) ? $this->configUi[$this->jenisTr]['shoppingCartShowScheme'] : false;
        $imageType = isset($this->configUi[$this->jenisTr]['shoppingCartImageType']) ? $this->configUi[$this->jenisTr]['shoppingCartImageType'] : "blaa";
        $pairedItemEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItem']['enabled']) && $this->configUi[$this->jenisTr]['shoppingCartPairedItem']['enabled'] == true ? true : false;
        $pairedItem = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItem']) ? $this->configUi[$this->jenisTr]['shoppingCartPairedItem'] : array();
        $pairedItemTarget = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName']) ? $this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName'] : "items2";
        $pairedItemField = isset($this->configUi[$this->jenisTr]['shoppingCartFieldsPairedItem'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartFieldsPairedItem'][$stepNumber] : array();
        $pairedItemRecorder = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItemRecorder']) ? $this->configUi[$this->jenisTr]['shoppingCartPairedItemRecorder'] : "";

        $pairedMoq = isset($this->configUi[$this->jenisTr]['shoppingCartMinFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartMinFields'][$stepNumber] : array();
        $avoidRemove = isset($this->configUi[$this->jenisTr]['shoppingCartAvoidRemove']) ? $this->configUi[$this->jenisTr]['shoppingCartAvoidRemove'] : false;
        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();
        $reqDiskon = isset($this->configUi[$this->jenisTr]['reqDiskon']) ? $this->configUi[$this->jenisTr]['reqDiskon'] : array();
        $unionSelectors = isset($this->configUi[$this->jenisTr]['shoppingCartUnionSelectors'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartUnionSelectors'][$stepNumber] : array();
        $keyUpEvents = isset($this->configUi[$this->jenisTr]['shoppingCartKeyUpEvents'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartKeyUpEvents'][$stepNumber] : array();
        $selectedPrices = isset($this->configUi[$this->jenisTr]['selectedPrice']['key_label']) ? $this->configUi[$this->jenisTr]['selectedPrice']['key_label'] : array();
        $showItems = isset($this->configUi[$this->jenisTr]['showItems']) && $this->configUi[$this->jenisTr]['showItems'] == "false" ? "false" : "true";
        $fixedNote = isset($this->config->item('heTransaksi_layout')[$this->jenisTr]['fixedNote']) ? $this->config->item('heTransaksi_layout')[$this->jenisTr]['fixedNote'] : null;
        $fixedNoteTop = isset($this->config->item('heTransaksi_layout')[$this->jenisTr]['fixedNoteTop']) ? $this->config->item('heTransaksi_layout')[$this->jenisTr]['fixedNoteTop'] : null;
        $shopingCartParamForceEditable = isset($this->configUi[$this->jenisTr]['shopingCartParamForceEditable'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shopingCartParamForceEditable'][$stepNumber] : array();
        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array();
        //----------------------------------------------
        $isSettlement = isset($this->configUi[$this->jenisTr]['isSettlement']) ? $this->configUi[$this->jenisTr]['isSettlement'] : false;
        //----------------------------------------------
        $shopingCartItemOptionFields = isset($this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][$stepNumber] : array();

        if ($editMainHandlerMethod != NULL) {
            if (isset($_SESSION[$cCode]['main']['pihakMainName'])) {
                $editHandlerMethod = isset($editMainHandlerMethod[$_SESSION[$cCode]['main']['pihakMainName']]) ? $editMainHandlerMethod[$_SESSION[$cCode]['main']['pihakMainName']] : "edit";
            }
        }
        if ($editMainHandlerMethod2 != NULL) {
            if (isset($_SESSION[$cCode]['main']['pihakMainName'])) {
                $editHandlerMethod2 = isset($editMainHandlerMethod2[$_SESSION[$cCode]['main']['pihakMainName']]) ? $editMainHandlerMethod2[$_SESSION[$cCode]['main']['pihakMainName']] : "edit";
            }
        }

        if (sizeof($shoppingCartMainEditableFields) > 0) {
            if (isset($_SESSION[$cCode]['main']['pihakMainName'])) {

                if (isset($shoppingCartMainEditableFields[$_SESSION[$cCode]['main']['pihakMainName']]) && sizeof($shoppingCartMainEditableFields[$_SESSION[$cCode]['main']['pihakMainName']]) > 0) {
                    $editableFields = $shoppingCartMainEditableFields[$_SESSION[$cCode]['main']['pihakMainName']];
                }
            }
        }
        $hargaJualItem = array();
        $itemsProdukIds=array();
        if (isset($_SESSION[$cCode])) {
            if (isset($_SESSION[$cCode]['items'])) {
                $no = 0;
                $sesItems = $_SESSION[$cCode]['items'];
                // arrPrint($_SESSION[$cCode]['items']);
                foreach ($_SESSION[$cCode]['items'] as $id => $iSpec) {
                    $pihakID = $id;
                    $no++;
                    $pihakName = isset($sesMains['pihakName']) ? $sesMains['pihakName'] : "";
                    $tmp = array(//                        "id"     => $iSpec['id'],
                        "id" => $id,
                        "no_part" => isset($iSpec['no_part']) ? $iSpec['no_part'] : "",
                        "nama" => isset($iSpec['nama']) ? $iSpec['nama'] : "",
                        "kode" => isset($iSpec['kode']) ? "'" . strval($iSpec['kode']) : "-",
                        "code" => isset($iSpec['code']) ? "'" . strval($iSpec['code']) : "-",
                        "lokasi_nama" => isset($iSpec['lokasi_nama']) ? $iSpec['lokasi_nama'] : "-",
                        "merek_nama" => isset($iSpec['merek_nama']) ? $iSpec['merek_nama'] : "-",
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "n/a",
                        "jml"                => isset($iSpec['jml']) ? $iSpec['jml'] : 0,
                        "stok_all" => isset($iSpec['stok_all']) ? $iSpec['stok_all'] : 0,
                        "moq" => isset($iSpec['moq']) ? $iSpec['moq'] : 0,
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "",
                        // -----------
                        "sub_berat_gross" => isset($iSpec['sub_berat_gross']) ? $iSpec['sub_berat_gross'] : "",
                        "sub_lebar_gross" => isset($iSpec['sub_lebar_gross']) ? $iSpec['sub_lebar_gross'] : "",
                        // -----------
                        "sub_panjang_gross" => isset($iSpec['sub_panjang_gross']) ? $iSpec['sub_panjang_gross'] : "",
                        "sub_tinggi_gross" => isset($iSpec['sub_tinggi_gross']) ? $iSpec['sub_tinggi_gross'] : "",
                        "sub_volume_gross" => isset($iSpec['sub_volume_gross']) ? $iSpec['sub_volume_gross'] : "",
                        // -----------
                        "sub_volume" => isset($iSpec['sub_volume']) ? $iSpec['sub_volume'] : "",
                        "sub_berat" => isset($iSpec['sub_berat']) ? $iSpec['sub_berat'] : "",
                        "request_jml" => isset($iSpec['request_jml']) ? $iSpec['request_jml'] : 0,
                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "0",
                        "stok_hold" => isset($iSpec['stok_hold']) ? $iSpec['stok_hold'] : "0",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        "stok_avail" => isset($iSpec['stok_avail']) ? $iSpec['stok_avail'] : 0,
                        "stok_rekening" => isset($iSpec['stok_rekening']) ? $iSpec['stok_rekening'] : 0,
                        "sent_jml" => isset($iSpec['sent_jml']) ? $iSpec['sent_jml'] : "",
                        "packed_jml" => isset($iSpec['packed_jml']) ? $iSpec['packed_jml'] : "",
                        "cancel_jml" => isset($iSpec['cancel_jml']) ? $iSpec['cancel_jml'] : "",
                        "req_cancel_jml" => isset($iSpec['req_cancel_jml']) ? $iSpec['req_cancel_jml'] : "",
                        "cancel_qty" => isset($iSpec['cancel_qty']) ? $iSpec['cancel_qty'] : "",
                        "req_cancel_qty" => isset($iSpec['req_cancel_qty']) ? $iSpec['req_cancel_qty'] : "",
                        "max_jml" => isset($iSpec['max_jml']) ? $iSpec['max_jml'] : "",
                        "outstanding" => isset($iSpec['outstanding']) ? $iSpec['outstanding'] : 0,
                        "ppn_persen" => isset($iSpec['ppn_persen']) ? $iSpec['ppn_persen'] : 0,
                        "merk" => isset($iSpec['merk']) ? $iSpec['merk'] : "",
                        "serial_no" => isset($iSpec['serial_no']) ? $iSpec['serial_no'] : "",
                        "extern2_nama" => isset($iSpec['extern2_nama']) ? $iSpec['extern2_nama'] : "",
                        "valas_nama" => isset($iSpec['valas_nama']) ? $iSpec['valas_nama'] : "",
                        "valas_nilai" => isset($iSpec['valas_nilai']) ? $iSpec['valas_nilai'] : "",
                        "satuan_factor_nama" => isset($iSpec['satuan_factor_nama']) ? $iSpec['satuan_factor_nama'] : "",
                        "satuan_factor_id" => isset($iSpec['satuan_factor_id']) ? $iSpec['satuan_factor_id'] : "",
                        "qty_unit" => isset($iSpec['qty_unit']) ? $iSpec['qty_unit'] : "",
                        "free_produk_note" => isset($iSpec['free_produk_note']) ? $iSpec['free_produk_note'] : "",
                    );
                    if ($noteEnabled) {
                        $tmp['note'] = isset($iSpec['note']) ? $iSpec['note'] : "";
                    }
                    if ($imageEnable) {
                        $tmp['images'] = isset($iSpec['images']) ? $iSpec['images'] : "";
                    }
                    if (sizeof($itemNumLabels) > 0) {
                        foreach ($itemNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;
                        }
                    }
                    if (sizeof($pairedMoq) > 0) {
                        foreach ($pairedMoq as $key => $label) {
                            $minValue[$key][$iSpec['id']] = isset($iSpec[$key]) ? $iSpec[$key] : 1;
                        }
                    }
                    if (sizeof($fieldSrcs) > 0) {
                        foreach ($fieldSrcs as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                        }
                    }


                    //                    $tmp[$shoppingCartAmountValue] = isset($iSpec[$shoppingCartAmountValue]) ? $iSpec[$shoppingCartAmountValue] : 0;
                    $tmp['subtotal'] = isset($iSpec['subtotal']) ? $iSpec['subtotal'] : 0;
                    $tmp['sub_harga'] = isset($iSpec['sub_harga']) ? $iSpec['sub_harga'] : 0;
                    // cekLime(isset($iSpec['handler']) ? $iSpec['handler'] : '0');
                    $tmp["editTarget"] = base_url() . (isset($iSpec['handler']) ? $iSpec['handler'] : '') . "/" . $editHandlerMethod . "/" . $this->jenisTr . "?id=" . $id . "&newQty=";
                    $tmp["removeTarget"] = base_url() . (isset($iSpec['handler']) ? $iSpec['handler'] : '') . "/remove/" . $this->jenisTr . "?id=" . $id;

                    $items[] = $tmp;

                    $hargaJualItem[$id] = $iSpec['harga_jual'];
                    $itemsProdukIds[$id] = array();
                    //                    arrPrint($shoppingCartAmountValue);


                    //                    if (sizeof($notifications) > 0) {
                    //                        $plafon = $lv->callPlafonHutangBank($id);
                    //
                    //                        // cekHitam("$plafon");
                    //                        if (($pihakID > 0) && ($plafon == 0)) {
                    //                            echo "<div class='alert alert-danger'>";
                    //                            // echo "<a href='#' class='close' data-dismiss='alert' aria-label='close' style='text-decoration: none;'>&times;</a>";
                    //                            echo "<span class='blink'><i class='fa fa-warning'></i></span> ";
                    //                            echo "$pihakName :: " . $notifications[$stepNow];
                    //                            echo "</div>";
                    //                        }
                    //                    }
                }
            }

            if (isset($_SESSION[$cCode]['free_items'])) {
                $free_items = $_SESSION[$cCode]['free_items'];
        }
        }

        //item2 sum
        if (isset($_SESSION[$cCode])) {
            if (isset($_SESSION[$cCode]['items2_sum'])) {
                $items2_sum_kurang = array();
                $no = 0;
                $valItem = 0;
                foreach ($_SESSION[$cCode]['items2_sum'] as $iSpec) {
                    $sisa = isset($iSpec['stok']) && isset($iSpec['jml']) ? $iSpec['stok'] - $iSpec['jml'] : 0;

                    $no++;
                    $tmp = array("id" => $iSpec['id'],
                        "nama" => isset($iSpec['nama']) ? $iSpec['nama'] : "",
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "",
                        "jml" => isset($iSpec['jml']) ? $iSpec['jml'] : 0,
                        "jual" => isset($iSpec['jual']) ? $iSpec['jual'] : 0,
                        "disc_value" => isset($iSpec['disc_value']) ? $iSpec['disc_value'] : 0,
                        "disc_persent" => isset($iSpec['disc_persent']) ? $iSpec['disc_persent'] : 0,
                        "subtotal" => isset($iSpec['subtotal']) ? $iSpec['subtotal'] : 0,
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : isset($iSpec['kode']) ? $iSpec['kode'] : "",
                        // --
                        "kode" => isset($iSpec['kode']) ? $iSpec['kode'] : "",
                        "referensi" => isset($iSpec['pihakName']) ? $iSpec['pihakName'] : "",
                        "harga_ori" => isset($iSpec['harga_ori']) ? $iSpec['harga_ori'] : "",
                        "harga" => isset($iSpec['harga']) ? $iSpec['harga'] : "",
                        "harga2" => isset($iSpec['harga']) ? $iSpec['harga'] : "",
                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        //                        "sisa" => isset($iSpec['stok']) && isset($iSpec['jml']) ? $iSpec['stok'] - $iSpec['jml'] : "",
                        "sisa" => isset($sisa) ? $sisa : 0,
                        "produk_id" => isset($iSpec['id']) ? $iSpec['id'] : "",
                        "qty" => isset($iSpec['jml']) ? $iSpec['jml'] : "",
                        "produk_nama" => isset($iSpec['nama']) ? $iSpec['nama'] : "",
                        "produk_ord_jml" => isset($iSpec['jml']) ? $iSpec['jml'] : 0,
                        "produk_ord_hrg" => isset($iSpec['jual']) ? $iSpec['jual'] : "",
                        //                        "produk_kode" => isset($iSpec['kode']) ? $iSpec['kode'] : "",
                        "produk_label" => isset($iSpec['label']) ? $iSpec['label'] : "",
                        "harga_last" => isset($iSpec['harga_last']) ? $iSpec['harga_last'] : "",
                        "sub_harga_last" => isset($iSpec['sub_harga_last']) ? $iSpec['sub_harga_last'] : "",
                    );
                    if ($noteEnabled) {
                        $tmp['note'] = isset($iSpec['note']) ? $iSpec['note'] : "";
                    }
                    if ($imageEnable) {
                        $tmp['images'] = isset($iSpec['images']) ? $iSpec['images'] : "";
                    }
                    if (sizeof($itemNumLabels) > 0) {

                        foreach ($itemNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            //                            cekHitam($key);
                            $valItem += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;
                            $main[$key] = $valItem;
                            //                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                        }
                    }
                    if (isset($iSpec['subtotal'])) {
                        $tmp['subtotal'] = $iSpec['subtotal'];
                    }
                    if (isset($iSpec['sub_harga'])) {
                        $tmp['sub_harga'] = $iSpec['sub_harga'];
                    }

                    if (isset($editHandlerMethod2)) {
                        if (isset($iSpec['handler'])) {
                            $tmp["editTarget"] = base_url() . $iSpec['handler'] . "/" . $editHandlerMethod2 . "/" . $this->jenisTr . "?id=" . $id . "&newQty=";
                            $tmp["removeTarget"] = base_url() . $iSpec['handler'] . "/remove/" . $this->jenisTr . "?id=" . $id;
                        }
                        else {
                            $tmp["editTarget"] = "";
                            $tmp["removeTarget"] = "";
                        }
                    }
                    else {
                        $tmp["editTarget"] = "";
                        $tmp["removeTarget"] = "";
                    }


                    $items2[] = $tmp;


                }
            }
        }

        //items3
        if (isset($_SESSION[$cCode]['items3'])) {
            $items3 = $_SESSION[$cCode]['items3'];
        }

        //item3 sum
        $items3_sum = array();
        if (isset($_SESSION[$cCode])) {
            if (isset($_SESSION[$cCode]['items3_sum'])) {
                $no = 0;
                foreach ($_SESSION[$cCode]['items3_sum'] as $iSpec) {
                    $no++;
                    $tmp = array("id" => $iSpec['id'],
                        "nama" => isset($iSpec['nama']) ? $iSpec['nama'] : "",
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "",
                        "jml" => isset($iSpec['jml']) ? $iSpec['jml'] : 0,
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "",
                        "referensi" => isset($iSpec['pihakName']) ? $iSpec['pihakName'] : "",
                        "harga" => isset($iSpec['harga']) ? $iSpec['harga'] : "",
                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        "sisa" => isset($iSpec['stok']) && isset($iSpec['jml']) ? $iSpec['stok'] - $iSpec['jml'] : "",
                        "sub_nilai" => isset($iSpec['sub_nilai']) ? $iSpec['sub_nilai'] : 0,
                    );
                    if ($noteEnabled) {
                        $tmp['note'] = isset($iSpec['note']) ? $iSpec['note'] : "";
                    }
                    if ($imageEnable) {
                        $tmp['images'] = isset($iSpec['images']) ? $iSpec['images'] : "";
                    }
                    if (sizeof($itemNumLabels) > 0) {
                        foreach ($itemNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                        }
                    }
                    if (isset($iSpec['subtotal'])) {
                        $tmp['subtotal'] = $iSpec['subtotal'];
                    }
                    if (isset($iSpec['sub_harga'])) {
                        $tmp['sub_harga'] = $iSpec['sub_harga'];
                    }

                    $tmp["editTarget"] = "";
                    $tmp["removeTarget"] = "";

                    $items3_sum[] = $tmp;


                }
            }
        }

        if (isset($this->configUi[$this->jenisTr]['shoppingCartSubamount2']) && $this->configUi[$this->jenisTr]['shoppingCartSubamount2'][$stepNumber] == true) {

            if($isMob){
                $itemLabels = $itemLabels + array("subtotal" => "Total<br><r>(incl)</r><br><r>(VAT & DISC)</r>");
                $itemLabels = $itemLabels + array("sub_harga" => "Total<br><r>(excl)</r><br><r>(VAT & DISC)</r>");
            }
            else{
            $itemLabels = $itemLabels + $itemNumLabels + array("subtotal" => "Total<br><r>(incl)</r><br><r>(VAT & DISC)</r>");
            $itemLabels = $itemLabels + array("sub_harga" => "Total<br><r>(excl)</r><br><r>(VAT & DISC)</r>");
            }

            $itemLabels2 = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "Total<br><r>(incl)</r><br><r>(VAT & DISC)</r>");
            $itemLabels2 = $itemLabels2 + array("sub_harga" => "Total<br><r>(excl)</r><br><r>(VAT & DISC)</r>");
        }
        else {

            if($isMob){
                $itemLabels = $itemLabels + array("subtotal" => "Total Price");
            }
            else{
            $itemLabels = $itemLabels + $itemNumLabels + array("subtotal" => "Total Price");
            }

            $itemLabels2 = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "Total Price");
            $itemLabels3 = $itemLabels3 + $itemNumLabels3 + array("subtotal" => "Total Price");
        }

        if (isset($this->configUi[$this->jenisTr]['shoppingCartHideSubamount']) && $this->configUi[$this->jenisTr]['shoppingCartHideSubamount'][$stepNumber] == true) {
            unset($itemLabels['subtotal']);
            unset($itemLabels2['subtotal']);
            unset($itemLabels3['subtotal']);
            unset($itemLabels[$shoppingCartAmountValue]);
        }

        //region ======additional rows======
        $sumRowAction = base_url() . "ValueGate/evalFees/" . $this->jenisTr;
        $sumRowAction2 = base_url() . "ValueGate/evalVals/" . $this->jenisTr;
        $addValues = isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array();
        $addValues2 = isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array();
        $mainFields = array();
        $sumRows2 = array();
        $sumSpec2 = array();
        $sumType2 = array();
        if (isset($this->configCore[$this->jenisTr]['externalValues'])) {
            if (sizeof($this->configCore[$this->jenisTr]['externalValues']) > 0) {
                $iterator = $this->configCore[$this->jenisTr]['externalValues'];
                foreach ($iterator as $vName => $vSpec) {
                    //region sepasang combobox
                    if (isset($vSpec['mdlName']) && strlen($vSpec['mdlName']) > 0) {
                        $key = $vName . "_src";
                        $sumRows2[$key] = "select " . $vSpec['label'];
                        $sumSpec2[$key] = "<select id='$key' name='$key' class='form-control' onchange=\"document.getElementById('result').src='" . $sumRowAction2 . "?key=$key&value='+this.value;\">";
                        $sumSpec2[$key] .= "<option value=''>-select-</option>";
                        $mdlName9 = $vSpec['mdlName'];
                        $this->load->model("Mdls/" . $mdlName9);
                        $o9 = new $mdlName9();
                        $tmp9 = $o9->lookupAll()->result();
                        if (sizeof($tmp9) > 0) {
                            foreach ($tmp9 as $row9) {
                                $defaultValue = isset($addValues2[$key]) ? $addValues2[$key] : "";
                                $selected = $row9->id == $defaultValue ? "selected" : "";
                                $sumSpec2[$key] .= "<option value='" . $row9->id . "' $selected>" . $row9->nama . "</option>";
                            }
                        }
                        $sumSpec2[$key] .= "</select>";
                        $sumType2[$key] = "text";
                    }
                    //endregion
                    //region sepasang text
                    $key = $vName;
                    $sumRows2[$vName] = $vSpec['label'];
                    $color = "343434";
                    if (in_array($key, $editableFields)) {
                        $readOnly = "";
                    }
                    else {
                        $readOnly = "readonly";
                    }
                    $defaultValue = isset($addValues[$key]) ? $addValues[$key] : 0;
                    $sumSpec2[$key] = "<input type='text' class='form-control text-right' name=$key id=$key value='$defaultValue' 
                    onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+removeCommas(this.value);}\"
                    onmouseout=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+removeCommas(this.value);}\"
                    >";
                    $sumType2[$key] = "number";
                    //endregion
                    if ($vSpec['taxFactor'] > 0) {
                        $key = $vName . "_tax";
                        $defaultValue = isset($addValues[$key]) ? $addValues[$key] : 0;
                        $sumRows2[$key] = "tax for " . $vSpec['label'];
                        $sumSpec2[$key] = "<input type='text' class='form-control text-right' name=$key id=$key value='$defaultValue' 
                        onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+removeCommas(this.value);}\"
                        onmouseout=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+removeCommas(this.value);}\"
                        >";
                        $sumType2[$key] = "number";
                    }
                }
            }
        }
        //endregion

        //region diskon event diskon tambahan
        /* ---------------------------------------------------------------------------------
        * BACA SETTINGAN DISKON YG BERLAKU berdasar level member
        * ---------------------------------------------------------------------------------*/
        $str_customer = "";
        $info_member_style = "";
        $main_tmp = array();
        if (isset($_SESSION[$cCode]['main']['pihakLevel'])) {
            $data_mains = $_SESSION[$cCode]['main'];
            // arrPrintHijau($data_mains);
            $pihakLevel = $data_mains['pihakLevel'];
            // $harga_nppn = isset($data_mains['harga_nett1']) ? $data_mains['harga_nett1'] : 0;
            $harga_nppn = isset($data_mains['grand_total']) ? $data_mains['grand_total'] : 0;
            $pointSaldo = isset($data_mains['pihakPoint']) ? $data_mains['pihakPoint'] : 0;

            $this->load->library("Diskon");
            $dk = new Diskon();
            $dk->setTokoId(my_toko_id());
            $dsc_param_src = $dk->callCustomerLevelDiskon($pihakLevel);
            $dsc_params = $dsc_param_src["customer_level_diskon"];
            // arrPrint($dsc_params);
            $trans_nilai = $harga_nppn;
            // cekKuning($data_mains["harga_net"]);
            $macem_diskons = array();
            foreach ($dsc_params as $item) {
                // arrPrintPink($item);
                $dk_tipe = $item['tipe'];
                $dk_jenis = $item['jenis'];

                $macem_diskons[$dk_tipe][$dk_jenis][] = $item;
            }
//             arrPrintKuning($macem_diskons);
            // arrPrintKuning($macem_diskons["diskon"]);
            $tgl_now = dtimeNow('Y-m-d');
            $tgl_now_s = dtimeToSecond($tgl_now);
            $diskon_cashbacks = array();
            $info_diskon_cashbacks = array();
            foreach ($macem_diskons as $diskon_tipe => $macem_diskon) {
                foreach ($macem_diskon as $diskon_nama => $item_diskon) {

                    $jml_even_diskon = sizeof($item_diskon);
                    $evnt_count = 0;
                    foreach ($item_diskon as $item) {
                        // arrPrintPink($item);
                        $evnt_count++;
                        $gro_tipe = $item['tipe'];
                        $gro_minim_db = $item['minim'];
                        $gro_maxim = $evnt_count == $jml_even_diskon ? INF : $item['maxim'];
                        $gro_persen = $item['persen'];
                        //--------------------------------------------------------
                        $gro_start = $item['tanggal_start'];
                        $gro_stop = $item['tanggal_stop'];
                        $gro_start_s = dtimeToSecond($gro_start);
                        $gro_stop_s = dtimeToSecond($gro_stop);

                        if (($trans_nilai >= $gro_minim_db) && ($trans_nilai <= $gro_maxim)) {
                        // cekPink2("$diskon_nama:: $trans_nilai >= $gro_minim_db) && ($trans_nilai <= $gro_maxim)");


                            /* --------------------------------------------------------------
                             * pembatasan tgl setting diskon
                             * --------------------------------------------------------------*/
                            $d_pokok = 0;
                            $gro_minim = 0;
//                             cekHijau("$tgl_now >= $gro_start && $tgl_now <= $gro_stop");
//                             cekHijau("$tgl_now_s >= $gro_start_s && $tgl_now_s <= $gro_stop_s");
                            if ($gro_start_s <= 0) {
                                $d_pokok = $gro_persen;
                                $gro_minim = $gro_minim_db;
                            }
                            elseif ($tgl_now_s >= $gro_start_s && $tgl_now_s <= $gro_stop_s) {
                                $d_pokok = $gro_persen;
                                $gro_minim = $gro_minim_db;
                            }
                            // ---------------------------------------------------------------

                            // cekBiru("---- $d_pokok");
                            $diskon_cashbacks[$diskon_tipe][$diskon_nama] = $d_pokok;
                            $info_diskon_cashbacks[$diskon_tipe][$diskon_nama]["persen"] = $d_pokok;
                            $info_diskon_cashbacks[$diskon_tipe][$diskon_nama]["range"] = $gro_minim . "-" . $gro_maxim;

                            /*--------- paramnya point ------------*/
                            if ($gro_tipe == "point") {
                                $diskon_cashbacks[$diskon_tipe]["minim"] = $gro_minim;
                            }
                            break;
                        }

                    }
                }
            }

//            matiHere(__LINE__);

            // arrPrintHijau($diskon_cashbacks);
            $diskon_events = isset($diskon_cashbacks['diskon']) ? $diskon_cashbacks['diskon'] : array();
            $cashback_events = isset($diskon_cashbacks['cashback']) ? $diskon_cashbacks['cashback'] : array();
            $point_events = isset($diskon_cashbacks['point']) ? $diskon_cashbacks['point'] : array();
//            arrPrintWebs($info_diskon_cashbacks);
            $calc_hasil = $dk->calcDiskon($trans_nilai, array(), $diskon_events, array(), "diskon");
            // arrPrintKuning($calc_hasil);
            $harga_af = $calc_hasil['harga_af'];

            $main_tmp['diskon_tambahan_persen'] = $calc_hasil['persen'];
            $main_tmp['diskon_tambahan_nilai'] = $calc_hasil['nilai'];
            $main_tmp['harga_final'] = $harga_af;

            $calc_cashback = $dk->calcDiskon($trans_nilai, array(), $cashback_events, array(), "diskon");
            // arrPrintPink($calc_cashback);
            $main_tmp['cashback_persen'] = isset($cashback_events['cashback']) ? $cashback_events['cashback'] * 1 : 0;
            $main_tmp['cashback_nilai'] = $calc_cashback['nilai'];
            // matiHere(__LINE__);

            /*point transaksi*/
//             arrPrintPink($point_events);
//             cekPink($jml_point);
//             cekPink(sizeof($point_events));
//             cekhijau($trans_nilai);
//             cekhijau($point_events['minim']);
//             cekhijau($point_events['point']);

            if (sizeof($point_events) > 0) {
                $jml_point = $point_events['minim'] *1>0 && $point_events['point']*1>0 ? $trans_nilai / $point_events['minim'] * $point_events['point'] : 0;
                $main_tmp['point_saldo_awal'] = (int)$pointSaldo;
                $main_tmp['point_transaksi'] = (int)$jml_point;
                $main_tmp['point_saldo_akhir'] = (int)$pointSaldo + (int)$jml_point;
                $main_tmp['point_nilai'] = $point_events['minim'];
                $main_tmp['point_set'] = $point_events['point'];
            }
            else {
                $main_tmp['point_transaksi'] = 0;
                $main_tmp['point_nilai'] = 0;
                $main_tmp['point_set'] = 0;
            }


            // $array_main = $_SESSION[$cCode]['main'];
            // $array_tableIn_master_values = $_SESSION[$cCode]['tableIn_master_values'];

            // arrPrintHijau($cashback_events);
            // arrPrintKuning($array_main);
            // arrPrintKuning($main_tmp);

            /* --------------------------------------------------------------
             * memamsukan main_tmp ke session main
             * --------------------------------------------------------------*/
            foreach ($main_tmp as $key => $item_val) {
                // $array_main[$key] = $item_val;
                $_SESSION[$cCode]['main'][$key] = $item_val;
                $_SESSION[$cCode]['tableIn_master_values'][$key] = $item_val;
            }

            $_SESSION[$cCode]['diskon_event'] = sizeof($diskon_events) > 0 ? $diskon_events : null;
            $_SESSION[$cCode]['cashback_event'] = sizeof($cashback_events) ? $cashback_events : null;
            $_SESSION[$cCode]['cashback_event']['cashback_nilai'] = $calc_cashback['nilai'];
            $_SESSION[$cCode]['point_event'] = count($point_events) ? $point_events : null;

            /* ---------------------------------------------
             * INFO CUSTOMER
             ---------------------------------------------*/
            $info_member_style = "<style type='text/css'>
                        .info-member{
                            padding: 5px;
                            border-radius: 5px;
                            // box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
                            margin-right: 10px;
                            // border: darkblue;
                            box-shadow: rgba(6, 24, 44, 0.4) 0px 0px 0px 1px, rgba(6, 24, 44, 0.65) 0px 2px 6px -1px, rgba(255, 255, 255, 0.08) 0px 1px 0px inset;
                            // box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 1px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;
                            // box-shadow: rgba(9, 30, 66, 0.25) 0px 4px 8px -2px, rgba(9, 30, 66, 0.08) 0px 0px 0px 1px;
                        }
                    </style>";
            $pihakName = isset($data_mains['pihakName']) ? $data_mains['pihakName'] : "PILIH CUSTOMER";
            $pihakLevelNama = $data_mains['pihakLevelNama'];
            $star_icon = "<i class='fa fa-star text-yellow'></i>";

            $level_icon = "";
            for($i=1;$i<= $pihakLevel;$i++){
                $level_icon .= $star_icon."&nbsp;";
            }

            $tgl_now = dtimeNow("Y-m-d");
            $tgl_now_f_fulldate = formatField_he_format("fulldate", dtimeNow());
            $tgl_now_s = dtimeToSecond($tgl_now);
            // $tgl_now_mk = mktime($tgl_now);
            // $tgl_now_str = strtotime($tgl_now);
            /*DISKON -------------------------------------------------------------------------------*/
            $str_diskon = "";
            if(isset($macem_diskons["diskon"]["transaksi"])){
                foreach ($macem_diskons["diskon"]["transaksi"] as $macem_diskon) {
                    $minim = $macem_diskon["minim"];
                    $minim_f = formatField_he_format("valas", $minim);
                    $maxim = $macem_diskon["maxim"];
                    $persen = $macem_diskon["persen"];
                    $stop = $macem_diskon["tanggal_stop"];
                    $stop_f = formatField_he_format("fulldate",$stop);
                    $maxim_f = $maxim == 0 ? "~" : $maxim;
                    if ($tgl_now <= $stop) {
                        $str_diskon .= "<div>$persen% transaki <span style='height: 5px;'>$minim_f</span> <span class='pull-right'>$stop_f</span></div>";
                    }
                }
            }
            $str_customer .= "<div class='col-md-2 bg-info info-member text-center'>$level_icon <div class='text-uppercase'>$pihakLevelNama member<br>a/n $pihakName</div></div>";
            $str_customer .= "<div class='col-md-3 bg-warning info-member text-red'>$str_diskon</div>";

            /*CASHBACK ----------------------------------------------------------------------------------------*/
            // arrPrint($macem_diskons["cashback"]["cashback"]);
            $str_cashback = "";
            if(isset($macem_diskons["cashback"]["cashback"])){
                foreach ($macem_diskons["cashback"]["cashback"] as $macem_diskon) {
                    // arrPrintPink($macem_diskon);
                    $minim = $macem_diskon["minim"];
                    $minim_f = formatField_he_format("valas", $minim);
                    $maxim = $macem_diskon["maxim"];
                    $persen = $macem_diskon["persen"];
                    $stop = $macem_diskon["tanggal_stop"];
                    $stop_f = formatField_he_format("fulldate",$stop);
                    $maxim_f = $maxim == 0 ? "~" : $maxim;
                    // cekHere("$stop <= $tgl_now");
                    if ($tgl_now <= $stop) {
                        $str_cashback .= "<div>$persen% transaki <span style='height: 5px;'>$minim_f</span> <span class='pull-right'>$stop_f</span></div>";
                    }
                    // else{
                    //     $str_diskon .= "none";
                    // }

                }
            }
            $str_customer .= "<div class='col-md-3 bg-danger info-member text-blue'>$str_cashback</div>";
            /* ---POINT ----------------------------------------------------------------------------------------*/
            // arrPrint($macem_diskons);
            // arrPrint($macem_diskons["point"]["point"]);
            $str_point = "";
            if (isset($macem_diskons["point"]["point"])) {
                foreach ($macem_diskons["point"]["point"] as $macem_diskon) {
                    // arrPrintPink($macem_diskon);
                    $minim = $macem_diskon["minim"];
                    $minim_f = formatField_he_format("kredit_limit", $minim);
                    $maxim = $macem_diskon["maxim"];
                    $persen = $macem_diskon["persen"];
                    $persen_f = formatField_he_format("kredit_limit", $persen);
                    $stop = $macem_diskon["tanggal_stop"];
                    $stop_s = dtimeToSecond($stop);
                    $stop_f = $stop_s > 0 ? formatField_he_format("fulldate", $stop) : "";
                    // $stop_mk = mktime($stop);
                    // $stop_str = strtotime($stop);
                    $maxim_f = $maxim == 0 ? "~" : $maxim;
                    // cekHere("$stop_f ==== $stop === $stop_s == $stop_str <= $tgl_now === $tgl_now_f_fulldate ==== $tgl_now_s == $tgl_now_str");
                    if ($stop_s < 0 || $tgl_now_s <= $stop_s) {
                        $str_point .= "<div>$persen_f point tiap transaki <span style='height: 5px;'>$minim_f</span> <span class='pull-right'>$stop_f</span></div>";
                    }
                    // else{
                    //     $str_diskon .= "none";
                    // }

                }
            }
            $str_customer .= "<div class='col-md-3 bg-success info-member'>$str_point</div>";
            // $str_customer .= "$pihakLevelNama";
        }
        //endregion

        //region ======additional rows from reference (if this is a RETURN)======
        if (isset($this->configUi[$this->jenisTr]['referenceJenisTr']) && strlen($this->configUi[$this->jenisTr]['referenceJenisTr']) > 1) {

            $refJenisTr = $this->configUi[$this->jenisTr]['referenceJenisTr'];
            //            cekKuning("berasal dari $refJenisTr");
            $cCode2 = "_TR_" . $refJenisTr;
            $addValues = isset($_SESSION[$cCode2]['main_add_values']) ? $_SESSION[$cCode2]['main_add_values'] : array();
            $addValues2 = isset($_SESSION[$cCode2]['main_add_fields']) ? $_SESSION[$cCode2]['main_add_fields'] : array();
            $mainFields = array();
            $sumRows2 = array();
            $sumSpec2 = array();
            $sumType2 = array();
            if (isset($this->configCore[$refJenisTr]['externalValues'])) {
                if (sizeof($this->configCore[$refJenisTr]['externalValues']) > 0) {
                    $iterator = $this->configCore[$refJenisTr]['externalValues'];
                    foreach ($iterator as $vName => $vSpec) {
                        //region sepasang combobox
                        if (isset($vSpec['mdlName']) && strlen($vSpec['mdlName']) > 0) {
                            $key = $vName . "_src";
                            $sumRows2[$key] = "select " . $vSpec['label'];
                            $sumSpec2[$key] = "<select id='$key' name='$key' class='form-control' onchange=\"document.getElementById('result').src='" . $sumRowAction2 . "?key=$key&value='+this.value;\">";
                            $sumSpec2[$key] .= "<option value=''>-select-</option>";
                            $mdlName9 = $vSpec['mdlName'];
                            $this->load->model("Mdls/" . $mdlName9);
                            $o9 = new $mdlName9();
                            $tmp9 = $o9->lookupAll()->result();
                            if (sizeof($tmp9) > 0) {
                                foreach ($tmp9 as $row9) {
                                    $defaultValue = isset($addValues2[$key]) ? $addValues2[$key] : "";
                                    $selected = $row9->id == $defaultValue ? "selected" : "";
                                    $sumSpec2[$key] .= "<option value='" . $row9->id . "' $selected>" . $row9->nama . "</option>";
                                }
                            }
                            $sumSpec2[$key] .= "</select>";
                            $sumType2[$key] = "text";
                        }
                        //endregion
                        //region sepasang text
                        $key = $vName;
                        $sumRows2[$vName] = $vSpec['label'];
                        $color = "343434";
                        if (in_array($key, $editableFields)) {
                            $readOnly = "";
                        }
                        else {
                            $readOnly = "readonly";
                        }
                        $defaultValue = isset($addValues[$key]) ? $addValues[$key] : 0;
                        $sumSpec2[$key] = "<input type='text' readonly class='form-control text-right' name=$key id=$key value='$defaultValue' 
                        onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+this.value;}\"
                        onmouseout=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+this.value;}\"
                        >";
                        $sumType2[$key] = "number";
                        //endregion
                        if ($vSpec['taxFactor'] > 0) {
                            $key = $vName . "_tax";
                            $defaultValue = isset($addValues[$key]) ? $addValues[$key] : 0;
                            $sumRows2[$key] = "tax for " . $vSpec['label'];
                            $sumSpec2[$key] = "<input type='text' readonly class='form-control text-right' name=$key id=$key value='$defaultValue' 
                            onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+this.value;}\"
                            onmouseout=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src='" . $sumRowAction . "?key=$key&value='+this.value;}\"
                            >";
                            $sumType2[$key] = "number";
                        }
                    }
                }
            }
        }

        //endregion

        $tmpMasterValues = isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array();
        $addValues = array_merge(array_filter($addValues), array_filter($tmpMasterValues));

        //region elements & inputs (if any)
        $elStr = array();
        $elements = array();
        $elementsModal = array();
        $inputs = array();
        $addRows = array();
        $addRowLabels = array();
        $addRowHiddens = array();

        //==iterasi untuk memasukkan element relatif
        if (!isset($_SESSION[$cCode]['main_inputs'])) {
            $_SESSION[$cCode]['main_inputs'] = array();
        }
        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            foreach ($_SESSION[$cCode]['main_elements'] as $eName => $eSpec) {
                if (array_key_exists($eName, $relElementConfigs)) {
                    switch ($eSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $eSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $eSpec['value'];
                            break;
                    }
                    if (sizeof($relElementConfigs[$eName]) > 0) {
                        foreach ($relElementConfigs[$eName] as $valID => $valSpec) {
                            if ($currentValue == $valID) {

                            }
                            else {

                            }
                        }
                    }

                    if (array_key_exists($currentValue, $relElementConfigs[$eName])) {
                        //                        echo("-- $currentValue ada dalam elementConfig $eName<br>");
                        //===daftarkan ke elementConfig
                        if (sizeof($relElementConfigs[$eName][$currentValue]) > 0) {
                            foreach ($relElementConfigs[$eName][$currentValue] as $rKey => $rcSpec) {
                                $elKey = $rKey;
                                $elementConfigs[$elKey] = $relElementConfigs[$eName][$currentValue][$rKey];
                            }
                        }
                        else {
                            //                            echo("---- TIDAK PERLU memeriksa $eName, $currentValue<br>");
                        }
                    }
                    else {
                        //                        echo("-- $currentValue TIDAK ada dalam elementConfig $eName<br>");
                    }
                }
                else {
                    //                    echo("$eName TIDAK ada dalam elementConfig<br>");
                }
                if (array_key_exists($eName, $relOptionConfigs)) {
                    if (isset($relOptionConfigs[$eName][$currentValue])) {
                        if (sizeof($relOptionConfigs[$eName][$currentValue]) > 0) {
                            foreach ($relOptionConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                                if (isset($oValSpec['addPoints']) && in_array(1, $oValSpec['addPoints'])) {
                                    $relInputTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldInput/" . $this->jenisTr . "/$oValueName/?val='+this.value";

                                    //==init value and params
                                    //region default value
                                    if (isset($oValSpec['defaultValue'])) {
                                        $origDefValue = makeValue($oValSpec['defaultValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    }
                                    //endregion

                                    //region max-value
                                    $maxValue = $origDefValue;
                                    if (isset($oValSpec['maxValue'])) {
                                        $maxValue = makeValue($oValSpec['maxValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    }
                                    //endregion

                                    //region min-value
                                    $minValue = $origDefValue;
                                    if (isset($oValSpec['minValue'])) {
                                        $minValue = makeValue($oValSpec['minValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    }
                                    //endregion

                                    $defVal = isset($_SESSION[$cCode]['main_inputs'][$oValueName]) && $_SESSION[$cCode]['main_inputs'][$oValueName] > 0 ? $_SESSION[$cCode]['main_inputs'][$oValueName] : $origDefValue;
                                    $inputs[$oValueName] = "<input sini main_element type=number id='$oValueName'
                                                                class='form-control text-center'
                                                                placeholder='$oValueName'
                                                                value='$defVal'
                                                                min='$minValue'
                                                                max='$maxValue'
                                                                onfocus='this.select()'
                                                                onkeyup=\"if(parseInt(this.value)>$maxValue || parseInt(this.value)<$minValue){this.value='$origDefValue';}\"
onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src=$relInputTarget;}\"
onmouseout=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src =$relInputTarget;}\"
>";
                                    $_SESSION[$cCode]['main_inputs'][$oValueName] = $defVal;

                                    $inputLabels[$oValueName] = $oValSpec['label'] . "<small> (max: " . number_format($maxValue) . ")</small>";
                                }
                            }
                        }
                    }
                    else {
                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                    }
                }
                else {
                    //					cekKuning("$eName TIDAK terdaftar pada relInputs");
                }
            }
        }

        // matiHere(__LINE__ . __METHOD__);
        //==memproses awal elemen2 yang terlibat, jika ada yang bisa dipre-process
        //==misalnya yang pilihannya cuma satu atau yang ada config nilai defaultnya
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                $elementConfigs[$eName]['autoSelect'] = false;
                if (!isset($_SESSION[$cCode]['main_elements'][$eName])) {
                    if (isset($eSpec['defaultValue'])) {//==cek apakah ada seting defaultValue
                        $defValueSrc = $eSpec['defaultValue'];
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                heFetchElement_he_element($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $this->configUiJenis);
                                break;
                            case "dataField":
                                heRecordElement_he_element($this->jenisTr, $eName, $defValueSrc, $this->configUiJenis);
                                break;
                        }
                        $elementConfigs[$eName]['autoSelect'] = true;
                    }
                    else {//==cek apakah pilihannya cuma satu
                        if (isset($eSpec['noPrefetch']) && $eSpec['noPrefetch'] == true) {

                        }
                        else {
                            switch ($eSpec['elementType']) {
                                case "dataModel":
                                    $amdlName = $eSpec['mdlName'];
                                    $this->load->model("Mdls/" . $amdlName);
                                    $labelSrc = $eSpec['labelSrc'];
                                    $keySrc = $eSpec['key'];
                                    $oo = new $amdlName();
                                    $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();
                                    if (sizeof($aFilter) > 0) {
                                        $oo = makeFilter($aFilter, $_SESSION[$cCode]['main'], $oo);
                                    }
                                    $tmpo = $oo->lookupAll()->result();
                                    if (sizeof($tmpo) == 1) {
                                        $usedKey = $eSpec['key'];
                                        $defValueSrc = $tmpo[0]->$usedKey;
                                        $configUiJenis = $this->configUi[$this->jenisTr];
                                        heFetchElement_he_element($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $configUiJenis);
                                    }
                                    break;
                                case "dataField":
                                    break;
                            }
                        }
                    }
                }
                else {
                    //                    cekHere(":: HOHOHO ::");
                    if (isset($eSpec['noPrefetch']) && $eSpec['noPrefetch'] == true) {

                    }
                    else {
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                $amdlName = $eSpec['mdlName'];
                                $this->load->model("Mdls/" . $amdlName);
                                $labelSrc = $eSpec['labelSrc'];
                                $keySrc = $eSpec['key'];
                                $oo = new $amdlName();
                                $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                                if (sizeof($aFilter) > 0) {
                                    $oo = makeFilter($aFilter, $_SESSION[$cCode]['main'], $oo);
                                }
                                $tmpo = $oo->lookupAll()->result();
                                if (sizeof($tmpo) == 1) {
                                    $usedKey = $eSpec['key'];
                                    $defValueSrc = $tmpo[0]->$usedKey;
                                    $configUiJenis = $this->configUi[$this->jenisTr];
                                    heFetchElement_he_element($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $configUiJenis);
                                }
                                break;
                            case "dataField":
                                break;
                        }
                    }
                }
            }
        }

        $_SESSION[$cCode]['payment'] = array();
        //==menciptakan selektor/pilihan berdasarkan jenis elemen
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {

                //reset dulu kalau yg tidak ada
                if (array_key_exists($eName, $relElementConfigs)) {
                    switch ($eSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $eSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $eSpec['value'];
                            break;
                    }

                    if (array_key_exists($currentValue, $relElementConfigs[$eName])) {
                        //===daftarkan ke elementConfig
                        if (sizeof($relElementConfigs[$eName][$currentValue]) > 0) {
                            foreach ($relElementConfigs[$eName][$currentValue] as $rKey => $rcSpec) {
                                $elKey = $rKey;
                                $elementConfigs[$elKey] = $relElementConfigs[$eName][$currentValue][$rKey];
                            }
                        }
                        else {
                            //                            echo("---- TIDAK PERLU memeriksa $eName, $currentValue<br>");
                        }
                    }
                    else {
                        //                        echo("-- $currentValue TIDAK ada dalam elementConfig $eName<br>");
                    }
                }
                else {
                    //                    echo("$eName TIDAK ada dalam elementConfig<br>");
                }


                if (array_key_exists($eName, $addRowsConfigs)) {
                    switch ($elementConfigs[$eName]['elementType']) {
                        case "dataModel":
                            $currentValue = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : "";
                            break;
                        case "dataField":
                            $currentValue = $_SESSION[$cCode]['main_elements'][$eName]['value'];
                            break;
                    }

                    if (isset($addRowsConfigs[$eName][$currentValue])) {
                        if (sizeof($addRowsConfigs[$eName][$currentValue]) > 0) {
//                            cekMerah($currentValue);
//                            $_SESSION[$cCode]['payment'][$eName][$oValueName] = removeCommas($defVal);

                            foreach ($addRowsConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {

//                                cekMerah($oValueName);
//                                cekHijau("oValueName: ".$oValueName . " | oValSpec: " . $oValSpec);

                                if (isset($oValSpec['addPoints']) && in_array(1, $oValSpec['addPoints'])) {

//                                    cekHijau($oValSpec);

                                    $relInputTarget = "'" . MODUL_PATH . get_class($this) . "/recordAddRow/" . $this->jenisTr . "/$oValueName/?val='+removeCommas(this.value)";

                                    //==init value and params
                                    //region default value
                                    if (isset($oValSpec['defaultValue'])) {
                                        $origDefValue = makeValue($oValSpec['defaultValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    }
                                    //endregion

                                    if (isset($oValSpec['hideRow']) && $oValSpec['hideRow'] == true) {
                                        $addRowHiddens[$oValueName] = "hidden";
                                    }

                                    //region max-value
                                    $maxValue = $origDefValue;
                                    if (isset($oValSpec['maxValue'])) {
                                        $maxValue = makeValue($oValSpec['maxValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    }
                                    else {
                                        $maxValue = "";
                                    }
                                    //endregion

                                    //region min-value
                                    $minValue = $origDefValue;
                                    if (isset($oValSpec['minValue'])) {
                                        $minValue = makeValue($oValSpec['minValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    }
                                    else {
                                        $minValue = "";
                                    }
                                    //endregion

                                    $minValStr = $minValue != "" ? "min='$minValue'" : "";
                                    $maxValStr = $maxValue != "" ? "max='$maxValue'" : "";

                                    //region inisiasi keystroke
                                    $keyupAct = "";
                                    if (isset($oValSpec['keyupAction']) && strlen($oValSpec['keyupAction']) > 0) {
                                        $keyupAct = $oValSpec['keyupAction'];
                                    }

                                    $keyupStr = "";
                                    if ($maxValue != "") {
                                        $keyupStr .= "if(parseInt(removeCommas(this.value))>$maxValue){this.value='$origDefValue';console.log('keyup:'+this.value);console.log('origDefValue: $origDefValue');this.select();} ";
                                    }
                                    $keyupStr .= $keyupAct;

                                    $disabled = "";
                                    if (isset($oValSpec['disabled'])) {
                                        $disabled = $oValSpec['disabled'];
                                    }

                                    $blurStr = "";
                                    if ($minValue != "") {
                                        $blurStr = "if(removeCommas(this.value)!=removeCommas(this.defaultValue)){console.log('this.defaultValue: '+ this.defaultValue);console.log('this.value: '+ this.value);if(parseInt(removeCommas(this.value))>=$minValue){hiliteDiv(this);document.getElementById('result').src=$relInputTarget;}else{this.values='$minValue';this.focus();}}";
                                    }
                                    else {
                                        $blurStr = "if(removeCommas(this.value)!=removeCommas(this.defaultValue)){hiliteDiv(this);document.getElementById('result').src=$relInputTarget;}";
                                    }
                                    //endregion

                                    $defVal = isset($_SESSION[$cCode]['main'][$oValueName]) && $_SESSION[$cCode]['main'][$oValueName] > 0 ? ( removeCommas($_SESSION[$cCode]['main'][$oValueName]) + 0) : removeCommas($origDefValue);

                                    if (isset($addRowsConfigs[$eName][$currentValue][$oValueName]['role']) && $addRowsConfigs[$eName][$currentValue][$oValueName]['role'] == "minus") {
                                        $defVal = "(" . $defVal . ")";
                                    }

                                    $background_input_bisa_isi = $disabled!="" ? "" : "background:#ffc800;" ;

                                    $addRows[$oValueName] = "<input " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=text autocomplete='off' id='$oValueName' class='form-control text-right' style='font-size:17px;$background_input_bisa_isi' $disabled placeholder='$oValueName' value='".addCommas($defVal)."' $minValStr $maxValStr
                                                                onfocus='this.select()'
                                                                onkeyup=\"$keyupStr\"
                                                                onfocusxx=\"$keyupStr\"
                                                                onblurxx=\"$blurStr\"
                                                                onmouseout=\"$blurStr\"
                                                                >";

                                    $_SESSION[$cCode]['add_rows'][$oValueName] = removeCommas($defVal);
                                    $addRowLabels[$oValueName] = $oValSpec['label'];

                                    if( isset($oValSpec['groupLabel']) && $oValSpec['groupLabel'] == "payment" ) {
                                        $_SESSION[$cCode]['payment'][$currentValue][$oValueName] = removeCommas($defVal);
                                        if( removeCommas($defVal) *1 > 0){
                                            $addRowLabels["extra_".$oValueName] = $currentValue;
                                            $addRows["extra_".$oValueName] = "<div>pilihan account penerimaan</div>";
                                }
                            }

                                    if($oValueName=="voucher"){

                                        // $_SESSION[$cCode]['payment'][$oValueName][$oValueName] = removeCommas($defVal);

                                        $addRowLabels["nilai_".$oValueName] = "Nilai Voucher";
                                        $addRows["nilai_".$oValueName] = "<input
                                            type=text
                                            disabled
                                            id='nilai_$oValueName'
                                            class='form-control text-right'
                                            style='font-size:17px;'
                                            placeholder='nilai $oValueName'
                                            value='".addCommas($defVal)."'
                                        >";
                        }


                    }
                            }
                        }
                    }
                    else {
                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                        //                        cekmerah("aturan untuk $currentValue TIDAK ada");
                    }
                }
                else {
                    //					cekKuning("$eName TIDAK terdaftar pada relInputs");
                }

                switch ($eSpec['elementType']) {
                    case "dataModel":
                        $addStr = "";
                        $editStr = "";
                        $amdlName = $eSpec['mdlName'];
                        $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                        $elStr[$eName] = "";
                        $this->load->model("Mdls/" . $amdlName);
                        $labelSrc = $eSpec['labelSrc'];
                        $keySrc = $eSpec['key'];
                        $oo = new $amdlName();
                        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);

                        if (sizeof($aFilter) > 0) {
                            foreach ($aFilter as $filter) {
                                $exFilter = explode("=", $filter);
                                if (sizeof($exFilter) > 1) {
                                    if (substr($exFilter[1], 0, 1) == ".") {
                                        //                                        $oo->addFilter($exFilter[0] . "='" . ltrim($exFilter[1], ".") . "'");
                                    }
                                    else {
                                        if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                            //                                            $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                            $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $_SESSION[$cCode]['main'][$exFilter[1]];
                                        }
                                        else {
                                            //                                            $oo->addFilter($exFilter[0] . "='none'");
                                        }
                                    }
                                }
                            }
                            $oo = makeFilter($aFilter, $_SESSION[$cCode]['main'], $oo);
                        }

                        $addClick = "";
                        $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array("viewers" => array(),
                            "creators" => array(),
                            "creatorAdmins" => array(),
                            "updaters" => array(),
                            "updaterAdmins" => array(),
                            "deleters" => array(),
                            "deleterAdmins" => array(),
                            "historyViewers" => array(),
                        );
                        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                    });";
                                $addStr = "<a href='javascript:void(0)' class='btn btn-tool' onclick=\"$addClick\"><span class='glyphicon glyphicon-plus'></span></a>";
                                        }
                            }

                        $tmpo = $oo->lookupAll()->result();
                        //                        cekmerah($this->db->last_query());
                        $elPair[$amdlName] = array();
                        $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+this.value";

                        $elStr[$eName] .= "<div class='box-body'>";

                        switch ($eSpec['inputType']) {
                            case "combo":
                                $elStr[$eName] .= "<select class='form-control' onchange=\"hiliteDiv(this);document.getElementById('result').src=$selectorTarget;\">";
                                $elStr[$eName] .= "<option value=''>-select-</option>";
                                if (sizeof($tmpo) > 0) {
                                    foreach ($tmpo as $row) {
                                        $ex = explode("/", $elementConfigs[$eName]['labelSrc']);
                                        if (sizeof($ex) > 1) {
                                            $labelValue = "";
                                            foreach ($ex as $col) {
                                                $labelValue .= $row->$col . " / ";
                                            }
                                            $labelValue = rtrim($labelValue, " / ");
                                            $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                            $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";

                                            $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                            $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                            $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $labelValue . "</option>";
                                            //                                            $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $$labelValue . "</option>";

                                        }
                                        else {
                                            $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                            $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                            $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";
                                        }


                                    }
                                }
                                $elStr[$eName] .= "</select>";
                                break;
                            case "radio":

                                if (sizeof($tmpo) > 0) {
                                    foreach ($tmpo as $row) {
                                        $ex = explode("/", $elementConfigs[$eName]['labelSrc']);
                                        if (sizeof($ex) > 1) {
                                            $labelValue = "";
                                            foreach ($ex as $col) {
                                                $labelValue .= $row->$col . " / ";
                                            }
                                            $labelValue = rtrim($labelValue, " / ");
                                            $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                            $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";
                                            $elStr[$eName] .= "<label class='badge text-uppercase' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);document.getElementById('result').src =$selectorTarget;\">" . $labelValue . "</label>\n";
                                        }
                                        else {
                                            $elPair[$amdlName][$row->$keySrc] = isset($row->$labelSrc) ? $row->$labelSrc : "-";
                                            $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";
                                            $elStr[$eName] .= "<label class='badge text-uppercase' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);document.getElementById('result').src =$selectorTarget;\">" . (isset($row->$labelSrc) ? $row->$labelSrc : '-') . "</label>\n";
                                        }

                                    }
                                }
                                break;
                        }


                        $elStr[$eName] .= "</div class='box-header'>";

                        $defKey = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : 0;
                        $showNull = isset($elementConfigs[$eName]['showNull']) ? $elementConfigs[$eName]['showNull'] : false;
                        $nullValue = isset($elementConfigs[$eName]['nullValue']) ? $elementConfigs[$eName]['nullValue'] : "";
                        $nullSrc = isset($elementConfigs[$eName]['nullSrc']) ? $elementConfigs[$eName]['nullSrc'] : "";

                        $defValue = "";
                        if (isset($_SESSION[$cCode]['main_elements'][$eName]['key']) && $_SESSION[$cCode]['main_elements'][$eName]['contents']) {
                            if (isset($elementConfigs[$eName]['usedFields']) && sizeof($elementConfigs[$eName]['usedFields']) > 0) {
                                //								$defValue .= "<table class='table table-condensed no-padding' style='padding:0px;margin:0px;'>";
                                $defValue .= "<div class='panel-body'>";
                                $defValue .= "<table cellspacing='0' cellpadding='0' border='0'>";
                                $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['main_elements'][$eName]['contents']));
                                $semicolonnbsp = "";
                                foreach ($elementConfigs[$eName]['usedFields'] as $src => $label) {
                                    $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                    $defValue .= "<tr " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . "'>";
                                    if (strlen($fieldLabel) > 0 || $showNull == true) {
                                        if (strlen($label) > 0) {
                                            $defValue .= "<td class='text-capitalize' align='left'>$label";
                                            $defValue .= "&nbsp;</td>";
                                            $semicolonnbsp = ":&nbsp; ";
                                            $newValue_r = $fieldLabel == "" && $showNull == true && $nullValue != "" ? ($nullSrc == $label ? $nullValue : formatField_he_format($src, $fieldLabel)) : formatField_he_format($src, $fieldLabel);
                                            if ($src == 'saldo') {
                                                $arrNewValue_r = explode('+', $newValue_r);
                                                $newSaldo = 0;
                                                if (sizeof($arrNewValue_r) > 0) {
                                                    foreach ($arrNewValue_r as $k => $kVal) {
                                                        $newSaldo += $kVal;
                                                    }
                                                }
                                                $newValue_r = $newSaldo > 0 ? "<span class='text-bold text-green'>" . number_format($newSaldo) . "</span>" : "<span class='text-bold text-red'>SALDO KOSONG</span>";
                                            }
                                            $defValue .= "<td $label align='left' class='text-bold text-uppercase'>$semicolonnbsp" . $newValue_r;
                                            $defValue .= "</td>";
                                        }
                                        else {
                                            $defValue .= "<td align='left' colspan='2' class='text-bold text-uppercase'>$semicolonnbsp " . formatField_he_format($src, $fieldLabel);
                                            $defValue .= "</td>";
                                        }
                                    }
                                    $defValue .= "</tr>";
                                }
                                $defValue .= "</table>";
                                $defValue .= "</div class='panel-body'>";
                            }
                        }
                        else {//menentukan nilai default

                        }

                        if ($defKey > 0) {
                            if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                    $editClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $editLink . "'),
                                        draggable:true,
                                        size:BootstrapDialog.SIZE_WIDE,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                        }
                                        );";

                                    $editStr = "<a href='javascript:void(0)' class='btn btn-tool' onclick=\"$editClick\"><span class='glyphicon glyphicon-pencil'></span></a>";
                                }
                            }
                        }

                        $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                        $elStr[$eName] .= "</div id='el$amdlName'>";

                        $elements[$eName] = array("type" => $eSpec['inputType'],
                            "mdlName" => $eSpec['mdlName'],
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                            "editStr" => $editStr,
                            "addStr" => $addStr,
                            "bgColor" => $defValue == "" ? "#fcfce0" : "#f5fff9",
                        );


                        break;
                    case "dataField":
                        $elStr[$eName] = "";
                        $initValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                        //                        $defaultValue = isset($_SESSION[$cCode]['main_elements'][$eName]['value']) ? $_SESSION[$cCode]['main_elements'][$eName]['value'] : "";
                        $defaultValue = isset($_SESSION[$cCode]['main'][$eName]) ? $_SESSION[$cCode]['main'][$eName] : 0;
                        $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+this.value";
                        //                        $elStr[$eName] .="<div class='box'>";

                        $maxValue = isset($eSpec['maxValue']) && isset($_SESSION[$cCode]['main'][$eSpec['maxValue']]) ? $_SESSION[$cCode]['main'][$eSpec['maxValue']] : "";

                        $elStr[$eName] .= "<div class='box-body'>";
                        switch ($eSpec['inputType']) {
                            case "text":
                                $elStr[$eName] .= "<input " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=text class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\"
onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);document.getElementById('result').src=$selectorTarget;}\">";
                                break;
                            case "number":
                                $maxValStr = $maxValue != "" ? " max='" . $maxValue . "''" : "";
                                $maxValValidator = $maxValue != "" ? " onkeyup=\"if(this.value>$maxValue){this.value='$maxValue';}\" " : "";
                                $elStr[$eName] .= "<input " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=number class='form-control' value='$defaultValue' onfocus='this.select()' $maxValStr $maxValValidator oonclick=\"this.value='$defaultValue';\"
onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);document.getElementById('result').src=$selectorTarget;}\">";
                                break;
                            case "date":
                                $elStr[$eName] .= "<input " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=date class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\"
onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);document.getElementById('result').src=$selectorTarget;}\">";
                                break;
                        }
                        $elStr[$eName] .= "</div class='box-body'>";

                        $elements[$eName] = array("mdlName" => null,
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                            "editStr" => "",
                            "addStr" => "",
                            "bgColor" => $defaultValue == "" ? "#fcfce0" : "#fcfcff",
                        );

                        break;
                }
            }
        }

        //endregion

        //region items element auto build.
        if (sizeof($elementItemsAutoConfigs) > 0) {
            if (isset($_SESSION[$cCode]['items'])) {
                foreach ($_SESSION[$cCode]['items'] as $iID => $iSpec) {
                    foreach ($elementItemsAutoConfigs as $eSpec) {
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                $addStr = "";
                                $editStr = "";
                                $amdlName = $eSpec['mdlName'];
                                $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                                $iLabel = $iSpec['nama'];
                                $eName = $iID;
                                $helpName = "pembantu";

                                $elStr[$eName] = "";
                                $this->load->model("Mdls/" . $amdlName);
                                $labelSrc = $eSpec['labelSrc'];
                                $keySrc = $eSpec['key'];
                                $oo = new $amdlName();
                                $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);

                                if (sizeof($aFilter) > 0) {
                                    foreach ($aFilter as $filter) {
                                        $exFilter = explode("=", $filter);
                                        if (sizeof($exFilter) > 1) {
                                            if (substr($exFilter[1], 0, 1) == ".") {
                                                //                                        $oo->addFilter($exFilter[0] . "='" . ltrim($exFilter[1], ".") . "'");
                                            }
                                            else {
                                                if (isset($iSpec[$exFilter[1]])) {
                                                    //                                            $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                                    $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $iSpec[$exFilter[1]];
                                                }
                                                else {
                                                    //                                            $oo->addFilter($exFilter[0] . "='none'");
                                                }
                                            }
                                        }
                                    }
                                    $oo = makeFilter($aFilter, $iSpec, $oo);
                                }

                                $addClick = "";
                                $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array("viewers" => array(),
                                    "creators" => array(),
                                    "creatorAdmins" => array(),
                                    "updaters" => array(),
                                    "updaterAdmins" => array(),
                                    "deleters" => array(),
                                    "deleterAdmins" => array(),
                                    "historyViewers" => array(),
                                );
                                $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                                if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                                    if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                        $addClick = "
                                    top.BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                            message: top.$('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                        }
                                        );";
                                        $addStr = "<a " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " href='JavaScript:void(0)' class='btn btn-tool' onclick=\"$addClick\"><span class='glyphicon glyphicon-plus'></span></a>";
                                    }
                                }

                                $tmpo = $oo->lookupAll()->result();
//                                cekmerah($this->db->last_query());


                                $elPair[$amdlName] = array();
                                $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/fetchItemsElement/" . $this->jenisTr . "/$eName/$amdlName/$helpName?key='+this.value";

                                $elStr[$eName] .= "<div class='box-body'>";
                                //                                cekHitam(": $eName :");
                                switch ($eSpec['inputType']) {
                                    case "combo":
                                        $elStr[$eName] .= "<select " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " class='form-control' onchange=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">";
                                        $elStr[$eName] .= "<option value=''>-select-</option>";
                                        if (sizeof($tmpo) > 0) {
                                            foreach ($tmpo as $row) {
                                                //                                                cekPink2($row->$keySrc);
                                                $ex = explode("/", $eSpec['labelSrc']);
                                                if (sizeof($ex) > 1) {
                                                    $labelValue = "";
                                                    foreach ($ex as $col) {

                                                        $labelValue .= $row->$col . " / ";
                                                    }
                                                    $labelValue = rtrim($labelValue, " / ");
                                                    $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                    $selected = isset($_SESSION[$cCode]['items'][$eName][$helpName]) && $_SESSION[$cCode]['items'][$eName][$helpName] == $row->$keySrc ? "checked" : "";

                                                    $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                    $selected = isset($_SESSION[$cCode]['items'][$eName][$helpName]) && $_SESSION[$cCode]['items'][$eName][$helpName] == $row->$keySrc ? "selected" : "";
                                                    $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $labelValue . "</option>";

                                                }
                                                else {
                                                    $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                                    $selected = isset($_SESSION[$cCode]['items'][$eName][$helpName]) && $_SESSION[$cCode]['items'][$eName][$helpName] == $row->$keySrc ? "selected" : "";
                                                    $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";
                                                }


                                            }
                                        }
                                        $elStr[$eName] .= "</select>";
                                        break;
                                    case "radio":

                                        if (sizeof($tmpo) > 0) {
                                            foreach ($tmpo as $row) {
                                                $ex = explode("/", $eSpec['labelSrc']);
                                                if (sizeof($ex) > 1) {
                                                    $labelValue = "";
                                                    foreach ($ex as $col) {
                                                        $labelValue .= $row->$col . " / ";
                                                    }
                                                    $labelValue = rtrim($labelValue, " / ");
                                                    $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                    $selected = isset($_SESSION[$cCode]['items'][$eName][$helpName]) && $_SESSION[$cCode]['items'][$eName][$helpName] == $row->$keySrc ? "checked" : "";
                                                    $elStr[$eName] .= "<label class='badge text-uppercase' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">" . $labelValue . "</label>\n";
                                                }
                                                else {
                                                    $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                                    $selected = isset($_SESSION[$cCode]['items'][$eName][$helpName]) && $_SESSION[$cCode]['items'][$eName][$helpName] == $row->$keySrc ? "checked" : "";
                                                    $elStr[$eName] .= "<label class='badge text-uppercase' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">" . $row->$labelSrc . "</label>\n";
                                                }

                                            }
                                        }
                                        break;
                                }


                                $elStr[$eName] .= "</div class='box-header'>";

                                $defKey = isset($_SESSION[$cCode]['items'][$eName][$helpName]) ? $_SESSION[$cCode]['items'][$eName][$helpName] : 0;
                                $showNull = isset($eSpec['showNull']) ? $eSpec['showNull'] : false;
                                $nullValue = isset($eSpec['nullValue']) ? $eSpec['nullValue'] : "";
                                $nullSrc = isset($eSpec['nullSrc']) ? $eSpec['nullSrc'] : "";

                                $defValue = "";
                                if (isset($_SESSION[$cCode]['items_elements'][$eName]['key']) && $_SESSION[$cCode]['items_elements'][$eName]['contents']) {
                                    if (isset($eSpec['usedFields']) && sizeof($eSpec['usedFields']) > 0) {

                                        $defValue .= "<div class='panel-body'>";
                                        $defValue .= "<table cellspacing='0' cellpadding='0' border='0'>";
                                        $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['items_elements'][$eName]['contents']));
                                        $semicolonnbsp = "";
                                        foreach ($eSpec['usedFields'] as $src => $label) {
                                            $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                            $defValue .= "<tr " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . "'>";
                                            if (strlen($fieldLabel) > 0 || $showNull == true) {
                                                if (strlen($label) > 0) {
                                                    $defValue .= "<td class='text-capitalize' align='left'>$label";
                                                    $defValue .= "&nbsp;</td>";
                                                    $semicolonnbsp = ":&nbsp;";
                                                    $newValue_r = $fieldLabel == "" && $showNull == true && $nullValue != "" ? ($nullSrc == $label ? $nullValue : formatField_he_format($src, $fieldLabel)) : formatField_he_format($src, $fieldLabel);
                                                    if ($src == 'saldo') {
                                                        $arrNewValue_r = explode('+', $newValue_r);
                                                        $newSaldo = 0;
                                                        if (sizeof($arrNewValue_r) > 0) {
                                                            foreach ($arrNewValue_r as $k => $kVal) {
                                                                $newSaldo += $kVal;
                                                            }
                                                        }
                                                        $newValue_r = $newSaldo > 0 ? "<span class='text-bold text-green'>" . number_format($newSaldo) . "</span>" : "<span class='text-bold text-red'>SALDO KOSONG</span>";
                                                    }
                                                    $defValue .= "<td $label align='left' class='text-bold text-uppercase'>$semicolonnbsp" . $newValue_r;
                                                    $defValue .= "</td>";
                                                }
                                                else {
                                                    $defValue .= "<td align='left' colspan='2' class='text-bold text-uppercase'>$semicolonnbsp" . formatField_he_format($src, $fieldLabel);
                                                    $defValue .= "</td>";
                                                }
                                            }
                                            $defValue .= "</tr>";
                                        }
                                        $defValue .= "</table>";
                                        $defValue .= "</div class='panel-body'>";
                                    }
                                }
                                else {//menentukan nilai default

                                }

                                //                                if ($defKey > 0) {
                                //                                    if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                //                                        $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                //                                        if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                //                                            $editClick = "
                                //                    top.BootstrapDialog.show(
                                //                                   {
                                //                                        title:'New " . $eSpec['label'] . "',
                                //                                        message: top.$('<div></div>').load('" . $editLink . "'),
                                //                                        draggable:true,
                                //                                        size:BootstrapDialog.SIZE_WIDE,
                                //                                        closable:true,
                                //                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                //                                        }
                                //                                        );";
                                //
                                //                                            $editStr = "<a " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " href='JavaScript:void(0)' class='btn btn-tool' onclick=\"$editClick\"><span class='glyphicon glyphicon-pencil'></span></a>";
                                //                                        }
                                //                                    }
                                //                                }

                                $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                                $elStr[$eName] .= "</div id='el$amdlName'>";


                                $nonStr[$eName] = "";
                                $nonStr[$eName] .= "<div class='alert alert-warning' style='font-weight: bold;'>";
                                $nonStr[$eName] .= $eSpec['nullValue'];
                                $nonStr[$eName] .= "</div>";

                                $itemsElements[$eName] = array("type" => $eSpec['inputType'],
                                    "mdlName" => $eSpec['mdlName'],
                                    "label" => $eSpec['label'] . " $iLabel ",
                                    //                                    "string" => $elStr[$eName],
                                    "string" => sizeof($tmpo) > 0 ? $elStr[$eName] : $nonStr[$eName],
                                    "editStr" => $editStr,
                                    "addStr" => $addStr,
                                    "bgColor" => $defValue == "" ? "#fcfce0" : "#f5fff9",
                                    "helpName" => $helpName,
                                );


                                break;
                            case "dataField":
                                $iLabel = $iSpec['nama'];
                                $eName = $iID;

                                $elStr[$eName] = "";
                                $initValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                                $defaultValue = isset($iSpec[$eName]) ? $iSpec[$eName] : 0;
                                $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldItemsElement/" . $this->jenisTr . "/$eName/$amdlName/$helpName?val='+this.value";

                                $maxValue = isset($eSpec['maxValue']) && isset($iSpec[$eSpec['maxValue']]) ? $iSpec[$eSpec['maxValue']] : "";

                                $elStr[$eName] .= "<div class='box-body'>";
                                switch ($eSpec['inputType']) {
                                    case "text":
                                        $elStr[$eName] .= "<input " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=text class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\"
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                        break;
                                    case "number":
                                        $maxValStr = $maxValue != "" ? " max='" . $maxValue . "''" : "";
                                        $maxValValidator = $maxValue != "" ? " onkeyup=\"if(this.value>$maxValue){this.value='$maxValue';}\" " : "";
                                        $elStr[$eName] .= "<input sini bukan " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=text class='form-control' value='$defaultValue' onfocus='this.select()' $maxValStr $maxValValidator oonclick=\"this.value='$defaultValue';\"
onblur=\"if(removeCommas(this.value)!=removeCommas(this.defaultValue)){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                        break;
                                    case "date":
                                        $elStr[$eName] .= "<input " . basename(__FILE__) . " " . __FUNCTION__ . " " . __LINE__ . " type=date class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\"
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                        break;
                                }
                                $elStr[$eName] .= "</div class='box-body'>";

                                $itemsElements[$eName] = array("mdlName" => null,
                                    "label" => $eSpec['label'] . " $iLabel ",
                                    "string" => $elStr[$eName],
                                    "editStr" => "",
                                    "addStr" => "",
                                    "bgColor" => $defaultValue == "" ? "#fcfce0" : "#fcfcff",
                                    "helpName" => $helpName,
                                );

                                break;
                        }
                    }
                }
            }
        }
        //endregion

        $tmpMasterValues = isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array();

        /* ----------------------------------------------
         * kiriman ke shoping cart
         * ----------------------------------------------*/
        foreach ($main_tmp as $key => $item_val) {
            $main[$key] = $item_val;
        }
        $main = $main + $tmpMasterValues;

        //bersihkan elemen yang tidak relevan
        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            foreach ($_SESSION[$cCode]['main_elements'] as $elName => $elSpec) {

                if (!array_key_exists($elName, $elementConfigs)) {
                    $_SESSION[$cCode]['main_elements'][$elName] = null;
                    unset($_SESSION[$cCode]['main_elements'][$elName]);

                    $mainResetList = array($elName,
                        $elName . "__label"
                    );
                    foreach ($mainResetList as $kk) {
                        if (isset($_SESSION[$cCode]['main'][$kk])) {
                            $_SESSION[$cCode]['main'][$kk] = null;
                            unset($_SESSION[$cCode]['main'][$kk]);
                        }
                    }
                }
            }
        }

        $arrCons = array();
        $headerScheme = array();

        if ($showScheme) {

            $awal_pinjaman = isset($_SESSION[$cCode]['main']['awal_pinjaman']) ? $_SESSION[$cCode]['main']['awal_pinjaman'] : date('Y-m-d');
            $jatuh_tempo = isset($_SESSION[$cCode]['main']['jatuh_tempo']) ? $_SESSION[$cCode]['main']['jatuh_tempo'] : date('Y-m-d');
            $nilai_pinjaman = isset($_SESSION[$cCode]['main']['harga']) ? $_SESSION[$cCode]['main']['harga'] : 0;
            $rate_bunga = isset($_SESSION[$cCode]['main']['persen_bunga']) ? $_SESSION[$cCode]['main']['persen_bunga'] : 0;

            $npwp = "";
            $pph_nilai = strlen($npwp) > 10 && $pph_nilai == 15 ? 15 : 15; //dipaksa 15% untuk pemegang saham
            $valid_bunga = ($nilai_pinjaman / 12);
            $nilai_bunga = ($valid_bunga * $rate_bunga) / 100;
            $nilai_pph23 = ($nilai_bunga * $pph_nilai) / 100;

            $period = new DatePeriod(new DateTime($awal_pinjaman), new DateInterval('P1D'), new DateTime($jatuh_tempo));

            $periodNow = new DatePeriod(new DateTime($awal_pinjaman), new DateInterval('P1D'), new DateTime(date('Y-m-d')));

            $arrBulan = array();
            $arrBulanNow = array();
            $arrHarian = array();
            $arrWaktu = array();

            foreach ($period as $key => $value) {
                if (!isset($arrBulan[$value->format('Y-m')])) {
                    $arrBulan[$value->format('Y-m')] = array();
                }
                $arrBulan[$value->format('Y-m')][] = $value->format('Y-m-d');
            }

            foreach ($periodNow as $key => $value) {
                if (!isset($arrBulanNow[$value->format('Y-m')])) {
                    $arrBulanNow[$value->format('Y-m')] = array();
                }
                $arrBulanNow[$value->format('Y-m')][] = $value->format('Y-m-d');
            }

            $hariPadaBulanJatuhTempo = isset($arrBulan[date('Y-m', strtotime($jatuh_tempo))]) ? count($arrBulan[date('Y-m', strtotime($jatuh_tempo))]) : 0;
            $arrBulan[date('Y-m', strtotime($jatuh_tempo))][$hariPadaBulanJatuhTempo] = date('Y-m-d', strtotime($jatuh_tempo));


            $total_hari = 0;
            $total_bulan = 0;
            foreach ($arrBulan as $thnbln => $thblntgl) {
                $tmp = array("thnbln" => $thnbln,
                    "jml_hari_dbln" => count($arrBulan[$thnbln]),
                    "nilai_pinjaman" => $nilai_pinjaman,
                    "rate_bunga" => $rate_bunga,
                    "valid_bunga" => $valid_bunga * (count($arrBulan[$thnbln]) / 30),
                    "nilai_bunga" => $nilai_bunga * (count($arrBulan[$thnbln]) / 30),
                    "nilai_pph23" => $nilai_pph23 * (count($arrBulan[$thnbln]) / 30),
                    "nett_bunga" => $nilai_bunga * (count($arrBulan[$thnbln]) / 30) - ($nilai_pph23 * (count($arrBulan[$thnbln]) / 30)),
                    "silangan" => isset($arrBulanNow[$thnbln]) ? ($thnbln != date('Y-m') ? "hijau" : "berjalan") : "merah",
                );
                if (!isset($arrCons[$thnbln])) {
                    $arrCons[$thnbln] = array();
                }
                $arrCons[$thnbln] = $tmp;
                $total_bulan++;
                $total_hari += count($arrBulan[$thnbln]);
            }

            $nmPemengangSaham = "belum memilih kreditur";
            foreach ($items as $ids => $data) {
                $nmPemengangSaham = isset($data['nama']) ? $data['nama'] : "<span class='text-bol text-red'>belum ditentunkan</span>";

                // $hargaItems[]
            }

            $headerScheme = array("nama" => "$nmPemengangSaham",
                "jml_pinjaman" => "$nilai_pinjaman",
                "bunga_tahunan" => "$rate_bunga",
                "awal_meminjam" => date('d F Y', strtotime($awal_pinjaman)),
                "pelunasan_pinjaman" => date('d F Y', strtotime($jatuh_tempo)),
                "lama_pinjaman" => "$total_hari hari ($total_bulan bln)",
            );

        }
        $detilSizeBar = array();

        if (isset($elements['detilSize'])) {
            $detilSizeBar = array(
                //CKD
                "volume_gross" => isset($main['volume_gross']) ? number_format(conv_mmc_mc($main['volume_gross']), 2) : 0,
                "berat_gross" => isset($main['berat_gross']) ? conv_g_kg($main['berat_gross']) : 0,
                //CBU
                "volume" => isset($main['volume']) ? number_format(conv_mmc_mc($main['volume']), 2) : 0,
                "berat" => isset($main['berat']) ? conv_g_kg($main['berat']) : 0,
            );
        }
        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
            if (sizeof($itemsLabelReplacer) > 0) {
                foreach ($itemsLabelReplacer as $key => $keyVal) {
                    $itemLabels[$key] = $_SESSION[$cCode]['items'][$id][$keyVal];
                }
            }
        }

        $paramForceEditable = array();
        if (sizeof($shopingCartParamForceEditable) > 0) {
            foreach ($shopingCartParamForceEditable as $paramsKey => $paramGate) {
                $paramForceEditable = isset($_SESSION[$cCode][$paramsKey]) ? $_SESSION[$cCode][$paramsKey] : array();
            }
        }

        //-------------------------------------------------------------------------------
        $elementMutasiConfig = $this->config->item("accountElementMutasi") != NULL ? $this->config->item("accountElementMutasi") : array();
        $elementMutasi = array();
        if (sizeof($elementMutasiConfig) > 0) {
            if ($this->session->login['cabang_id'] < 0) {
                $subjectID = isset($_SESSION[$cCode]['main']['pihakID']) ? $_SESSION[$cCode]['main']['pihakID'] : "";
                $elementMutasiTmp = $elementMutasiConfig["center"];
                foreach ($elementMutasiTmp as $el_nama => $el_spec) {
                    $elementMutasi[$el_nama] = base_url() . $el_spec['link'] . "$subjectID?o=" . $this->session->login['cabang_id'];
                }
            }
        }

        /*
         * Lock Transaksi jika ada cancel yang masih gantung...
         */
        $heTransaksi_ui = isset($this->configUi[$this->jenisTr]['checkReturnStatus']) && $this->configUi[$this->jenisTr]['checkReturnStatus'] == "false" ? "false" : "true";
        $jMaster = isset($this->configUi[$this->jenisTr]['rejectedTraget']) ? $this->configUi[$this->jenisTr]['rejectedTraget'] : "false";
        $lockTransaksi = 0;
        if($heTransaksi_ui){
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("div_id='" . $this->session->login['div_id'] . "'");
            $tr->addFilter("next_substep_code<>''");
            $tr->addFilter("sub_step_number>0");
            $tr->addFilter("valid_qty>0");
            $tr->addFilter("jenis_master='$jMaster'");
            $tmpTr = $tr->lookupUndoneEntries_joined(replaceSession())->result();
            if(!empty($tmpTr)){
                $lockTransaksi = count($tmpTr);
            }
        }

        //-------------------------------------------------------------------------------
        $elementResetTarget = MODUL_PATH . get_class($this) . "/resetElement/" . $this->jenisTr . "/";
        $itemsElementResetTarget = MODUL_PATH . get_class($this) . "/resetItemsElement/" . $this->jenisTr . "/";

        $listItemsShoppingCart="1";
        if(!empty($itemsProdukIds)){
            foreach($itemsProdukIds as $k => $v) { $itemsIDs[] = "$k"; }
            $listItemsShoppingCart = implode(',', $itemsIDs);
        }

//        print_r($listItemsShoppingCart);

        $this->load->library("Diskon");
        $dp = new Diskon();
        $dp->setTokoId(my_toko_id());
        $src_diskon = $dp->CallProdukDiskon(explode(",",$listItemsShoppingCart));


// arrPrint($hargaJualItem);
        $produkDiskon=array();
        if(!empty($src_diskon['grosir'])){
            foreach($src_diskon['grosir'] as $k => $rp ){
                $produk_id = $rp['produk_id'];
                $produk_persen = $rp['persen'];
                $produk_harga = isset($hargaJualItem[$produk_id]) ? $hargaJualItem[$produk_id] : 0;

                if($produk_harga > 0){

                    $calcDiskon = $dp->calcDiskon($produk_harga,array($produk_persen),array());
                    // arrPrintKuning($calcDiskon);
                    // $rp["harga_jual"] = $produk_harga;
                    foreach ($calcDiskon as $kItemD => $itemD) {
                        $rp[$kItemD] = $itemD;
                    }
                }

                // cekMerah("$produk_id $produk_harga ==");

                $produkDiskon[$rp['produk_id']][] = $rp;
            }
        }

        /* ------------------------------------------------------------------------------------------------------------
         * tebus murah
         * parametes tbm masuk di session cCode supaya gampang pas implementasi saat milih produk yg masuk tebus murah
         * bagian ini belum jadi geset prioritas ke point 1/4/2023 setelah pulang dari bali
         * ------------------------------------------------------------------------------------------------------------
         * */
        $src_tebusMurah = $dp->callDiskonTebusMurah();
        // showLast_query("biru");
        // arrPrintWebs($src_tebusMurah);
        // if()
        // matiHere(__LINE__);
        $srcTebusMurah = $src_tebusMurah;

//echo json_encode($produkDiskon);

        $data = array(
            "main" => $main,
            "showScheme" => $arrCons,
            "showItems" => $showItems,
            "produkDiskon" => $produkDiskon,
            "jenisTr" => $this->jenisTr,
            "cCode" => $cCode,
            "referenceNo" => isset($_SESSION[$cCode]['main']['referenceNomer']) && $_SESSION[$cCode]['main']['referenceNomer'] != "" ? formatField_he_format("nomer", $_SESSION[$cCode]['main']['referenceNomer'])  : "",
            "headerScheme" => $headerScheme,
            "noteEnabled" => $noteEnabled,
            "noteType" => $noteType,
            "noteRecorder" => MODUL_PATH . "ValueGate/recordItemColumn/" . $this->jenisTr . "/note",
            "imageEnable" => $imageEnable,
            "imageType" => $imageType,
            "imageRecorder" => MODUL_PATH . "ValueGate/recordImage/" . $this->jenisTr . "/images",
            "pairedItemEnabled" => isset($pairedItemEnabled) ? $pairedItemEnabled : array(),
            //            "pairedItemRecorder" => MODUL_PATH . "ValueGate/recordPaireditem/" . $this->jenisTr . "/note",
            "pairedItemRecorder" => MODUL_PATH . "ValueGate/$pairedItemRecorder/" . $this->jenisTr . "/note",
            "addValues" => $addValues,
            "items" => $items,
            "free_items" => $free_items,
            "items2" => $items2,
            "items3" => $items3,
            "items3_sum" => $items3_sum,
            "itemLabels" => $itemLabels,
            "itemLabels2" => $itemLabels2,
            "itemLabels3" => $itemLabels3,
            "numLabels" => $itemNumLabels,
            "detilSizeBar" => $detilSizeBar,
            //            "itemLabels"=>$itemLabels,
            "sumRows" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields'][$stepNumber] : $this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNumber],
            "sumRows2" => $sumRows2,
            "sumRows3" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields3'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields3'][$stepNumber] : isset($this->configLayout[$this->jenisTr]['receiptSumFields3'][$stepNumber]) ? $this->configLayout[$this->jenisTr]['receiptSumFields3'][$stepNumber] : array(),
            "sumSpec2" => $sumSpec2,
            "sumType2" => $sumType2,
            "sumRowAction" => MODUL_PATH . "ValueGate/evalFees/" . $this->jenisTr,
            "editableFields" => $editableFields,
            "editableFields2" => $editableFields2,
            //            "applets"        => $applets,
            "elements" => $elements,
            "elementConfigs" => $elementConfigs,
            "elementConfigMutasi" => isset($elementMutasi) ? $elementMutasi : array(),
            "inputs" => $inputs,
            "inputLabels" => $inputLabels,
            "grandTotal" => isset($_SESSION[$cCode]['main']['grand_total']) ? $_SESSION[$cCode]['main']['grand_total'] : 0,

            //            "appletConfig" => $appletConfigs,
            "resetLink" => MODUL_PATH . get_class($this) . "/reset/" . $this->jenisTr,
            "minValues" => $minValue,
            "addRows" => $addRows,
            "addRowLabels" => $addRowLabels,
            "addRowHiddens" => $addRowHiddens,
            "avoidRemove" => $avoidRemove,
            "tmpSaver" => $tmpSaver,
            "reqDiskon" => $reqDiskon,
            "elementResetTarget" => $elementResetTarget,
            "pairedItemField" => isset($pairedItemField) ? $pairedItemField : array(),
            "pairedValue" => isset($_SESSION[$cCode]['pairs']) ? $_SESSION[$cCode]['pairs'] : array(),
            "unionSelectors" => $unionSelectors,
            "keyUpEvents" => $keyUpEvents,
            "selectedPrices" => $selectedPrices,
            "isi_modal" => "",
            "keyupAction" => isset($this->configUi[$this->jenisTr]['keyupAction']) ? $this->configUi[$this->jenisTr]['keyupAction'] : false,
            "fixedNote" => $fixedNote,
            "fixedNoteTop" => $fixedNoteTop,
            "items2_sum_kurang" => isset($items2_sum_kurang) ? $items2_sum_kurang : array(),
            "paramsForceEditable" => $paramForceEditable,
            //---MILIK SETTLEMENT-----------------------------
            "isSettlement" => $isSettlement,
            "headerMainByTransaksi" => isset($this->configUi[$this->jenisTr]['settlementHeaderByTransaksi'][$stepNumber]) ? $this->configUi[$this->jenisTr]['settlementHeaderByTransaksi'][$stepNumber] : array(),
            // --
            "headerByTransaksi" => isset($this->configUi[$this->jenisTr]['settlementByTransaksi'][$stepNumber]) ? $this->configUi[$this->jenisTr]['settlementByTransaksi'][$stepNumber] : array(),
            "headerByMenu" => isset($this->configUi[$this->jenisTr]['settlementByMenu'][$stepNumber]) ? $this->configUi[$this->jenisTr]['settlementByMenu'][$stepNumber] : array(),
            "headerByProduk" => "",
            "headerByBahan" => isset($this->configUi[$this->jenisTr]['settlementByBahan'][$stepNumber]) ? $this->configUi[$this->jenisTr]['settlementByBahan'][$stepNumber] : array(),
            "headerByPayment" => isset($this->configUi[$this->jenisTr]['settlementByPayment'][$stepNumber]) ? $this->configUi[$this->jenisTr]['settlementByPayment'][$stepNumber] : array(),
            // ---
            "summaryByTransaksi" => isset($this->configUi[$this->jenisTr]['summaryByTransaksi'][$stepNumber]) ? $this->configUi[$this->jenisTr]['summaryByTransaksi'][$stepNumber] : array(),
            "labelByMenu" => isset($this->configUi[$this->jenisTr]['labelByMenu'][$stepNumber]) ? $this->configUi[$this->jenisTr]['labelByMenu'][$stepNumber] : array(),
            "labelByTransaksi" => isset($this->configUi[$this->jenisTr]['labelByTransaksi'][$stepNumber]) ? $this->configUi[$this->jenisTr]['labelByTransaksi'][$stepNumber] : array(),
            "labelByPayment" => isset($this->configUi[$this->jenisTr]['labelByPayment'][$stepNumber]) ? $this->configUi[$this->jenisTr]['labelByPayment'][$stepNumber] : array(),
            "labelByBahan" => isset($this->configUi[$this->jenisTr]['labelByBahan'][$stepNumber]) ? $this->configUi[$this->jenisTr]['labelByBahan'][$stepNumber] : array(),
            "labelTotal" => "",
            "settlementByTransaksi" => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
            "settlementByTransaksiProduk" => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
            "settlementByMenu" => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
            //            "settlementByProduk" => "",
            "settlementByBahan" => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
            "settlementByPayment" => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
            "settlementTotal" => array(),
            //--------------------------------------------
            "arrHeaderElement" => isset($arrHeaderElement) ? $arrHeaderElement : array(),
            // --
            "subItemLabels" => $shoppingCartFieldsSubItems,
            "items_cCode" => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
            "items2_komposisi" => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
            "itemElements" => isset($itemsElements) ? $itemsElements : array(),
            "itemElementConfigs" => isset($elementItemsAutoConfigs) ? $elementItemsAutoConfigs : array(),
            "itemElementResetTarget" => isset($itemsElementResetTarget) ? $itemsElementResetTarget : "",
            "isMobile" => $isMob,
            "optionItemField" => sizeof($shopingCartItemOptionFields) > 0 ? $shopingCartItemOptionFields : array(),
            "str_customer" => $str_customer,
            "info_member_style"                => $info_member_style,
            "customer_nama"                => isset($pihakName) ? $pihakName : "",
            "selectAll" => ($cCode=="_TR_582" ? false : true),
            "cellID" => isset($_GET['selID']) ? $_GET['selID'] : 0,
            "lockTransaksi" => $lockTransaksi,
            "onPreOrderOnly" => in_array("o_takingorder", $this->session->login['membership']),
            "tebusMurah" => $srcTebusMurah,
            "hargaJualItems" => $hargaJualItem,
        );

        //==selector for pairedItem
        if (sizeof($pairedItem) > 0) {
            if (isset($pairedItem['enabled']) && ($pairedItem['enabled'] == true)) {
                $mdlName = $pairedItem['mdlName'];
                $srcKey = isset($pairedItem['srcKey']) ? $pairedItem['srcKey'] : "";
                $srcLabel = isset($pairedItem['srcLabel']) ? $pairedItem['srcLabel'] : array();

                $this->load->model("Mdls/$mdlName");
                $pro = new $mdlName();

                if (isset($pairedItem['mdlFilter']) && (sizeof($pairedItem['mdlFilter']) > 0)) {
                    foreach ($pairedItem['mdlFilter'] as $filter) {
                        $pro->addFilter($filter);
                    }
                }

                $selItems = array();
                $tmp = $pro->lookupAll()->result();

                if (sizeof($tmp) > 0) {
                    foreach ($tmp as $row) {
                        if (sizeof($srcLabel) > 0) {
                            foreach ($srcLabel as $label) {
                                $kode = isset($row->kode) ? $row->kode : "--";
                                $folder = isset($row->folders_nama) ? $row->folders_nama : "--";
                                $keterangan = isset($row->keterangan) ? $row->keterangan : "--";
                                $barcode = isset($row->barcode) ? $row->barcode : "--";
                                $selItems[$row->$srcKey] = $row->$label;
                                $selItemsKode[$row->$srcKey] = $kode;
                                $selItemsFolder[$row->$srcKey] = $folder;
                                $selItemsKeterangan[$row->$srcKey] = $keterangan;
                                $selItemsBarcode[$row->$srcKey] = $barcode;
                            }
                        }
                    }
                }

                $data['selItems'] = $selItems;
                $data['selItemsKode'] = $selItemsKode;
                $data['selItemsFolder'] = $selItemsFolder;
                $data['selItemsKeterangan'] = $selItemsKeterangan;
                $data['selItemsBarcode'] = $selItemsBarcode;
                $data['pairedItems'] = isset($_SESSION[$cCode][$pairedItemTarget]) ? $_SESSION[$cCode][$pairedItemTarget] : array();

            }
        }

        $previewJurnalConfig = isset($this->configUi[$this->jenisTr]["previewJurnal"]) ? $this->configUi[$this->jenisTr]["previewJurnal"] : array();
        if (isset($previewJurnalConfig["enabled"]) && $previewJurnalConfig["enabled"] == true) {
            $previewJurnal = previewJurnal($this->jenisTr);
            $previewJurnal['header'] = array(//                "dtime" => "date",
                "rekening" => "account",
                "debet" => "debet",
                "kredit" => "kredit",
            );
            $data['previewJurnal'] = $previewJurnal;
        }

        $columnRecorderTarget = isset($this->configUi[$this->jenisTr]["columnRecorderTarget"]) ? $this->configUi[$this->jenisTr]["columnRecorderTarget"] : false;
        if ($columnRecorderTarget == true) {
            $data["columnRecorderTargetStatus"] = true;
            $data["columnRecorderTarget"] = MODUL_PATH . "Create/recordColumn/" . $this->jenisTr . "/";
            $data["columnRecorderTargetIsi"] = isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "";
        }

        if ($isMob) {
            if (isset($this->configUi[$this->jenisTr]['isMobile_redirect'])) {
                echo "<script>
                        top.window.location.replace('" . base_url() . "MobileDev/createForm/" . $this->jenisTr . "');
                    </script>";
                die();
                redirect(base_url() . "MobileDev/createForm/" . $this->jenisTr);
            }
        }


        //================= PRE NUMBERING =================
        //=================================================

        $tokoID = $_SESSION[$cCode]["main"]['tokoID'];
        $tokoNama = $_SESSION[$cCode]["main"]["tokoNama"];
        $_SESSION[$cCode]["main"]["machineID"] = MACHINE_ID;

        //region penomoran receipt
        $this->load->model("CustomCounter");
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $configCustomParams = $this->configValues[$this->jenisTr]["counters"];
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]["main"][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                $cContent[$cRawParams][$cRawValues] = $paramSpec["value"];

                switch ($paramSpec["id"]) {
                    case 0: //===counter type is new
                        $addData = array(
                            "toko_id" => $tokoID,
                            "toko_nama" => $tokoNama,
                        );
                        $paramKeyRaw = print_r($cParams, true);
                        $paramValuesRaw = print_r($cValues[$i], true);
//                            $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                        break;
                    default: //===counter to be updated
//                            $cn->updateCount($paramSpec["id"], $paramSpec["value"]);
                        break;
                }
            }
        }

        $appliedCounters = base64_encode(serialize($cContent));

        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $counterForNumber = array($this->configValues[$this->jenisTr]["formatNota"]);
        foreach ($counterForNumber as $i => $c0RawParams) {
            $c0Params = explode(",", $c0RawParams);
            foreach($c0Params as $k=>$cRawParams){
                $dParams = explode("|", $cRawParams);
                if(count($dParams)>1){
                    if (!in_array($cRawParams, $this->configValues[$this->jenisTr]["counters"])) {
                        die(__LINE__ . "( $cRawParams ) Used number should be registered in counters config as well");
                    }
                }
            }
        }

        $tmpNomorNota="";
        $arrNomorNota=array();
        foreach ($counterForNumber as $i => $c0RawParams) {
            $c0Params = explode(",", $c0RawParams);
            $c0Values = array();
            foreach($c0Params as $k=>$cRawParams){
                $arrRawParams = explode("|", $cRawParams);
                if(sizeof($arrRawParams)>1){
                    $cRawParamsValues = array();
                    foreach($arrRawParams as $key){
                        $cRawParamsValues[$key] = $_SESSION[$cCode]['main'][$key];
                    }
                    $cRawParamsValuesK = implode("|", array_keys($cRawParamsValues));
                    $cRawParamsValuesV = implode("|", $cRawParamsValues);
                    $arrNomorNota[] = digit_4($cContent[$cRawParamsValuesK][$cRawParamsValuesV]);
                }
                else{
                    $cRawParamsValuesK = $arrRawParams[0];
                    $cRawParamsValuesV = $_SESSION[$cCode]['main'][$arrRawParams[0]];
                    if($arrRawParams[0]=="fulldate"){
                        $arrNomorNota[] = $arrRawParams[0]."|".date("mY", strtotime($cRawParamsValuesV));
                    }
                    elseif($arrRawParams[0]=="stepCode"){
                        $arrNomorNota[] = $cRawParamsValuesV; //ini harus ori tidak boleh di masking/ diformat
                    }
                    elseif($arrRawParams[0]=="placeID"){
                        $arrNomorNota[] = digit_2($cRawParamsValuesV);
                    }
                    elseif($arrRawParams[0]=="customerID"){
                        $arrNomorNota[] = digit_4($cRawParamsValuesV);
                    }
                    elseif($arrRawParams[0]=="olehID"){
                        $arrNomorNota[] = digit_4($cRawParamsValuesV);
                    }
                    elseif($arrRawParams[0]=="supplierID"){
                        $arrNomorNota[] = digit_4($cRawParamsValuesV);
                    }
                    elseif($arrRawParams[0]=="machineID"){
                        if($cRawParamsValuesV!=""){
                            $arrNomorNota[] = substr($cRawParamsValuesV,-4);
                        }
                        else{
                            $arrNomorNota[] = substr(MACHINE_ID,-4);
                        }
                    }
                    else{
                        $arrNomorNota[] = $cRawParamsValuesV;
                    }
                }
            }
        }

        $tmpNomorNota = implode("-", $arrNomorNota);
        //endregion penomoran receipt

        if(!isset($_SESSION[$cCode]['main']['pre_numbering'])){
            $_SESSION[$cCode]['main']['pre_numbering'] = $tmpNomorNota;
        }
        else{
            if($tmpNomorNota != $_SESSION[$cCode]['main']['pre_numbering']){
                $_SESSION[$cCode]['main']['pre_numbering'] = $tmpNomorNota;
            }
        }

//        $this->recordShoppingCart($cCode);
        $this->load->view("shoppingCart", $data);

    }

    public function fetchModelDescription()
    {
        //        $jenisTr = $this->uri->segment(3);
        //        $cCode = "_TR_" . $jenisTr;
        $cCode = $this->cCode;
        $jenisTr = $this->jenisTr;
        $mdlName = $this->uri->segment(5);
        $id = $this->uri->segment(6);
        $label = unserialize(base64_decode($_GET['label']));
        $labelSrc = unserialize(base64_decode($_GET['labelSrc']));
        $descSrc = unserialize(base64_decode($_GET['desc']));

        $this->load->model("Mdls/" . $mdlName);
        $oo = new $mdlName();
        $oo->addFilter("id='$id'");
        $tmp = $oo->lookupAll()->result();
        if (sizeof($tmp) > 0) {
            //==pecahkan label
            $strLabel = "";
            if (strlen($labelSrc) > 0) {
                $exLabel = explode("+", $labelSrc);
                foreach ($exLabel as $f) {
                    $strLabel .= $tmp[0]->$f . " ";
                }
            }

            //==pecahkan desc
            $strDesc = "";
            if (strlen($descSrc) > 0) {
                $exLabel = explode("+", $descSrc);
                foreach ($exLabel as $f) {
                    $strDesc .= $tmp[0]->$f . " ";
                }
            }

        }

        if (!isset($_SESSION[$cCode]['main_applets'])) {
            $_SESSION[$cCode]['main_applets'] = array();
        }
        $_SESSION[$cCode]['main_applets'][$mdlName] = array(
            "key" => $id,
            "label" => $label,
            "labelValue" => $strLabel,
            "description" => $strDesc,
        );


        echo "<script>";
        echo "top.getData('" . MODUL_PATH . "_shoppingCart/viewCart/$jenisTr/?kAhHJASAGHSGfags=kak','shopping_cart')";
        echo "</script>";


    }

    public function fetchElement()
    {
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $elName = $this->uri->segment(5);
        $mdlName = $this->uri->segment(6);
        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
//        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again...");

        $key = $_GET['key'];


        heFetchElement_modul($jenisTr, $elName, $mdlName, $key, $this->configUiJenis);

        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor( my_ppn_factor() );
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );


        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);

        //        mati_disini("kakakaak");
        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";

    }

    public function recordFieldElement()
    {
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $elName = $this->uri->segment(5);
        $val = ($_GET['val']);
        $elementConfigs = isset($this->configUi[$jenisTr]['receiptElements']) ? $this->configUi[$jenisTr]['receiptElements'] : array();
        $relElementConfigs = isset($this->configUi[$jenisTr]['relativeElements']) ? $this->configUi[$jenisTr]['relativeElements'] : array();
        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        heRecordElement_modul($jenisTr, $elName, $val, $configUiJenis);

        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";

    }

    public function resetElement()
    {

        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $elName = $this->uri->segment(5);
        $mdlName = $this->uri->segment(6);

        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
//        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");


        $_SESSION[$cCode]['main'][$elName] = null;
        $_SESSION[$cCode]['main'][$elName . "__label"] = null;

        //==reset kloningan elemen di main dan kroni2nya
        if (sizeof($_SESSION[$cCode]['main']) > 0) {
            foreach ($_SESSION[$cCode]['main'] as $key => $val) {
                if (strpos($key, $elName . "__") !== false) {
                    $_SESSION[$cCode]['main'][$key] = null;
                    unset($_SESSION[$cCode]['main'][$key]);
                }
            }
        }


        unset($_SESSION[$cCode]['main'][$elName]);
        unset($_SESSION[$cCode]['main_elements'][$elName]);

        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor( my_ppn_factor() );
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);


        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";

    }

    public function __reset()
    {
        $this->jenisTr = $this->uri->segment(3);
        $cCode = "_TR_" . $this->jenisTr;
        if (isset($_SESSION[$cCode])) {
            $_SESSION[$cCode] = null;
            unset($_SESSION[$cCode]);
        }
        echo "<script>";
        echo "top.location.reload()";
        echo "</script>";
    }

    public function reset()
    {
        $cCode = $this->cCode;
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $mdlName = isset($lockerConfig['mdlName']) ? $lockerConfig['mdlName'] : "MdlLockerStock";
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
//        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        $cCode = $this->cCode;
        $this->load->model("Mdls/" . $mdlName);
        if (isset($_SESSION[$cCode]['items'])) {
            foreach ($_SESSION[$cCode]['items'] as $id => $item) {
                if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {

                    $this->db->trans_start();

                    $c = new $mdlName();
                    $array_hold_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "hold", $this->session->login['id'], "0", $this->session->login['gudang_id'], $this->session->login['toko_id']);
                    $where = array(
                        "id" => $array_hold_sebelumnya['id'],
                    );
                    $data_hold = array(
                        "jumlah" => 0,
                    );

                    $c->updateData($where, $data_hold);
                    cekBiru($this->db->last_query());


                    $c = new $mdlName();
                    $array_active_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "active", "0", "0", $this->session->login['gudang_id'], $this->session->login['toko_id']);
                    cekHijau($this->db->last_query());


                    $where = array(
                        "id" => $array_active_sebelumnya['id'],
                    );
                    $data_active = array(
                        "jumlah" => $array_active_sebelumnya['jumlah'] + $array_hold_sebelumnya['jumlah'],
                    );
                    $c->updateData($where, $data_active);

                    $this->db->trans_complete() or die("Gagal bro");
                }


                cekkuning('memulai reset');
                $detailResetList = array(
                    "items",
                    "items2",
                    "items2_sum",
                    "tableIn_detail",
                    "tableIn_detail2",
                    "tableIn_detail2_sum",
                    "tableIn_detail_values",
                    "tableIn_detail_values2",
                    "tableIn_detail_values2_sum",
                );
                foreach ($detailResetList as $sSName) {
                    cekkuning("resetting $sSName");
                    $_SESSION[$cCode][$sSName][$id] = null;
                    unset($_SESSION[$cCode][$sSName][$id]);
                }
            }

        }


        $detailResetList = array(
            "items",
            "items2",
            "items2_sum",
            "items3",
            "items3_sum",
            "rsltItems",
            "tableIn_detail",
            "tableIn_detail2",
            "tableIn_detail2_sum",
            "tableIn_detail_rsltItems",
            "tableIn_detail_values",
            "tableIn_detail_values2",
            "tableIn_detail_values2_sum",
            "tableIn_detail_values_rsltItems",

            "items_komposisi",
        );
        foreach ($detailResetList as $sSName) {
            $_SESSION[$cCode][$sSName] = null;
            unset($_SESSION[$cCode][$sSName]);
        }

        //reset main juga
        if (isset($_SESSION[$cCode]['main'])) {
            unset($_SESSION[$cCode]);
        }

        //reset mode juga
        if (isset($_SESSION[$cCode]['mode'])) {
            unset($_SESSION[$cCode]);
        }


        //init sesssion
        $initMaster = array(
            "olehID" => $this->session->login['id'],
            "olehName" => $this->session->login['nama'],
            "placeID" => $this->session->login['cabang_id'],
            "placeName" => $this->session->login['cabang_nama'],
            "divID" => $this->session->login['div_id'],
            "divName" => $this->session->login['div_nama'],
            "cabangID" => $this->session->login['cabang_id'],
            "cabangName" => $this->session->login['cabang_nama'],
            "gudangID" => $this->session->login['gudang_id'],
            "gudangName" => $this->session->login['gudang_nama'],
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $this->configUi[$this->jenisTr]['steps'][1]['target'],
            "jenisTrName" => $this->jenisTrName,
            "stepNumber" => $stepNum,
            "stepCode" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
            "dtime" => date("Y-m-d H:i:s"),
            "shoppingcart_order_id" => strtotime( date("Y-m-d H:i:s") ),
            "fulldate" => date("Y-m-d"),
            "sellerID" => $this->session->login['id'],
            "sellerName" => $this->session->login['nama'],
            "tokoID" => $this->session->login['toko_id'],
        );
        foreach ($initMaster as $key => $val) {
            $_SESSION[$cCode]['main'][$key] = $val;
        }

        echo "<script>";
        echo "  if(top.document.getElementById('shopping_cart')){";
        echo "  top.$('#shopping_cart').load('" . base_url() . $this->modul . "/_shoppingCart/viewCart/" . $this->jenisTr . "?selID=$id');";
        echo "  top.$('.produk_diskon_list').html('');";
        echo "  }";
        echo "</script>";

//        $result = array(
//            "status" => 1
//        );
//        echo json_encode($result);
    }

    public function recordFieldInput()
    {
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $elName = $this->uri->segment(5);
        $elementConfigs = isset($this->configUi[$jenisTr]['receiptElements']) ? $this->configUi[$jenisTr]['receiptElements'] : array();


        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");


        $val = ($_GET['val']);

        if (!isset($_SESSION[$cCode]['main_inputs'])) {
            $_SESSION[$cCode]['main_inputs'] = array();
        }
        $_SESSION[$cCode]['main_inputs'][$elName] = $val;

        //==masukkan ke gerbang utama
        $_SESSION[$cCode]["main"][$elName] = $val;
        //        $_SESSION[$cCode]["main"][$elName] = $val;

        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);


        echo "<script>";
        //        echo "top.$('#result').load('" . base_url() . "ValueGate/buildValues/" . $jenisTr . "?epreketek=yes');";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";

    }

    public function recordAddRow()
    {

        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $rowName = $this->uri->segment(5);
        $val = ($_GET['val']);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];
        $total_diskon = isset($mains['akumDisc']) ? $mains['akumDisc'] + $val : $val;

        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
//        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        //        cekOrange("seg-4:: $rowName --- $val");

        if (!isset($_SESSION[$cCode]['add_rows'])) {
            $_SESSION[$cCode]['add_rows'] = array();
        }
        $_SESSION[$cCode]['add_rows'][$rowName] = $val;
        $_SESSION[$cCode]['add_rows']['total_disc'] = $total_diskon;

        //==masukkan ke gerbang utama
        $_SESSION[$cCode]["main"][$rowName] = $val;

        /* --------------------------------
         * memasukan request diskon ke tbl untuk diorisasi atau dikirim otp
         * ---------------------------*/

        $harga_nett1 = isset($main['harga_nett1']) ? $mains['harga_nett1'] : 0;
        $add_disc_params = $configUiJenis['additionalRows']['paymentMethod']['cash']['add_disc'];
        $maxValue_params = $add_disc_params['maxValue'];
        // arrPrintWebs($maxValue_params);
        // cekMerah($maximum_disc);

        if ($rowName == 'add_disc') {
            $maximum_disc = makeValue($maxValue_params, $mains, $mains, 0);
            if ($val > $maximum_disc) {
                $maximum_disc_f = formatField_he_format("curency", $maximum_disc) . ".-";
                echo lgShowAlert("diskon yang diperbolehkan untuk transaksi ini maksimal $maximum_disc_f");
//                echo "<script>
////                          top.$('#btnProcess').prop('disabled', true);
////                          top.$('#oto_diskon').prop('disabled', true);
////                          top.$('#req_diskon').prop('disabled', true);
////                          top.$('#tmp_save').prop('disabled', true);
//                      </script>";
                die();
            }

            $_SESSION[$cCode]['main']['masuk_mana'] = "gak masuk manapun";

            if (!isset($_SESSION[$cCode]['main']['oto_diskon'])) {
                $_SESSION[$cCode]['main']['oto_diskon'] = 0;
                $_SESSION[$cCode]['main'][$rowName] = 0;
                $_SESSION[$cCode]['add_rows'][$rowName] = $val*-1;
                $_SESSION[$cCode]['add_rows']['total_disc'] = $val*-1;
//                $_SESSION[$cCode]['main']['masuk_mana'] = "#1";
            }

            if ($_SESSION[$cCode]['main']['oto_diskon'] == 1 && $_SESSION[$cCode]['main'][$rowName] == 0) {
                $_SESSION[$cCode]['main']['oto_diskon'] = 0;
                $_SESSION[$cCode]['main'][$rowName] = 0;
                $_SESSION[$cCode]['add_rows'][$rowName] = $val*-1;
                $_SESSION[$cCode]['add_rows']['total_disc'] = $val*-1;
//                $_SESSION[$cCode]['main']['masuk_mana'] = "#2";
            }

            if ($_SESSION[$cCode]['main'][$rowName]*1 == 0 && $val*1 > 0 && $_SESSION[$cCode]['main'][$rowName]*1 <> $val*1) {
                $_SESSION[$cCode]['main']['oto_diskon'] = 0;
                $_SESSION[$cCode]['main'][$rowName] = 0;
//                $_SESSION[$cCode]['add_rows'][$rowName] = $val;
//                $_SESSION[$cCode]['add_rows']['total_disc'] += $val*-1;
//                $_SESSION[$cCode]['main']['masuk_mana'] = "#3";

                echo "<script>

                    var showViewOtorisasiDiskon = function(){

                        top.swal({
                           title: 'Perlu Otorisasi Admin/SPV',
                           html: 'Menambah <r>Additional Diskon</r> harus melalui Otorisasi.<br>Masukan PIN/OTP dari SPV Anda...???<br><br><br>' +
                           \"<div class=''>\" +
                           \"<div style='' class='col-md-12 col-xs-12'>\" +
                           \"<div class='input-group'>\" +

                           \"<span class='input-group-btn'>\" +
                           \"<div class='btn btn-md btn-danger' onclick='swal.close()'> <i class='fa fa-times'></i> Batalkan \" +
                           \"</div>\" +
                           \"</span>\" +

                           \"<span class='input-group-btn'>\" +
                           \"<div class='btn btn-md btn-default' disabled>\" +
                           \"<i class='fa fa-key'></i>\" +
                           \"</div>\" +
                           \"</span>\" +

                           \"<input type='password' class='form-control text-uppercase' name='diskonPinOtp' id='diskonPinOtp' value='' placeholder='OTP / PIN ADMIN' onclick='this.select()' onkeyup=''>\" +

                           \"<span class='input-group-btn'>\" +
                           \"<div id='btn-otorisasi' class='btn btn-md btn-success' disabled>\" +
                           \"<i class='text-uppercase text-bold fa fa-save'> LANJUTKAN </i>\" +
                           \"</div>\" +
                           \"</span>\" +

                           \"</div>\" +
                           \"</div>\" +
                           \"</div>\" +

                           '',
                           type: 'warning',
                           showConfirmButton: false,
                           allowOutsideClick: false,
                           onOpen: function(){

                                console.log('onOpen swal ');
//                                console.log('onOpen swal ');
                                top.$('.modal #add_disc').val(0).trigger('mouseout')

                                top.$('#diskonPinOtp').on('keyup', top.delay_v2( function(){
                                    if( this.value.length >= 6){
                                        activeBtnNextDiskon()
                                    }
                                }, 500) )

                                $(document).off('focusin.modal');

                                var activeBtnNextDiskon = function(){
                                    top.$('#btn-otorisasi').attr('disabled', false);
                                    top.$('#btn-otorisasi').on('click', function(){
                                        var pin_otp = top.$('#diskonPinOtp').val();
                                        if( pin_otp != '' ){
                                            top.$.ajax({
                                                url: '". base_url() . $this->modul . "/_shoppingCart/add_discOtorisator/".$this->jenisTr."',
                                                method: 'post',
                                                data: {
                                                    pin_diskon: pin_otp,
                                                },
                                                success: function(a){
                                                    jsonData = JSON.parse(a);
                                                    if(jsonData.status){
                                                        top.swal('BERHASIL', jsonData.reason, 'warning');
                                                        var target_diskon = jsonData.target_diskon;
                                                        var target_key = jsonData.target_key;
                                                        if( top.$('input#'+target_key) ){
                                                            top.$('input#'+target_key).val(target_diskon).trigger('mouseout')
                                                        }
//                                                        console.log('target_qty: '+ target_diskon);
//                                                        console.log('target_key: '+ target_key);
                                                    }
                                                    else{
                                                        top.swal('Perbaiki PIN/OTP', jsonData.reason, 'warning');
                                                        setTimeout(function(){
                                                            showViewOtorisasiDiskon()
                                                        },1000)
                                                    }
                                                }
                                            })
                                        }
                                        else{
                                            top.swal('masih kosong cookk, masukan pin lok');
                                            setTimeout(function(){
                                                showViewOtorisasiDiskon()
                                            },1000)
                                        }
                                    })
                                }
                           }
                        });
                    }

                    showViewOtorisasiDiskon()

                </script>";


                $this->load->model("Mdls/MdlTmpDiskon");
                $td = new MdlTmpDiskon();
                $total_diskon = $mains['add_disc'];
                $datas = blobEncode($mainGates);
                $otp = randomNumber(6);

                $dTmpDiskons = array(
                    "datas" => $datas,
                    "jenis" => "diskon_penjualan",
                    "cabang_id" => $mains['placeID'],
                    "cabang_nama" => $mains['placeName'],
                    "oleh_id" => $mains['olehID'],
                    "oleh_nama" => $mains['olehName'],
                    "customer_id" => $mains['customerID'],
                    "customer_nama" => $mains['customerName'],
                    "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
                    "add_disc" => $val,
                    "tr_jenis" => $this->jenisTr,
                    "nilai_transaksi" => $mains['grand_total'],
                    "gate" => "main",
                    "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),
                    "otp" => $otp,
                );

                /* ----------------------
                 * membaca tmpDiskon
                 * ------------------------------*/
                $condites = array(
                    "cabang_id" => $mains['placeID'],
                    "oleh_id" => $mains['olehID'],
                    "customer_id" => $mains['customerID'],
                    "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
                );

                $cekData = $td->lookupByCondition($condites)->num_rows();

                if ($cekData > 0) {
                    $delete = $td->deleteData($condites);
                    showLast_query("orange");
                }

                if($_SESSION[$cCode]['main']['oto_diskon']==0 && $val*1>0){
                    $td->addData($dTmpDiskons);
                }

                $_SESSION[$cCode]['main']['oto_diskon'] = 1;
                die();
            }

            $addRow_add_disc    = $_SESSION[$cCode]['add_rows'][$rowName];
            $addRow_total_disc  = $_SESSION[$cCode]['add_rows']['total_disc'];
            $oto_diskon         = $_SESSION[$cCode]['main']['oto_diskon'];
            $add_disc           = $_SESSION[$cCode]['main'][$rowName];
            $masuk_mana         = $_SESSION[$cCode]['main']['masuk_mana'];


            echo "<script>
//                      top.console.log('addRow_add_disc: '+$addRow_add_disc);
//                      top.console.log('addRow_total_disc: '+$addRow_total_disc);
//                      top.console.log('addRow_total_disc: '+$addRow_total_disc);
//                      top.console.log('add_disc: '+$add_disc);
//                      top.console.log('masuk_mana: $masuk_mana');
                      top.$('#btnProcess').prop('disabled', true);
                  </script>";

            unset($_SESSION[$cCode]['main']['oto_diskon']);
        }

        if ($rowName == 'voucher') {

            $this->load->model("Mdls/MdlPaymentUangMuka");
            $vc = new MdlPaymentUangMuka();

            $condites = array(
                "nomer" => $val,
            );

            $cekData = $vc->lookupByCondition($condites);

            if($cekData->num_rows()){

                cekhere( $cekData->result() );

            }

//            matiHere($cekData);
        }

        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor( my_ppn_factor() );
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";
    }

    public function add_discOtorisator()
    {
        $cCode = "_TR_582";
        $sessionMains = $_SESSION[$cCode]['main'];
        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();

        $pin = $_POST['pin_diskon'];
        $id_oto = $_POST['oto_settlement_id'];

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();

        $td->addFilter("cabang_id=" . my_cabang_id());
        $td->addFilter("oleh_id=" . my_id());
        $td->addFilter("jenis='diskon_penjualan'");
        $td->addFilter("shoppingcart_order_id=".$sessionMains['shoppingcart_order_id']);
        $tmpDisc = $td->lookupAll();

        $cekData = $tmpDisc->result();
//        $cekData = $td->lookupReqDiskonMainFilter($sessionMains)->result();
        $dbData = blobDecode($cekData[0]->datas);

        $master_diskon = "123456___";
        $emp->setFilters(array());
        $tmpUser = $emp->lookupByCondition(array(
            "id" => $id_oto,
            "oto_settlement" => 1,
            "password" => md5($pin),
            "status" => "1",
        ))->result();
        $lastQuery = $this->db->last_query();

        $pin_diskon = $cekData[0]->otp;
        $dbId = $cekData[0]->id;

        $shoppingcart_order_id = $cekData[0]->shoppingcart_order_id;
        $add_disc = $cekData[0]->add_disc;
        $tr_jenis = $cekData[0]->tr_jenis;

        if (($pin == $pin_diskon) || ($pin == $master_diskon) || count($tmpUser)*1>0 ) {
            $this->db->trans_begin();
            $pin_or_otp = $pin == $pin_diskon ? "(OTP $pin)" : (count($tmpUser)*1>0 ? "PIN SUPERVISOR" : "(MASTER_PASSWORD)");

            //region logger
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title"         => "add diskon",
                "sub_title"     => "$pin_or_otp - Otorisasi Add Diskon senilai $add_disc",
                "uid"           => $this->session->login['id'],
                "uname"         => $this->session->login['nama'],
                "dtime"         => date("Y-m-d H:i:s"),
                "transaksi_id"  => $shoppingcart_order_id,
                "deskripsi_old" => "",
                "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
                "jenis"         => $tr_jenis,
                "ipadd"         => $_SERVER['REMOTE_ADDR'],
                "devices"       => $_SERVER['HTTP_USER_AGENT'],
                "category"      => "otorisasi_diskon",
                "controller"    => $this->uri->segment(1),
                "method"        => $this->uri->segment(2),
                "url"           => current_url(),
            );
            $logID = $hTmp->addData($tmpHData, $hTmp->getTableName());
            //endregion logger

            //region delete data request
            $condites = array(
                'id' => $dbId
            );
            $td->deleteData($condites);
            //endregion delete data request

            if( $this->db->trans_complete() ){
                $result = array(
                    'status' => 1,
                    'logID' => $logID,
                    'reason' => "Otorisasi Additional Diskon berhasil",
                    'target_diskon' => $add_disc,
                    'target_key' => "add_disc",
                );

                $_SESSION[$cCode]['main']['oto_diskon'] = 1;
            }
            else{
                $result = array(
                    'status' => 0,
                    'reason' => "gagal commit nih",
                );
            }
        }
        else {
            $result = array(
                'status' => 0,
                'reason' => "periksa kembali PIN/OTP yang Anda masukan",
                'lastQuery' => $lastQuery,
            );
        }

        echo json_encode($result);

    }

    public function requestOtoDiskon()
    {
        $cCode = "_TR_582";
        $_SESSION[$cCode]['main']['oto_diskon'] = 0;
        // matiHere();
        topReload(100);
    }

    public function restoreCart()
    {
        $dbId = $this->uri->segment(5);
        $jenis = $this->uri->segment(4);
        $cCode = "_TR_" . $jenis;
        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();
        $td->addFilter("id=" . $dbId);
        $td->addFilter("status=1");
        $tmps = $td->lookupAll()->result();

        $allowCrossLogin = 0;

        if(!empty($tmps)){

            $person = $this->session->login['id'];
            $olID = $tmps[0]->oleh_id;
            $isPreorder = $tmps[0]->preorder;

            if($allowCrossLogin){
                //lanjut
            }
            else{
                if($isPreorder){
                    //lanjut
                }
                else{
                    if($person!=$olID){
//                        echo "<script>top.swal('ANDA HANYA BOLEH MELANJUTKAN DARI PREORDER ATAU MILIK ANDA SENDIRI.')</script>";
                        $result = array(
                            "status" => 0,
                            "reason" => 'ANDA HANYA BOLEH MELANJUTKAN DARI PREORDER ATAU MILIK ANDA SENDIRI.'
                        );
                        echo json_encode($result);
                        die();
                    }
                }
            }

            $params = blobDecode($tmps[0]->datas);
            $mains = $_SESSION[$cCode]['main'];
            $_SESSION[$cCode] = $params;
            $_SESSION[$cCode]['main']['olehID'] = $this->session->login['id'];
            $_SESSION[$cCode]['main']['olehName'] = $this->session->login['nama'];
            $_SESSION[$cCode]['main']['oto_diskon'] = 0;
            if($tmps[0]->preorder || $params['main']['olehID'] != $this->session->login['id']){
                $_SESSION[$cCode]['main']['preorder_id']    = $tmps[0]->oleh_id;
                $_SESSION[$cCode]['main']['preorder_nama']  = $tmps[0]->oleh_nama;
                $_SESSION[$cCode]['main']['preorder']       = $tmps[0]->preorder;
            }
            $langsungDelete = 0;
            if($langsungDelete){
                $condites = array(
                    'id' => $dbId
                );
                $td->deleteData($condites);
            }
            else{
                $where = array(
                    'id' => $dbId
                );
                $data_hold = array(
                    'status'    => 0,
                    "used_nama" => $mains['olehName'],
                    "used_id"   => $mains['olehID'],
                    "used_time" => date("Y-m-d H:i:s"),
                );
                $td->updateData($where, $data_hold);
            }
            $result = array(
                "status" => 1,
                "pihakName"=>$params["main"]['pihakName'],
                "reason" => 'ADA DATANYA LOAD KE SESSION'
            );
            echo json_encode($result);
        }
        else{
            $result = array(
                "status" => 0,
                "reason" => 'TRANSAKSI MUNGKIN SUDAH DIGUNAKAN ATAU TIDAK ADA.'
            );
            echo json_encode($result);
        }

    }

    public function restoreCartPreOrder()
    {

        $dbId = $this->uri->segment(5);
        $jenis = $this->uri->segment(4);
        $cCode = "_TR_" . $jenis;
        $post = array(
            "login" => base64_encode(json_encode($this->session->login)),
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, ADM_DOMAIN . "/eusvc/NonRest/restoreCartPreOrder/$jenis/" . $dbId);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $result_curl = curl_exec($ch);
        curl_close ($ch);

        $outPut = json_decode($result_curl);

        if( !empty($outPut) && $outPut->status==1 ){
            $params = blobDecode($outPut->tmps->datas);

            $_SESSION[$cCode]['main']['oto_diskon'] = 0;
            $_SESSION[$cCode]['main']['preorder_id']    = $params['main']['oleh_id'];
            $_SESSION[$cCode]['main']['preorder_nama']  = $params['main']['oleh_nama'];
            $_SESSION[$cCode]['main']['preorder']       = $outPut->tmps->preorder;

            $arrCust = array();
            if( $params['main']['pihakID'] != 1 ){
                $arrCust[] = array(
                    "id" => $params['main']['pihakID'],
                    "nama" => $params['main']['pihakName'],
                );
            }

            $arrProduk = array();
            foreach($params['items'] as $id => $pData){
                $arrProduk[] = array(
                    "id" => $pData[id]*1,
                    "jml" => $pData[qty_unit],
                );
            }

            $result = array(
                "status" => 1,
                "reason" => $outPut->reason,
                "produk" => $arrProduk,
                "customer" => $arrCust,
                "login" => $this->session->login,
                "login_atas" => $outPut->login,
            );
        }
        else{
            $result = array(
                "status" => 88,
                "reason" => "Pastikan Komputer terkoneksi dengan jaringan INTERNET.",
            );
        }

        echo json_encode($result);

    }
    public function tmpSave()
    {
        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();
//        arrPrintWebs($tmpSaver);
        $mdlName = $tmpSaver['mdlName'];

        // $jenisTr = $this->uri->segment(3);
        // $cCode = "_TR_" . $jenisTr;
        $rowName = $this->uri->segment(5);
        // $val = ($_GET['val']);
        $mains = $_SESSION[$cCode]['main'];
        $jml_items = isset($_SESSION[$cCode]['items']) ? count($_SESSION[$cCode]['items']) : 0;
        $mainGates = $_SESSION[$cCode];
        /* --------------------------------
 * memasukan request diskon ke tbl untuk diorisasi atau dikirim otp
 * ---------------------------*/ // arrPrintPink($_SESSION[$cCode]);
        // matiHere(__LINE__);
        // if (sizeof($extTools) > 0) {
        //     if ($rowName == $extTools['field_id']) {
        // arrPrint($extTools);
        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        //region validasi nama konsumen
        if ($mains['customerID'] == 0) {
            $alerts = array("html" => "data konsumen harap dilengkapi dulu");
            echo swalAlert($alerts);
            die();
        }
        //endregion

        if (!isset($_SESSION[$cCode]['main']['oto_diskon'])) {
            $_SESSION[$cCode]['main']['oto_diskon'] = 0;
        }
        if ($mains['oto_diskon'] == 1 && $mains['add_disc'] == 0) {
            $_SESSION[$cCode]['main']['oto_diskon'] = 0;
        }

        $total_diskon = $mains['disc'] + $mains['add_disc'];
        $datas = blobEncode($mainGates);
        $otp = randomNumber(6);
        $dTmpDiskons = array(
            "datas" => $datas,
            "jenis" => "save_penjualan",
            "cabang_id" => $mains['placeID'],
            "cabang_nama" => $mains['placeName'],
            "toko_id" => $mains['tokoID'],
            "oleh_nama" => $mains['olehName'],
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "customer_nama" => $mains['customerName'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
            "nilai_transaksi" => $mains['grand_total'],
            "jml_items" => $jml_items,
            "otp" => $otp,
            "status" => 1,
            "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),
            "preorder" => (in_array("o_takingorder", $this->session->login['membership']) ? 1 : 0),
        );


        //jika yang simpan preorder, buatkan transaksi preordernya
        if( in_array("o_takingorder", $this->session->login['membership']) ){


        }

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => $mains['placeID'],
            "jenis" => 'save_penjualan',
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );
        $cekData = $td->lookupByCondition($condites)->num_rows();

        if ($cekData > 0) {
            $delete = $td->deleteData($condites);
            showLast_query("orange");
        }

        $this->db->trans_begin();
        $td->addData($dTmpDiskons);
        showLast_query("lime");

        $this->db->trans_complete();

        //clear shoppingcart
        $this->reset();

        topReload(100);
        /* ----------------------------------------
         * ON-OFF OTORISASI DISKON
         * disable dan pop up button otorisasi merefresh main body di cont/Transaksi/createForm
         * ------------------------------------------*/

    }

    //handle otorisasi TOTAL JUAL < TOTAL HPP
    public function reqJualLowerHppSave()
    {

        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $blob_datas = $this->input->post('blob_datas');
        $cCode = $this->input->post('cCode_set');
        $gate_set = $this->input->post('gate_set');
        $id_set = $this->input->post('id_set');
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $jenisTr = $this->input->post('jenisTr');

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();

        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        //region validasi nama konsumen
        if ($mains['customerID'] == 0) {
            $alerts = array("html" => "data konsumen harap dilengkapi dulu");
            echo swalAlert($alerts);
            die();
        }
        //endregion

        $otp = randomNumber(6);

        $dTmpDiskons = array(
            "datas" => $blob_datas,
            "jenis" => "jual_lower_hpp",
            "cabang_id" => my_cabang_id(),
            "cabang_nama" => my_cabang_nama(),
            "oleh_id" => my_id(),
            "oleh_nama" => my_name(),
            "customer_id" => $mains['customerID'],
            "customer_nama" => $mains['customerName'],

            "shoppingcart_order_id" => $shoppingcart_order_id,

            "toko_id" => my_toko_id(),
            "produk_id" => $produk_id,
            "gate" => $gate_set,
            "tr_jenis" => $jenisTr,
            "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),
            "otp" => $otp,
        );

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => my_cabang_id(),
            "oleh_id" => my_id(),
            "jenis" => 'jual_lower_hpp',
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );

        $cekData = $td->lookupByCondition($condites)->num_rows();
        $dataQuery = $this->db->last_query();

        if ($cekData > 0) {
            $result = array(
                'status' => 1,
                'row' => count($cekData),
            );
        }
        else{
            $this->db->trans_begin();
            $td->addData($dTmpDiskons);
            if($this->db->trans_complete()){
                //set oto ke items id
                $result = array(
                    'status' => 1,
                    'row' => count($cekData),
                );
            }
            else{
                $result = array(
                    'status' => 0,
                    'row' => count($cekData),
                );
            }
        }

        echo json_encode($result);
    }
    public function jualLowerHppOtorisator()
    {
        $cCode = "_TR_582";
        $sessionMains = $_SESSION[$cCode]['main'];
        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();
//        $cekData = $td->lookupReqDiskonMainFilter($sessionMains)->result();
        $pin = $_POST['pin_diskon'];
        $td->addFilter("cabang_id=" . my_cabang_id());
        $td->addFilter("oleh_id=" . my_id());
        $td->addFilter("jenis='jual_lower_hpp'");
        $td->addFilter("shoppingcart_order_id=".$sessionMains['shoppingcart_order_id']);
        $tmpDisc = $td->lookupAll();
        $cekData = $tmpDisc->result();

        $dbData = blobDecode($cekData[0]->datas);

        $master_diskon = "123456__";

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();

        $emp->setFilters(array());
        $tmpUser = $emp->lookupByCondition(array(
            "oto_settlement" => 1,
            "password" => md5($pin),
            "status" => "1",
        ))->result();

        $lastQuery = $this->db->last_query();

        $pin_diskon = $cekData[0]->otp;
        $dbId = $cekData[0]->id;

        $shoppingcart_order_id  = $cekData[0]->shoppingcart_order_id;
        $tr_jenis               = $cekData[0]->tr_jenis;
        $tr_gate                = $cekData[0]->gate;

        if (($pin == $pin_diskon) || ($pin == $master_diskon) || count($tmpUser)*1>0) {
            $this->db->trans_begin();
            $pin_or_otp = $pin == $pin_diskon ? "(OTP $pin)" : (count($tmpUser)*1>0 ? "PIN SUPERVISOR" : "(MASTER_PASSWORD)") ;

            //region logger
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title"         => "jual_lower_hpp",
                "sub_title"     => "$pin_or_otp - Otorisasi Payment JUAL < HPP ",
                "uid"           => $this->session->login['id'],
                "uname"         => $this->session->login['nama'],
                "dtime"         => date("Y-m-d H:i:s"),
                "transaksi_id"  => $shoppingcart_order_id,
                "deskripsi_old" => "",
                "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
                "jenis"         => $tr_jenis,
                "ipadd"         => $_SERVER['REMOTE_ADDR'],
                "devices"       => $_SERVER['HTTP_USER_AGENT'],
                "category"      => "otorisasi_jual_lower_hpp",
                "controller"    => $this->uri->segment(1),
                "method"        => $this->uri->segment(2),
                "url"           => current_url(),
            );
            $logID = $hTmp->addData($tmpHData, $hTmp->getTableName());
            //endregion logger

            //region delete data request
            $condites = array(
                'id' => $dbId
            );
            $td->deleteData($condites);
            //endregion delete data request

            if( $this->db->trans_complete() ){
                $_SESSION[$cCode][$tr_gate]['allow_jual_lower_hpp'] = 1;
                $_SESSION[$cCode][$tr_gate]['allow_jual_lower_hpp_customerID'] = $dbData['customerID'];
                $_SESSION[$cCode][$tr_gate]['allow_jual_lower_hpp_tagihan'] = $dbData['tagihan'];
                $_SESSION[$cCode][$tr_gate]['allow_jual_lower_hpp_oto_id'] = $tmpUser[0]->id;
                $_SESSION[$cCode][$tr_gate]['allow_jual_lower_hpp_oto_nama'] = $tmpUser[0]->nama;
                $result = array(
                    'status' => 1,
                    'logID' => $logID,
                    'reason' => "Otorisasi Payment JUAL < HPP berhasil",
                );
            }
            else{
                $result = array(
                    'status' => 0,
                    'reason' => "gagal commit nih",
                );
            }
        }
        else {
            $result = array(
                'status' => 0,
                'reason' => "periksa kembali PIN/OTP yang Anda masukan",
                'lastQuery' => $lastQuery,
            );
        }
        echo json_encode($result);

    }
    public function checkOtoJualLowerHpp()
    {
        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $oto_qty_unit_set = $this->input->post('oto_qty_unit_set');
        $qty_unit_before_set = $this->input->post('qty_unit_before_set');
        $qty_unit_target_set = $this->input->post('qty_unit_target_set');
        $cCode = $this->input->post('cCode_set');
        $gate_set = $this->input->post('gate_set');
        $id_set = $this->input->post('id_set');
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $jenisTr = $this->input->post('jenisTr');

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();
        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => $mains['placeID'],
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );

        $qd = $td->lookupByCondition($condites);
        $cekData = $qd->num_rows();
        $arrData = $qd->result();
        $dataQuery = $this->db->last_query();

        if(empty($cekData)){
            $result = array(
                'status' => 0,
                'reason' => 'data tak ade, remove yang di session',
                'dataQuery' => $dataQuery,
            );
            unset($_SESSION[$cCode]['items'][$id_set]['oto_qty_unit']);
            unset($_SESSION[$cCode]['items'][$id_set]['qty_unit_before']);
            unset($_SESSION[$cCode]['items'][$id_set]['qty_unit_target']);
        }
        else{
            $id_otorisator = $arrData[0]->otorisator_id *1 > 0 ? 1 : 0;
            if($id_otorisator){
                $nama_otorisator = $arrData[0]->otorisator_nama;
                $_SESSION[$cCode]['items'][$id_set]['qty_unit'] = $_SESSION[$cCode]['items'][$id_set]['qty_unit_target'];
                $result = array(
                    'status' => 1,
                    'reason' => 'sudah diapprove oleh ' . $nama_otorisator,
                    'qty_unit' => $_SESSION[$cCode]['items'][$id_set]['qty_unit'],
                );
            }
            else{
                $result = array(
                    'status' => 1,
                    'reason' => 'belum diapprove',
                );
            }
        }

        echo json_encode($result);

    }
    //handle otorisasi TOTAL JUAL < TOTAL HPP

    //handle otorisasi HPP > Harga
    public function reqHppSave()
    {

        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $produk_id = $this->input->post('produk_id');
        $produk_nama = $this->input->post('produk_nama');
        $produk_harga = $this->input->post('produk_harga');
        $produk_hpp = $this->input->post('produk_hpp');
        $jml_items = $this->input->post('jml_items');

        $blob_datas = $this->input->post('blob_datas');
        $produk_rl = $this->input->post('produk_rl');
        $cCode = $this->input->post('cCode_set');
        $gate_set = $this->input->post('gate_set');
        $id_set = $this->input->post('id_set');
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $jenisTr = $this->input->post('jenisTr');

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();

        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        //region validasi nama konsumen
        if ($mains['customerID'] == 0) {
            $alerts = array("html" => "data konsumen harap dilengkapi dulu");
            echo swalAlert($alerts);
            die();
        }
        //endregion

        $otp = randomNumber(6);

        $dTmpDiskons = array(
            "datas" => $blob_datas,
            "jenis" => "harga_lower_hpp",
            "cabang_id" => my_cabang_id(),
            "cabang_nama" => my_cabang_nama(),
            "oleh_id" => my_id(),
            "oleh_nama" => my_name(),
            "customer_id" => $mains['customerID'],
            "customer_nama" => $mains['customerName'],

            "produk_nama" => $produk_nama,
            "produk_harga" => $produk_harga,
            "produk_hpp" => $produk_hpp,
            "produk_rl" => $produk_rl,
            "produk_rl" => $produk_rl,
            "jml_items" => $jml_items,
            "shoppingcart_order_id" => $shoppingcart_order_id,

            "toko_id" => my_toko_id(),
            "produk_id" => $produk_id,
            "gate" => $gate_set,
            "tr_jenis" => $jenisTr,
            "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),
            "otp" => $otp,
        );

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => my_cabang_id(),
            "oleh_id" => my_id(),
            "jenis" => 'harga_lower_hpp',
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );

        $cekData = $td->lookupByCondition($condites)->num_rows();
        $dataQuery = $this->db->last_query();

        if ($cekData > 0) {
            $result = array(
                'status' => 1,
                'row' => count($cekData),
            );
        }
        else{
            $this->db->trans_begin();
            $td->addData($dTmpDiskons);
            if($this->db->trans_complete()){
                //set oto ke items id
                $result = array(
                    'status' => 1,
                    'row' => count($cekData),
                );
            }
            else{
                $result = array(
                    'status' => 0,
                    'row' => count($cekData),
                );
            }
        }

        echo json_encode($result);
    }
    public function hppOtorisator()
    {
        $cCode = "_TR_582";
        $sessionMains = $_SESSION[$cCode]['main'];
        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();
//        $cekData = $td->lookupReqDiskonMainFilter($sessionMains)->result();
        $pin = $_POST['pin_diskon'];
        $td->addFilter("cabang_id=" . my_cabang_id());
        $td->addFilter("oleh_id=" . my_id());
        $td->addFilter("jenis='harga_lower_hpp'");
        $td->addFilter("shoppingcart_order_id=".$sessionMains['shoppingcart_order_id']);
        $tmpDisc = $td->lookupAll();
        $cekData = $tmpDisc->result();

        $dbData = blobDecode($cekData[0]->datas);

        $master_diskon = "123456__";

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();

        $emp->setFilters(array());
        $tmpUser = $emp->lookupByCondition(array(
            "oto_settlement" => 1,
            "password" => md5($pin),
            "status" => "1",
        ))->result();

        $lastQuery = $this->db->last_query();

        $pin_diskon = $cekData[0]->otp;
        $dbId = $cekData[0]->id;

        $shoppingcart_order_id  = $cekData[0]->shoppingcart_order_id;
        $tr_jenis               = $cekData[0]->tr_jenis;
        $tr_gate                = $cekData[0]->gate;
        $produk_id              = $cekData[0]->produk_id;

        if (($pin == $pin_diskon) || ($pin == $master_diskon) || count($tmpUser)*1>0) {
            $this->db->trans_begin();
            $pin_or_otp = $pin == $pin_diskon ? "(OTP $pin)" : (count($tmpUser)*1>0 ? "PIN SUPERVISOR" : "(MASTER_PASSWORD)") ;

            //region logger
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title"         => "harga_lower_hpp",
                "sub_title"     => "$pin_or_otp - Otorisasi HRG < HPP ",
                "uid"           => $this->session->login['id'],
                "uname"         => $this->session->login['nama'],
                "dtime"         => date("Y-m-d H:i:s"),
                "transaksi_id"  => $shoppingcart_order_id,
                "deskripsi_old" => "",
                "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
                "jenis"         => $tr_jenis,
                "ipadd"         => $_SERVER['REMOTE_ADDR'],
                "devices"       => $_SERVER['HTTP_USER_AGENT'],
                "category"      => "otorisasi_hpp",
                "controller"    => $this->uri->segment(1),
                "method"        => $this->uri->segment(2),
                "url"           => current_url(),
            );
            $logID = $hTmp->addData($tmpHData, $hTmp->getTableName());
            //endregion logger

            //region delete data request
            $condites = array(
                'id' => $dbId
            );
            $td->deleteData($condites);
            //endregion delete data request

            if( $this->db->trans_complete() ){
                if(is_array($dbData)){
                    foreach($dbData as $kk => $kVal ){
                        $_SESSION[$cCode][$tr_gate][$produk_id][$kk] = $kVal;
                    }
                }
                $_SESSION[$cCode][$tr_gate][$produk_id]['allowHpp'] = 1;
                $_SESSION[$cCode][$tr_gate][$produk_id]['allowHppQty'] = $_SESSION[$cCode][$tr_gate][$produk_id]['qty_unit'];
                $_SESSION[$cCode][$tr_gate][$produk_id]['allowHppUom'] = $_SESSION[$cCode][$tr_gate][$produk_id]['satuan_factor_nama'];
                $_SESSION[$cCode][$tr_gate][$produk_id]['allowHpp_oto_id'] = $tmpUser[0]->id;
                $_SESSION[$cCode][$tr_gate][$produk_id]['allowHpp_oto_nama'] = $tmpUser[0]->nama;
                $result = array(
                    'status' => 1,
                    'logID' => $logID,
                    'reason' => "Otorisasi Harga < HPP berhasil",
                    'target_pid' => "$produk_id",
                    'target_url' => $_SESSION[$cCode][$tr_gate][$produk_id]['actual_link'],
                );
            }
            else{
                $result = array(
                    'status' => 0,
                    'reason' => "gagal commit nih",
                );
            }
        }
        else {
            $result = array(
                'status' => 0,
                'reason' => "periksa kembali PIN/OTP yang Anda masukan",
                'lastQuery' => $lastQuery,
            );
        }
        echo json_encode($result);

    }
    public function checkOtoHpp()
    {
        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $oto_qty_unit_set = $this->input->post('oto_qty_unit_set');
        $qty_unit_before_set = $this->input->post('qty_unit_before_set');
        $qty_unit_target_set = $this->input->post('qty_unit_target_set');
        $cCode = $this->input->post('cCode_set');
        $gate_set = $this->input->post('gate_set');
        $id_set = $this->input->post('id_set');
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $jenisTr = $this->input->post('jenisTr');

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();
        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => $mains['placeID'],
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );

        $qd = $td->lookupByCondition($condites);
        $cekData = $qd->num_rows();
        $arrData = $qd->result();
        $dataQuery = $this->db->last_query();

        if(empty($cekData)){
            $result = array(
                'status' => 0,
                'reason' => 'data tak ade, remove yang di session',
                'dataQuery' => $dataQuery,
            );
            unset($_SESSION[$cCode]['items'][$id_set]['oto_qty_unit']);
            unset($_SESSION[$cCode]['items'][$id_set]['qty_unit_before']);
            unset($_SESSION[$cCode]['items'][$id_set]['qty_unit_target']);
        }
        else{
            $id_otorisator = $arrData[0]->otorisator_id *1 > 0 ? 1 : 0;
            if($id_otorisator){
                $nama_otorisator = $arrData[0]->otorisator_nama;
                $_SESSION[$cCode]['items'][$id_set]['qty_unit'] = $_SESSION[$cCode]['items'][$id_set]['qty_unit_target'];
                $result = array(
                    'status' => 1,
                    'reason' => 'sudah diapprove oleh ' . $nama_otorisator,
                    'qty_unit' => $_SESSION[$cCode]['items'][$id_set]['qty_unit'],
                );
            }
            else{
                $result = array(
                    'status' => 1,
                    'reason' => 'belum diapprove',
                );
            }
        }

        echo json_encode($result);

    }
    //handle otorisasi HPP > Harga

    //handle otorisasi perubahan QTY
    public function reqQtySave()
    {

        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $oto_qty_unit_set = $this->input->post('oto_qty_unit_set');
        $qty_unit_before_set = $this->input->post('qty_unit_before_set');
        $qty_unit_target_set = $this->input->post('qty_unit_target_set');
        $cCode = $this->input->post('cCode_set');
        $gate_set = $this->input->post('gate_set');
        $id_set = $this->input->post('id_set');
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $jenisTr = $this->input->post('jenisTr');

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();

        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        //region validasi nama konsumen
        if ($mains['customerID'] == 0) {
            $alerts = array("html" => "data konsumen harap dilengkapi dulu");
            echo swalAlert($alerts);
            die();
        }
        //endregion

        $datas = blobEncode($mainGates);
        $otp = randomNumber(6);

        $dTmpDiskons = array("datas" => $datas,
            "jenis" => "qty_change",
            "cabang_id" => $mains['placeID'],
            "cabang_nama" => $mains['placeName'],
            "oleh_id" => $mains['olehID'],
            "oleh_nama" => $mains['olehName'],
            "customer_id" => $mains['customerID'],
            "customer_nama" => $mains['customerName'],
            "nilai_transaksi" => $mains['grand_total'],

            "oto_qty_unit_set" => $oto_qty_unit_set,
            "qty_unit_before_set" => $qty_unit_before_set,
            "qty_unit_target_set" => $qty_unit_target_set,
            "shoppingcart_order_id" => $shoppingcart_order_id,
            "produk_id" => $id_set,
            "gate" => $gate_set,
            "tr_jenis" => $jenisTr,

            "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),

            "otp" => $otp,
        );

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => $mains['placeID'],
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );

        $cekData = $td->lookupByCondition($condites)->num_rows();
        $dataQuery = $this->db->last_query();

        if ($cekData > 0) {
            $result = array(
                'status' => 1,
                'row' => count($cekData),
            );
        }
        else{

            $this->db->trans_begin();
            $td->addData($dTmpDiskons);

            if($this->db->trans_complete()){
                //set oto ke items id
                $result = array(
                    'status' => 1,
                    'row' => count($cekData),
                );
            }
            else{
                $result = array(
                    'status' => 0,
                    'row' => count($cekData),
                );
            }
        }



        echo json_encode($result);
    }
    public function qtyOtorisator()
    {
        $cCode = "_TR_582";
        $sessionMains = $_SESSION[$cCode]['main'];
        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();
//        $cekData = $td->lookupReqDiskonMainFilter($sessionMains)->result();
        $pin = $_POST['pin_diskon'];
        $td->addFilter("cabang_id=" . my_cabang_id());
        $td->addFilter("oleh_id=" . my_id());
        $td->addFilter("jenis='qty_change'");
        $td->addFilter("shoppingcart_order_id=".$sessionMains['shoppingcart_order_id']);
        $tmpDisc = $td->lookupAll();
        $cekData = $tmpDisc->result();

        $dbData = blobDecode($cekData[0]->datas);

        $master_diskon = "123456__";

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();

        $emp->setFilters(array());
        $tmpUser = $emp->lookupByCondition(array(
            "oto_settlement" => 1,
            "password" => md5($pin),
            "status" => "1",
        ))->result();

        $lastQuery = $this->db->last_query();

        $pin_diskon = $cekData[0]->otp;
        $dbId = $cekData[0]->id;

        $qty_unit_before_set = $cekData[0]->qty_unit_before_set;
        $qty_unit_target_set = $cekData[0]->qty_unit_target_set;
        $shoppingcart_order_id = $cekData[0]->shoppingcart_order_id;
        $tr_jenis = $cekData[0]->tr_jenis;
        $tr_gate = $cekData[0]->gate;
        $produk_id = $cekData[0]->produk_id;


        if (($pin == $pin_diskon) || ($pin == $master_diskon) || count($tmpUser)*1>0) {
            $this->db->trans_begin();
            $pin_or_otp = $pin == $pin_diskon ? "(OTP $pin)" : (count($tmpUser)*1>0 ? "PIN SUPERVISOR" : "(MASTER_PASSWORD)") ;

            //region logger
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title"         => "qty_change",
                "sub_title"     => "$pin_or_otp - Otorisasi Perubahan QTY dari ($qty_unit_before_set) MENJADI => ($qty_unit_target_set)",
                "uid"           => $this->session->login['id'],
                "uname"         => $this->session->login['nama'],
                "dtime"         => date("Y-m-d H:i:s"),
                "transaksi_id"  => $shoppingcart_order_id,
                "deskripsi_old" => "",
                "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
                "jenis"         => $tr_jenis,
                "ipadd"         => $_SERVER['REMOTE_ADDR'],
                "devices"       => $_SERVER['HTTP_USER_AGENT'],
                "category"      => "otorisasi_qty",
                "controller"    => $this->uri->segment(1),
                "method"        => $this->uri->segment(2),
                "url"           => current_url(),
            );
            $logID = $hTmp->addData($tmpHData, $hTmp->getTableName());
            //endregion logger

            //region delete data request
            $condites = array(
                'id' => $dbId
            );
            $td->deleteData($condites);
            //endregion delete data request

            if( $this->db->trans_complete() ){

                $result = array(
                    'status' => 1,
                    'logID' => $logID,
                    'reason' => "Otorisasi PERUBAHAN QTY berhasil",
                    'target_qty' => $qty_unit_target_set,
                    'target_key' => "id_jml",
                    'target_pid' => "$produk_id",
                );

                $_SESSION[$cCode][$tr_gate][$produk_id]['allowDown'] = 1;

            }
            else{
                $result = array(
                    'status' => 0,
                    'reason' => "gagal commit nih",
                );
            }
        }
        else {
            $result = array(
                'status' => 0,
                'reason' => "periksa kembali PIN/OTP yang Anda masukan",
                'lastQuery' => $lastQuery,
            );
        }

        echo json_encode($result);

    }
    public function checkOtoQty()
    {
        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $oto_qty_unit_set = $this->input->post('oto_qty_unit_set');
        $qty_unit_before_set = $this->input->post('qty_unit_before_set');
        $qty_unit_target_set = $this->input->post('qty_unit_target_set');
        $cCode = $this->input->post('cCode_set');
        $gate_set = $this->input->post('gate_set');
        $id_set = $this->input->post('id_set');
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $jenisTr = $this->input->post('jenisTr');

        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();
        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "cabang_id" => $mains['placeID'],
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $mains['shoppingcart_order_id'],
        );

        $qd = $td->lookupByCondition($condites);
        $cekData = $qd->num_rows();
        $arrData = $qd->result();
        $dataQuery = $this->db->last_query();

        if(empty($cekData)){
            $result = array(
                'status' => 0,
                'reason' => 'data tak ade, remove yang di session',
                'dataQuery' => $dataQuery,
            );
            unset($_SESSION[$cCode]['items'][$id_set]['oto_qty_unit']);
            unset($_SESSION[$cCode]['items'][$id_set]['qty_unit_before']);
            unset($_SESSION[$cCode]['items'][$id_set]['qty_unit_target']);
        }
        else{
            $id_otorisator = $arrData[0]->otorisator_id *1 > 0 ? 1 : 0;
            if($id_otorisator){
                $nama_otorisator = $arrData[0]->otorisator_nama;
                $_SESSION[$cCode]['items'][$id_set]['qty_unit'] = $_SESSION[$cCode]['items'][$id_set]['qty_unit_target'];
                $result = array(
                    'status' => 1,
                    'reason' => 'sudah diapprove oleh ' . $nama_otorisator,
                    'qty_unit' => $_SESSION[$cCode]['items'][$id_set]['qty_unit'],
                );
            }
            else{
                $result = array(
                    'status' => 1,
                    'reason' => 'belum diapprove',
                );
            }
        }

        echo json_encode($result);

    }
    //handle otorisasi perubahan QTY

    //handle otorisasi RETURN
    public function reqReturnOTP()
    {

        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $tmpSaver = isset($this->configUi[$this->jenisTr]['reqReturnOTP']) ? $this->configUi[$this->jenisTr]['reqReturnOTP'] : array();

        $mdlName = $tmpSaver['mdlName'];

        $rowName = $this->uri->segment(5);
        $mains = $_SESSION[$cCode]['main'];
        $mainGates = $_SESSION[$cCode];

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        //region validasi nama konsumen
        if ($mains['customerID'] == 0) {
            $alerts = array("html" => "data konsumen harap dilengkapi dulu");
            echo swalAlert($alerts);
            die();
        }
        //endregion

        $datas = blobEncode($mainGates);
        $otp = randomNumber(6);

        $dTmpDiskons = array("datas" => $datas,
            "jenis" => "request_return",
            "cabang_id" => $mains['placeID'],
            "cabang_nama" => $mains['placeName'],
            "oleh_id" => $mains['olehID'],
            "oleh_nama" => $mains['olehName'],
            "customer_id" => $mains['customerID'],
            "customer_nama" => $mains['customerName'],
            "shoppingcart_order_id" => $shoppingcart_order_id,
            "nilai_transaksi" => $mains['grand_total'],
            "gate" => "main",
            "tr_jenis" => $this->jenisTr,
            "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),
            "otp" => $otp,
        );

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "jenis" => "request_return",
            "cabang_id" => $mains['placeID'],
            "oleh_id" => $mains['olehID'],
            "customer_id" => $mains['customerID'],
            "shoppingcart_order_id" => $shoppingcart_order_id,
        );

        $cekData = $td->lookupByCondition($condites)->num_rows();
        $dataQuery = $this->db->last_query();

        if ($cekData > 0) {
            //tidak menghapus yang sebelumnya udh ada
            $delete = $td->deleteData($condites);
            $result = array(
                'status' => 1,
                'row' => count($cekData),
                'data' => $cekData,
                'query' => $dataQuery,
            );
        }


        $this->db->trans_begin();
        $td->addData($dTmpDiskons);
        if($this->db->trans_complete()){
            //ttt
            $result = array(
                'status' => 1,
                'row' => count($cekData),
                'data' => $cekData,
                'query' => $dataQuery,
            );
        }
        else{
            $result = array(
                'status' => 0,
                'row' => count($cekData),
                'data' => $cekData,
                'query' => $dataQuery,
            );
        }


        echo json_encode($result);
    }
    public function returnOtorisator()
    {
        $cCode = "_TR_982";
        $sessionMains = $_SESSION[$cCode]['main'];
        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();

//        $cekData = $td->lookupReqDiskonMainFilter($sessionMains)->result();
        $pin = $_POST['pin_diskon'];
        $id_oto = $_POST['oto_settlement_id'];

        $td->addFilter("cabang_id=" . my_cabang_id());
        $td->addFilter("oleh_id=" . my_id());
        $td->addFilter("jenis='request_return'");
        $td->addFilter("shoppingcart_order_id='".$sessionMains['referenceNomer']."'");
        $tmpDisc = $td->lookupAll();
        $cekData = $tmpDisc->result();

        $qResult = $this->db->last_query();

        if(empty($cekData)){
            $result = array(
                'status' => 0,
                'reason' => "data tak ditemukan nih, refresh browser dan lanjutkan kembali transaksi Anda.",
                'query' => $qResult,
            );
            echo json_encode($result);
            die();
        }
        $dbData = blobDecode($cekData[0]->datas);

        $master_diskon = "123456__";

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();

        $emp->setFilters(array());
        $tmpUser = $emp->lookupByCondition(array(
            "id" => $id_oto,
            "oto_settlement" => 1,
            "password" => md5($pin),
            "status" => "1",
        ))->result();

        $lastQuery = $this->db->last_query();

        $pin_diskon = $cekData[0]->otp;
        $dbId = $cekData[0]->id;

        $shoppingcart_order_id = $cekData[0]->shoppingcart_order_id;
        $tr_jenis = $cekData[0]->tr_jenis;
        $tr_gate = $cekData[0]->gate;
//        $produk_id = $cekData[0]->produk_id;
        $nilai_transaksi = $cekData[0]->nilai_transaksi;

        if (($pin == $pin_diskon) || ($pin == $master_diskon) || count($tmpUser)*1>0) {
            $this->db->trans_begin();
            $pin_or_otp = $pin == $pin_diskon ? "(OTP $pin)" : (count($tmpUser)*1>0 ? "PIN SUPERVISOR" : "(MASTER_PASSWORD)") ;

            //region logger
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title"         => "return_penjualan",
                "sub_title"     => "$pin_or_otp - Otorisasi Return Penjualan ",
                "uid"           => $this->session->login['id'],
                "uname"         => $this->session->login['nama'],
                "dtime"         => date("Y-m-d H:i:s"),
                "transaksi_id"  => $shoppingcart_order_id,
                "deskripsi_old" => "",
                "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
                "jenis"         => $tr_jenis,
                "ipadd"         => $_SERVER['REMOTE_ADDR'],
                "devices"       => $_SERVER['HTTP_USER_AGENT'],
                "category"      => "otorisasi_return",
                "controller"    => $this->uri->segment(1),
                "method"        => $this->uri->segment(2),
                "url"           => current_url(),
            );
            $logID = $hTmp->addData($tmpHData, $hTmp->getTableName());
            //endregion logger

            //region delete data request
            $condites = array(
                'id' => $dbId
            );
            $td->deleteData($condites);
            //endregion delete data request

            $debuger=0;

            if(!$debuger &&  $this->db->trans_complete() ){
                $result = array(
                    'status' => 1,
                    'logID' => $logID,
                    'reason' => "Otorisasi Return berhasil",
                    'nilai_transaksi' => $nilai_transaksi,
                );
                $_SESSION[$cCode][$tr_gate]['allowReturn'] = 1;
            }
            else{

                if($debuger){
                    $result = array(
                        'status' => 0,
                        'reason' => "stooop belum di commit",
                    );
                }
                else{
                    $result = array(
                        'status' => 0,
                        'reason' => "gagal commit nih",
                    );
                }

            }
        }
        else {
            $result = array(
                'status' => 0,
                'reason' => "periksa kembali PIN/OTP yang Anda masukan",
                'lastQuery' => $lastQuery,
            );
        }

        echo json_encode($result);

    }
    public function addReff()
    {
        $key = $_GET['key'];
        $val = $_GET['val'];
        //        $this->jenisTr = $this->uri->segment(3);
        //        $cCode = "_TR_" . $this->jenisTr;
        $cCode = $this->cCode;
        $jenisTr = $this->jenisTr;
        $_SESSION[$cCode]['main'][$key] = $val;
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);


        echo "<script>";
        //        echo "top.$('#result').load('" . base_url() . "ValueGate/buildValues/" . $this->jenisTr . "?epreketek=yes');";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";
    }

    //handle otorisasi SETTLEMENT
    public function reqSettlementOTP()
    {

        $jenisTr = $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;
        $shoppingcart_order_id = $this->input->post('shoppingcart_order_id');
        $tmpSaver = isset($this->configUi[$this->jenisTr]['tmpSave']) ? $this->configUi[$this->jenisTr]['tmpSave'] : array();

        $mdlName = $tmpSaver['mdlName'];
        $rowName = $this->uri->segment(5);
        $mainGates = $this->input->post('main');

        $this->load->model("Mdls/" . $mdlName);
        $td = new $mdlName();

        $datas = $mainGates;
        $otp = randomNumber(6);

        $dTmpDiskons = array(
            "datas" => $datas,
            "jenis" => "request_settlement",
            "cabang_id" => $this->session->login['cabang_id'],
            "cabang_nama" => $this->session->login['cabang_nama'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "customer_id" => '',
            "customer_nama" => '',
            "shoppingcart_order_id" => $shoppingcart_order_id,
            "nilai_transaksi" => $this->input->post('grand_total'),
            "gate" => "main",
            "tr_jenis" => $this->jenisTr,
            "expired" => strtotime("+10 minutes", strtotime(date("Y-m-d H:i:s"))),
            "otp" => $otp,
        );

        /* ----------------------
         * membaca tmpDiskon
         * ------------------------------*/
        $condites = array(
            "jenis"                 => "request_settlement",
            "cabang_id"             => $this->session->login['cabang_id'],
            "oleh_id"               => $this->session->login['id'],
            "shoppingcart_order_id" => $shoppingcart_order_id,
        );

        $cekData = $td->lookupByCondition($condites)->num_rows();
        $dataQuery = $this->db->last_query();

        if ($cekData > 0) {
            //tidak menghapus yang sebelumnya udh ada
            $delete = $td->deleteData($condites);
            $result = array(
                'status' => 1,
                'row' => count($cekData),
                'data' => $cekData,
                'query' => $dataQuery,
            );
        }

        $this->db->trans_begin();
        $td->addData($dTmpDiskons);
        if($this->db->trans_complete()){
            //ttt
            $result = array(
                'status' => 1,
                'row' => count($cekData),
                'data' => $cekData,
                'query' => $dataQuery,
            );
        }
        else{
            $result = array(
                'status' => 0,
                'row' => count($cekData),
                'data' => $cekData,
                'query' => $dataQuery,
            );
        }

        echo json_encode($result);
    }
    public function settlementOtorisator()
    {
        $cCode = "_TR_582";
        $nomer_main = $_POST['nomer_main'];
        $payment_nilai = $_POST['payment_nilai'];
        $oto_settlement_id = $_POST['oto_settlement_id'];
        $oto_settlement_nama = $_POST['oto_settlement_nama'];

        $this->load->model("Mdls/MdlTmpDiskon");
        $td = new MdlTmpDiskon();

        $td->addFilter("cabang_id=" . my_cabang_id());
        $td->addFilter("oleh_id=" . my_id());
        $td->addFilter("jenis='request_settlement'");
        $td->addFilter("shoppingcart_order_id='$nomer_main'");

        $tmpDisc = $td->lookupAll();
        $cekData = $tmpDisc->result();

        $qResult = $this->db->last_query();

        if(empty($cekData)){
            $result = array(
                'status' => 0,
                'reason' => "data tak ditemukan nih, refresh browser dan buka kembali settlement Anda.",
                'query' => $qResult,
            );
            echo json_encode($result);
            die();
        }

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();
        $emp->addFilter("oto_settlement=1");
        $emp->addFilter("id=$oto_settlement_id");
        $arrEmployee = $emp->lookUpAll()->result();

        if(empty($arrEmployee)){
            $result = array(
                'status' => 0,
                'reason' => strtoupper("<b>$oto_settlement_nama</b> tidak memiliki hak untuk menerima settlement"),
            );
            echo json_encode($result);
            die();
        }

        $dbData = blobDecode($cekData[0]->datas);

        $payment = $_POST['payment'];
        $terbilang = $_POST['terbilang'];
        $arrPayment = array();
        if(!empty($payment)){
            foreach($payment as $k => $rowp){
                $arrPayment[$rowp['payID']] = $rowp;
            }
        }
        $pin = $_POST['pin_diskon'];
        $selisihPayment = array();
        $totalSetor = 0;
        $totalSetorSeharusnya = 0;
        if(!empty($payment_nilai)){
            foreach($payment_nilai as $payid => $paynilai){
                $nilai_setor = $arrPayment[$payid]['nilai']*1;
                $pay_nama = $arrPayment[$payid]['payNama'];
                $nilai_seharusnya = $paynilai*1;
                $totalSetor += $nilai_setor;
                $totalSetorSeharusnya += $nilai_seharusnya;
                if($nilai_seharusnya-$nilai_setor <= 0){
                    //selisih plus
                    $status_selisih = ($nilai_seharusnya-$nilai_setor) == 0 ? "passed" : "plus";
                    $selisihPayment[$payid] = array(
                        "nama" => $pay_nama,
                        "nilai_setor" => $nilai_setor,
                        "nilai_seharusnya" => $nilai_seharusnya,
                        "selisih" => ($nilai_setor-$nilai_seharusnya),
                        "status_selisih" => $status_selisih,
                    );
                }
                else{
                    //selisih minus
                    $selisihPayment[$payid] = array(
                        "nama" => $pay_nama,
                        "nilai_setor" => $nilai_setor,
                        "nilai_seharusnya" => $nilai_seharusnya,
                        "selisih" => ($nilai_setor-$nilai_seharusnya),
                        "status_selisih" => "minus",
                    );
                }
            }
        }

        $dbData['payment'] =  $arrPayment;
        $dbData['payment_nilai'] =  $totalSetor;
        $dbData['payment_terbilang'] =  $terbilang;
        $dbData['payment_nilai_seharusnya'] =  $totalSetorSeharusnya;
        $dbData['payment_nilai_selisih'] =  $totalSetor-$totalSetorSeharusnya;
        $dbData['selisih_payment'] =  $selisihPayment;
        $dbData['payment_oto_id'] =  $oto_settlement_id;
        $dbData['payment_oto_nama'] =  $oto_settlement_nama;

        $master_diskon = "123456__";

        $emp->setFilters(array());
        $tmpUser = $emp->lookupByCondition(array(
            "id" => $oto_settlement_id,
            "password" => md5($pin),
            "status" => "1",
        ))->result();
        $lastQuery = $this->db->last_query();

        $pin_diskon = $cekData[0]->otp;
        $dbId = $cekData[0]->id;
        $shoppingcart_order_id = $cekData[0]->shoppingcart_order_id;
        $tr_jenis = $cekData[0]->tr_jenis;
        $tr_gate = $cekData[0]->gate;
        $nilai_transaksi = $cekData[0]->nilai_transaksi;

        if (($pin == $pin_diskon) || ($pin == $master_diskon) || count($tmpUser)*1>0) {
            $this->db->trans_begin();
            $pin_or_otp = $pin == $pin_diskon ? "(OTP $pin)" : (count($tmpUser)*1>0 ? "PIN SUPERVISOR" : "(MASTER_PASSWORD)") ;

            //region logger
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title"         => "penerimaan settlement",
                "sub_title"     => "$pin_or_otp - Otorisasi Return Penjualan ",
                "uid"           => $oto_settlement_id,
                "uname"         => $oto_settlement_nama,
                "dtime"         => date("Y-m-d H:i:s"),
                "transaksi_id"  => $shoppingcart_order_id,
                "deskripsi_old" => "",
                "deskripsi_new" => base64_encode(serialize($dbData)),
                "jenis"         => $tr_jenis,
                "ipadd"         => $_SERVER['REMOTE_ADDR'],
                "devices"       => $_SERVER['HTTP_USER_AGENT'],
                "category"      => "otorisasi_settlement",
                "controller"    => $this->uri->segment(1),
                "method"        => $this->uri->segment(2),
                "url"           => current_url(),
            );
            $logID = $hTmp->addData($tmpHData, $hTmp->getTableName());
            //endregion logger

            //region delete data request
            $condites = array(
                'id' => $dbId
            );
            $td->deleteData($condites);
            //endregion delete data request

            $debuger=0;

            if(!$debuger && $this->db->trans_complete()){
                $result = array(
                    'status' => 1,
                    'logID' => $logID,
                    'reason' => "Otorisasi Settlement berhasil",
                    'nilai_transaksi' => $nilai_transaksi,
                    'dbData' => $dbData,
                );
            }
            else{
                if($debuger){
                    $result = array(
                        'status' => 1,
                        'reason' => "stooop belum di commit",
                        'dbData' => $dbData,
                    );
                }
                else{
                    $result = array(
                        'status' => 0,
                        'reason' => "gagal commit nih",
                    );
                }
            }
        }
        else {
            $result = array(
                'status' => 0,
                'reason' => "periksa kembali PIN/OTP yang Anda masukan",
                'lastQuery' => $lastQuery,
            );
        }

        echo json_encode($result);

    }

    //-----------------------------------
    public function fetchItemsElement()
    {
        //        $jenisTr = $this->uri->segment(3);
        //        $cCode = "_TR_" . $jenisTr;
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $elName = $this->uri->segment(5);
        $mdlName = $this->uri->segment(6);
        $helpName = $this->uri->segment(7);
        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        $key = $_GET['key'];


        heFetchItemsElement_modul($jenisTr, $elName, $mdlName, $key, $helpName, $configUiJenis);
        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";

    }

    public function recordFieldItemsElement()
    {

        //        $jenisTr = $this->uri->segment(3);
        //        $cCode = "_TR_" . $jenisTr;
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $elName = $this->uri->segment(5);
        $val = ($_GET['val']);
        $elementConfigs = isset($this->configUi[$jenisTr]['receiptElements']) ? $this->configUi[$jenisTr]['receiptElements'] : array();
        $relElementConfigs = isset($this->configUi[$jenisTr]['relativeElements']) ? $this->configUi[$jenisTr]['relativeElements'] : array();
        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        heRecordElement_modul($jenisTr, $elName, $val, $configUiJenis);

        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";

    }

    public function resetItemsElement()
    {

        //        $jenisTr = $this->uri->segment(3);
        //        $cCode = "_TR_" . $jenisTr;
        $cCode = $this->cCode;
        $jenisTr = $this->jenisTr;
        $elName = $this->uri->segment(5);
        //        $mdlName = $this->uri->segment(6);
        $helpName = $this->uri->segment(7);
        $configUiJenis = $this->configUi[$this->jenisTr];
        $configCoreJenis = $this->configCore[$this->jenisTr];
        $configValuesJenis = $this->configValues[$this->jenisTr];
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        //        cekmerah("resetting element $elName on $cCode...");

        $_SESSION[$cCode]['main'][$helpName] = null;
        $_SESSION[$cCode]['main'][$helpName . "__label"] = null;

        //==reset kloningan elemen di main dan kroni2nya
        if (sizeof($_SESSION[$cCode]['main']) > 0) {
            foreach ($_SESSION[$cCode]['main'] as $key => $val) {
                if (strpos($key, $helpName . "__") !== false) {
                    $_SESSION[$cCode]['main'][$key] = null;
                    unset($_SESSION[$cCode]['main'][$key]);
                }
            }
        }

        //==reset kloningan elemen di items dan kroni2nya
        if (sizeof($_SESSION[$cCode]['items']) > 0) {
            foreach ($_SESSION[$cCode]['items'] as $ii => $spec) {
                $_SESSION[$cCode]['items'][$ii][$helpName] = null;
                unset($_SESSION[$cCode]['items'][$ii][$helpName]);

                foreach ($spec as $key => $val) {
                    if (strpos($key, $helpName . "__") !== false) {
                        $_SESSION[$cCode]['items'][$ii][$key] = null;
                        unset($_SESSION[$cCode]['items'][$ii][$key]);
                    }
                    if (strpos($key, "sub_" . $helpName . "__") !== false) {
                        $_SESSION[$cCode]['items'][$ii][$key] = null;
                        unset($_SESSION[$cCode]['items'][$ii][$key]);
                    }
                }
            }
        }

        unset($_SESSION[$cCode]['main'][$helpName]);
        unset($_SESSION[$cCode]['items_elements'][$elName]);

        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);


        echo "<script>";
        //        echo "top.$('#result').load('" . base_url() . "ValueGate/buildValues/" . $jenisTr . "?epreketek=yes&populate=1');";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";

    }

    //-----------------------------------
    public function recordItemColumn()
    {

        $cCode = $this->cCode;
        $id = $iID = $_GET['iid'];
        $colName = $this->uri->segment(5);
        $val = rawurldecode($_GET['val']);
        $valCol = isset($_GET['valCol']) ? $_GET['valCol'] : null;
        $valValue = isset($_GET['valValue']) ? rawurldecode($_GET['valValue']) : null;
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor");


        $_SESSION[$cCode]['items'][$iID][$colName] = $val;

        if ($valValue != null && $valCol != null) {
            $_SESSION[$cCode]['items'][$iID][$valCol] = $valValue;
        }

        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        //        $initMasterValues = array(
        //            "olehID" => my_id(),
        //            "olehName" => my_name(),
        //            "sellerID" => my_id(),
        //            "sellerName" => my_name(),
        //            "placeID" => my_cabang_id(),
        //            "placeName" => my_cabang_nama(),
        //            "divID" => my_div_id(),
        //            "divName" => my_div_nama(),
        //            "cabangID" => my_cabang_id(),
        //            "cabangName" => my_cabang_nama(),
        //            "gudangID" => my_gudang_id(),
        //            "gudangName" => my_gudang_nama(),
        //            "jenis_usaha" => my_jenis_usaha(),
        //            "tokoID" => my_toko_id(),
        //            "tokoNama" => my_toko_nama(),
        //            "jenisTr" => $this->jenisTr,
        //            "jenisTrMaster" => $this->jenisTr,
        //            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
        //            "jenisTrName" => $configUiJenis['steps'][1]['label'],
        //            "stepNumber" => $stepNum,
        //            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
        //            "dtime" => dtimeNow(),
        //            "fulldate" => dtimeNow("Y-m-d"),
        //            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        //        );
        $initMasterValues = heInitMasterValues_he_cart($this->jenisTr, $stepNum, $this->configUiJenis);
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $this->jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";


    }

    public function recordPairedItem()
    {

        $cCode = $this->cCode;
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();


        $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][1] : array();
        $priceConfig = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $selectorModel = $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = $this->configUi[$this->jenisTr]['selectorSrcModel'];
        $clonerConfig = isset($this->configUi[$this->jenisTr]['cloner']) ? $this->configUi[$this->jenisTr]['cloner'] : array();
        $mainClonerConfig = isset($this->configUi[$this->jenisTr]['mainCloner']['rsltItems']) ? $this->configUi[$this->jenisTr]['mainCloner']['rsltItems'] : array();
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor");


        $this->load->model("Mdls/" . $selectorSrcModel);
        $b = new $selectorSrcModel();


        if (!isset($_SESSION[$cCode]["items2_sum"])) {
            $_SESSION[$cCode]["items2_sum"] = array();
        }


        $id = $iID = $_GET['iid'];
        $colName = $this->uri->segment(5);
        $val = urldecode($_GET['val']);
        $valCol = isset($_GET['valCol']) ? $_GET['valCol'] : null;
        $valValue = isset($_GET['valValue']) ? urldecode($_GET['valValue']) : null;


        if (isset($_SESSION[$cCode]["items2_sum"][$iID])) {
            $_SESSION[$cCode]["items2_sum"][$iID] = null;
            unset($_SESSION[$cCode]["items2_sum"][$iID]);
        }


        $tmpB = $b->lookupByID($val)->result();
        if (sizeof($tmpB) > 0) {
            foreach ($tmpB as $row) {

                $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                $tmpJml = $_SESSION[$cCode]['items'][$iID]['jml'];

                $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");

                if (!array_key_exists($val, $_SESSION[$cCode]["items2_sum"])) {
                    $tmp = array(
                        "handler" => $this->uri->segment(1) . "/" . $this->uri->segment(2),
                        "id" => $val,
                        "jml" => $tmpJml,
                        "harga" => 0,
                        "subtotal" => 0,
                    );

                    if (sizeof($priceConfig) > 0) {
                        $mdlName = $priceConfig['model'];
                        $this->load->model("Mdls/" . $mdlName);
                        $h = new $mdlName();
                        $h->addFilter("produk_id='$val'");
                        $h->addFilter("status='1'");
                        //                        $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                        $h->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                        $this->db->where_in("jenis_value", $priceConfig['label']);
                        $tmpH = $h->lookupAll($val)->result();
                        cekHere(":: $mdlName ::");
                        showLast_query("biru");
                        cekHere(sizeof($tmpH));
                        arrPrintPink($tmpH);
                        if (sizeof($tmpH) > 0) {
                            foreach ($tmpH as $hSpec) {
                                foreach ($priceConfig['key_label'] as $key => $val) {
                                    if ($key == $hSpec->jenis_value) {
                                        $tmp[$val] = isset($hSpec->nilai) ? ($hSpec->nilai + 0) : 0;
                                    }
                                }
                            }
                        }
                        else {
                            $errMsgs = array();
                            foreach ($priceConfig['key_label'] as $key => $val) {
                                $errMsgs[] = "$key " . $row->nama . " belum ditentukan. Silahkan diseting dahulu.";
                            }
                            if (sizeof($errMsgs) > 0) {
                                $_SESSION['errMsg'] = implode("<br>", $errMsgs);
                                die(lgShowAlertBiru($_SESSION['errMsg']));
                            }
                        }
                    }

                    if (sizeof($clonerConfig) > 0) {
                        if (sizeof($clonerConfig['cloneLabel'])) {
                            foreach ($clonerConfig['cloneLabel'] as $label) {
                                $tmp[$label] = $_SESSION[$cCode][$clonerConfig['srcGateName']][$iID][$label];
                            }
                        }
                    }


                    foreach ($fieldSrcs as $key => $src) {
                        $tmp[$key] = makeValue($src, $tmp, $tmp, $row->$src);
                    }


                    //region perhitungan subtotal items
                    $cal = new FieldCalculator();

                    if ($subAmountConfig != null) {
                        $subtotal = makeValue($subAmountConfig, $tmp, $tmp, 0);
                    }
                    else {
                        $subtotal = 0;
                        cekHijau("subtotal NOL");
                    }
                    $tmp["subtotal"] = $subtotal;
                    $_SESSION[$cCode]["items2_sum"][$iID] = $tmp;
                    //endregion

                }
                else {
                    if (sizeof($itemNumLabels) > 0) {
                        echo("iterating subNums..");
                        foreach ($itemNumLabels as $key => $label) {
                            if (isset($_GET[$key]) && $_GET[$key] > 0) {
                                $newValue = $_GET[$key];
                                $tmp[$key] = $newValue;
                                $_SESSION[$cCode]["items2_sum"][$iID][$key] = $newValue;
                                echo "replacing value for $key with " . $newValue . "<br>";
                            }

                        }

                        foreach ($itemNumLabels as $key => $label) {
                            $_SESSION[$cCode]["items2_sum"][$iID]["sub_" . $key] = ($_SESSION[$cCode]["items2_sum"][$iID][$key] * $_SESSION[$cCode]["items2_sum"][$iID]["jml"]);
                        }
                        $_SESSION[$cCode]["items2_sum"][$iID]['sub_nett'] = ($_SESSION[$cCode]["items2_sum"][$iID]['nett'] * $_SESSION[$cCode]["items2_sum"][$iID]['jml']);
                        $_SESSION[$cCode]["items2_sum"][$iID]['subtotal'] = ($_SESSION[$cCode]["items2_sum"][$iID]['jml'] * $_SESSION[$cCode]["items2_sum"][$iID]['harga']);
                    }
                }

                if (sizeof($mainClonerConfig) > 0) {
                    foreach ($mainClonerConfig as $key => $val) {
                        $_SESSION[$cCode]['main'][$key] = $row->$val;
                    }
                }
            }
        }


        if ($valValue != null && $valCol != null) {
            $_SESSION[$cCode]["items2_sum"][$iID][$valCol] = $valValue;
        }
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        //        $initMasterValues = heInitMasterValues_he_cart($this->jenisTr, $stepNum, $this->configUiJenis);
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $this->jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";

    }

    public function recordPairedItemSatuan()
    {

        $cCode = $this->cCode;
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();


        $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][1] : array();
        $priceConfig = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $selectorModel = $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = $this->configUi[$this->jenisTr]['selectorSrcModel'];
        $clonerConfig = isset($this->configUi[$this->jenisTr]['cloner']) ? $this->configUi[$this->jenisTr]['cloner'] : array();
        $mainClonerConfig = isset($this->configUi[$this->jenisTr]['mainCloner']['items2']) ? $this->configUi[$this->jenisTr]['mainCloner']['items2'] : array();
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;

        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor");

        $this->load->model("Mdls/" . $selectorSrcModel);
        $b = new $selectorSrcModel();

        $id = $iID = $_GET['iid'];
        $colName = $this->uri->segment(5);
        $val = urldecode($_GET['val']);
        $valCol = isset($_GET['valCol']) ? $_GET['valCol'] : null;
        $valValue = isset($_GET['valValue']) ? urldecode($_GET['valValue']) : null;


        if (!isset($_GET['newQty'])) {
            if (isset($_SESSION[$cCode]['items2_sum'][$iID])) {
                $_SESSION[$cCode]['items2_sum'][$iID] = null;
                unset($_SESSION[$cCode]['items2_sum'][$iID]);
            }
            //            if (isset($_SESSION[$cCode]['rsltItems'][$iID])) {
            //                $_SESSION[$cCode]['rsltItems'][$iID] = null;
            //                unset($_SESSION[$cCode]['rsltItems'][$iID]);
            //            }
        }


        $tmpB = $b->lookupByID($val)->result();

        if (sizeof($tmpB) > 0) {

            foreach ($tmpB as $row) {

                $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                $tmpJml = $_SESSION[$cCode]['items'][$iID]['jml'];


                $_SESSION[$cCode]['items'][$iID]['targetID'] = isset($row->id) ? $row->id : 0;
                $_SESSION[$cCode]['items'][$iID]['targetName'] = isset($row->nama) ? $row->nama : "";
                $_SESSION[$cCode]['items'][$iID]['targetNama'] = isset($row->nama) ? $row->nama : "";


                $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");


                if (!array_key_exists($iID, $_SESSION[$cCode]['items2_sum'])) {
                    $tmp = array(
                        "handler" => $this->uri->segment(1) . "/" . $this->uri->segment(2),
                        "id" => $val,
                        "jml" => $tmpJml,
                        "harga" => 0,
                        "subtotal" => 0,
                        "produk_jenis" => "into",
                        "id_src" => "$iID",
                        "jml_per_satuan" => $tmpJml,
                    );

                    if (sizeof($priceConfig) > 0) {
                        $mdlName = $priceConfig['model'];
                        $this->load->model("Mdls/" . $mdlName);
                        $h = new $mdlName();
                        $h->addFilter("produk_id='$val'");
                        $h->addFilter("status='1'");
                        //                        $h->addFilter("jenis_value='" . $priceConfig['label'] . "'");
                        $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                        $h->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                        $tmpH = $h->lookupAll($val)->result();
                        //                        cekMerah($this->db->last_query());
                        if (sizeof($tmpH) > 0) {
                            foreach ($tmpH as $hSpec) {
                                foreach ($priceConfig['key_label'] as $key => $val) {
                                    if ($key == $hSpec->jenis_value) {
                                        $tmp[$val] = isset($hSpec->nilai) ? ($hSpec->nilai + 0) : 0;
                                        //                                        $tmp['hpp'] = isset($hSpec->nilai) ? ($hSpec->nilai + 0) : 0;
                                        //                                        if(isset($hSpec->nilai)){
                                        //                                            $tmp[$val] = ($hSpec->nilai + 0);
                                        //                                        }
                                        //                                        else{
                                        //                                            mati_disini("HAHAHAAHA");
                                        //                                            die(lgShowAlert("$key belum didefine. silahkan hubungi admin."));
                                        //                                        }
                                    }
                                }
                            }
                        }
                        //                        $tmp['harga'] = isset($tmpH[0]->nilai) ? ($tmpH[0]->nilai + 0) : 0;
                        //                        $tmp['hpp'] = isset($tmpH[0]->nilai) ? ($tmpH[0]->nilai + 0) : 0;
                    }

                    if (sizeof($clonerConfig) > 0) {
                        if (sizeof($clonerConfig['cloneLabel'])) {
                            foreach ($clonerConfig['cloneLabel'] as $label) {
                                $tmp[$label] = $_SESSION[$cCode][$clonerConfig['srcGateName']][$iID][$label];
                            }
                        }
                    }


                    foreach ($fieldSrcs as $key => $src) {
                        $tmpEx = $cal->multiExplode($src);
                        if (sizeof($tmpEx) > 1) {//===berarti mengandung karakter simbol perhitungan
                            cekBiru("$key perhitungan");
                            $newSrc = $src;
                            foreach ($tmpEx as $key2 => $val2) {

                                if (!is_numeric($val2)) {
                                    if (isset($tmp[$val2]) && $tmp[$val2] > 0) {
                                        $newSrc = str_replace($val2, $tmp[$val2], $newSrc);
                                    }
                                    else {
                                        $newSrc = str_replace($val2, 0, $newSrc);
                                    }
                                }
                                //                                else {
                                //                                    if (isset($_SESSION[$cCode]['main'][$val2]) && $_SESSION[$cCode]['main'][$val2] > 0) {
                                //                                        $newSrc = str_replace($val2, $_SESSION[$cCode]['main'][$val2], $newSrc);
                                //                                    } else {
                                //                                        if (isset($_SESSION[$cCode]['main'][$val2]) && $_SESSION[$cCode]['main'][$val2] > 0) {
                                //                                            $newSrc = str_replace($val2, $_SESSION[$cCode]['main'][$val2], $newSrc);
                                //                                        } else {
                                //                                            $newSrc = str_replace($val2, 0, $newSrc);
                                //                                        }
                                //                                    }
                                //                                }
                            }
                            cekBiru("$$src -> $newSrc -> " . $cal->calculate($newSrc));
                            $tmp[$key] = $cal->calculate($newSrc);
                        }
                        else {
                            cekBiru("$key BUKAN perhitungan");
                            $tmp[$key] = $row->$src;
                        }
                    }


                    //region perhitungan subtotal items
                    $cal = new FieldCalculator();
                    if ($subAmountConfig != null) {
                        $tmpEx = $cal->multiExplode($subAmountConfig);
                        if (sizeof($tmpEx) > 1) {
                            $newSrc = $subAmountConfig;
                            foreach ($tmpEx as $key2 => $val2) {
                                if (isset($tmp[$val2])) {
                                    $newSrc = str_replace($val2, $tmp[$val2], $newSrc);
                                    cekKuning("$val2 direplace dengan " . $tmp[$val2]);
                                }
                                else {
                                    $newSrc = str_replace($val2, "0", $newSrc);
                                    cekKuning("$val2 direplace dengan NOL");
                                }

                            }
                            $subtotal = $cal->calculate($newSrc);
                            cekHijau("subtotal dari perhitungan $subAmountConfig $newSrc");

                        }
                        else {
                            $subtotal = 0;
                            cekHijau("subtotal dari perhitungan yang gak ada");
                        }
                    }
                    else {
                        $subtotal = 0;
                        cekHijau("subtotal NOL");
                    }
                    $tmp["subtotal"] = $subtotal;
                    $_SESSION[$cCode]['items2_sum'][$iID] = $tmp;


                    //endregion

                }
                else {
                    cekUngu("BAWAH, ganti jumlah bawah items target");
                    if (isset($_GET['newQty'])) {
                        $_SESSION[$cCode]['items2_sum'][$iID]['jml'] = $_GET['newQty'];
                        $_SESSION[$cCode]['items2_sum'][$iID]['subtotal'] = ($_SESSION[$cCode]['items2_sum'][$iID]['jml'] * $_SESSION[$cCode]['items2_sum'][$iID]['harga']);

                        if ($_GET['newQty'] >= $tmpJml) {
                            $jml_satuan = $_GET['newQty'] / $tmpJml;
                            $jml_satuan_ex = explode(".", $jml_satuan);
                            if (sizeof($jml_satuan_ex) > 1) {
                                die(lgShowAlert("konversi salah. silahkan cek ulang jumlah per-item konversinya."));
                            }
                        }
                        else {
                            die(lgShowAlert("konversi salah. silahkan cek ulang jumlah per-item konversinya."));
                        }
                        $_SESSION[$cCode]['items2_sum'][$iID]['jml_per_satuan'] = $jml_satuan;
                        $_SESSION[$cCode]['items'][$iID]['jml_per_satuan'] = $jml_satuan;
                    }


                    if (sizeof($itemNumLabels) > 0) {
                        echo("iterating subNums..");
                        foreach ($itemNumLabels as $key => $label) {
                            if (isset($_GET[$key]) && $_GET[$key] > 0) {
                                $newValue = $_GET[$key];
                                $tmp[$key] = $newValue;
                                $_SESSION[$cCode]['items2_sum'][$iID][$key] = $newValue;
                                //                                $_SESSION[$cCode]['rsltItems'][$iID][$key] = $newValue;
                                echo "replacing value for $key with " . $newValue . "<br>";
                            }
                        }

                        foreach ($itemNumLabels as $key => $label) {
                            $_SESSION[$cCode]['items2_sum'][$iID]["sub_" . $key] = ($_SESSION[$cCode]['items2_sum'][$iID][$key] * $_SESSION[$cCode]['items2_sum'][$iID]["jml"]);
                            //                            $_SESSION[$cCode]['rsltItems'][$iID]["sub_" . $key] = ($_SESSION[$cCode]['rsltItems'][$iID][$key] * $_SESSION[$cCode]['rsltItems'][$iID]["jml"]);
                        }
                        $_SESSION[$cCode]['items2_sum'][$iID]['sub_nett'] = ($_SESSION[$cCode]['items2_sum'][$iID]['nett'] * $_SESSION[$cCode]['items2_sum'][$iID]['jml']);
                        $_SESSION[$cCode]['items2_sum'][$iID]['subtotal'] = ($_SESSION[$cCode]['items2_sum'][$iID]['jml'] * $_SESSION[$cCode]['items2_sum'][$iID]['harga']);
                    }
                }


                if (sizeof($mainClonerConfig) > 0) {
                    foreach ($mainClonerConfig as $key => $val) {
                        $_SESSION[$cCode]['main'][$key] = $row->$val;
                    }
                }
            }
        }


        if ($valValue != null && $valCol != null) {
            $_SESSION[$cCode]['items2_sum'][$iID][$valCol] = $valValue;

        }
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        //        $initMasterValues = heInitMasterValues_he_cart($this->jenisTr, $stepNum, $this->configUiJenis);
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $this->jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";
    }

    public function recordImage()
    {
        $cCode = $this->cCode;
        $colName = $this->uri->segment(5);
        $id = $iID = $this->uri->segment(6);
        $valCol = isset($_GET['valCol']) ? $_GET['valCol'] : null;
        $valValue = isset($_GET['valValue']) ? urldecode($_GET['valValue']) : null;
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor");

        $files = $_FILES['file'];

        if ($files['error'] == 0) {

            $cUrl_result = upload_image($files);

            $_SESSION[$cCode]['items'][$iID][$colName] = $cUrl_result->full_url;
        }
        $addQS = "";


        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        //        $initMasterValues = heInitMasterValues_he_cart($this->jenisTr, $stepNum, $this->configUiJenis);
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $this->jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";

    }

    public function recordPairedItemOther()
    {

        $cCode = $this->cCode;
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();


        $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][1] : array();
        $priceConfig = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;

        $selectorModel = $this->configUi[$this->jenisTr]['selectorModelTarget'];
        $selectorSrcModel = $this->configUi[$this->jenisTr]['selectorSrcModelTarget'];

        $clonerConfig = isset($this->configUi[$this->jenisTr]['cloner']) ? $this->configUi[$this->jenisTr]['cloner'] : array();
        $mainClonerConfig = isset($this->configUi[$this->jenisTr]['mainCloner']['rsltItems']) ? $this->configUi[$this->jenisTr]['mainCloner']['rsltItems'] : array();
        $stepNum = $_SESSION[$cCode]['main']['stepNumber'] > 0 ? $_SESSION[$cCode]['main']['stepNumber'] : 1;
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor");


        $this->load->model("Mdls/" . $selectorSrcModel);
        $b = new $selectorSrcModel();


        if (!isset($_SESSION[$cCode]["items2_sum"])) {
            $_SESSION[$cCode]["items2_sum"] = array();
        }


        $id = $iID = $_GET['iid'];
        $colName = $this->uri->segment(5);
        $val = urldecode($_GET['val']);
        $valCol = isset($_GET['valCol']) ? $_GET['valCol'] : null;
        $valValue = isset($_GET['valValue']) ? urldecode($_GET['valValue']) : null;


        if (isset($_SESSION[$cCode]["items2_sum"][$iID])) {
            $_SESSION[$cCode]["items2_sum"][$iID] = null;
            unset($_SESSION[$cCode]["items2_sum"][$iID]);
        }


        $tmpB = $b->lookupByID($val)->result();

        if (sizeof($tmpB) > 0) {
            foreach ($tmpB as $row) {


                $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                $tmpJml = $_SESSION[$cCode]['items'][$iID]['jml'];

                $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");

                if (!array_key_exists($val, $_SESSION[$cCode]["items2_sum"])) {
                    $tmp = array(
                        "handler" => $this->uri->segment(1) . "/" . $this->uri->segment(2),
                        "id" => $val,
                        "jml" => $tmpJml,
                        "harga" => 0,
                        "subtotal" => 0,
                    );

                    if (sizeof($priceConfig) > 0) {
                        $mdlName = $priceConfig['model'];
                        $this->load->model("Mdls/" . $mdlName);
                        $h = new $mdlName();
                        $h->addFilter("produk_id='$val'");
                        $h->addFilter("status='1'");
                        $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                        $h->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                        $tmpH = $h->lookupAll($val)->result();
                        //                        cekMerah($this->db->last_query());
                        //mati_disini("pID: $val");
                        if (sizeof($tmpH) > 0) {
                            foreach ($tmpH as $hSpec) {
                                foreach ($priceConfig['key_label'] as $key => $val) {
                                    if ($key == $hSpec->jenis_value) {
                                        $tmp[$val] = isset($hSpec->nilai) ? ($hSpec->nilai + 0) : 0;
                                    }
                                }
                            }
                        }
                        else {
                            $errMsgs = array();
                            foreach ($priceConfig['key_label'] as $key => $val) {
                                $errMsgs[] = "$key " . $row->nama . " is required (" . __LINE__ . ")";
                            }
                            if (sizeof($errMsgs) > 0) {
                                $_SESSION['errMsg'] = implode("<br>", $errMsgs);
                                //                                echo lgShowAlert($_SESSION['errMsg']);
                                die(lgShowAlert($_SESSION['errMsg']));
                            }
                            //                            mati_disini("---");
                        }
                    }

                    if (sizeof($clonerConfig) > 0) {
                        if (sizeof($clonerConfig['cloneLabel'])) {
                            foreach ($clonerConfig['cloneLabel'] as $label) {
                                $tmp[$label] = $_SESSION[$cCode][$clonerConfig['srcGateName']][$iID][$label];
                            }
                        }
                    }


                    foreach ($fieldSrcs as $key => $src) {
                        $tmp[$key] = makeValue($src, $tmp, $tmp, $row->$src);
                    }


                    //region perhitungan subtotal items
                    $cal = new FieldCalculator();

                    if ($subAmountConfig != null) {
                        $subtotal = makeValue($subAmountConfig, $tmp, $tmp, 0);
                    }
                    else {
                        $subtotal = 0;
                        cekHijau("subtotal NOL");
                    }
                    $tmp["subtotal"] = $subtotal;
                    $_SESSION[$cCode]["items2_sum"][$iID] = $tmp;
                    //endregion

                }
                else {
                    if (sizeof($itemNumLabels) > 0) {
                        echo("iterating subNums..");
                        foreach ($itemNumLabels as $key => $label) {
                            if (isset($_GET[$key]) && $_GET[$key] > 0) {
                                $newValue = $_GET[$key];
                                $tmp[$key] = $newValue;
                                $_SESSION[$cCode]["items2_sum"][$iID][$key] = $newValue;
                                echo "replacing value for $key with " . $newValue . "<br>";
                            }

                        }

                        foreach ($itemNumLabels as $key => $label) {
                            $_SESSION[$cCode]["items2_sum"][$iID]["sub_" . $key] = ($_SESSION[$cCode]["items2_sum"][$iID][$key] * $_SESSION[$cCode]["items2_sum"][$iID]["jml"]);
                        }
                        $_SESSION[$cCode]["items2_sum"][$iID]['sub_nett'] = ($_SESSION[$cCode]["items2_sum"][$iID]['nett'] * $_SESSION[$cCode]["items2_sum"][$iID]['jml']);
                        $_SESSION[$cCode]["items2_sum"][$iID]['subtotal'] = ($_SESSION[$cCode]["items2_sum"][$iID]['jml'] * $_SESSION[$cCode]["items2_sum"][$iID]['harga']);
                    }
                }

                if (sizeof($mainClonerConfig) > 0) {
                    foreach ($mainClonerConfig as $key => $val) {
                        $_SESSION[$cCode]['main'][$key] = $row->$val;
                    }
                }
            }
        }


        if ($valValue != null && $valCol != null) {
            $_SESSION[$cCode]["items2_sum"][$iID][$valCol] = $valValue;
        }
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "sellerID" => my_id(),
            "sellerName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => $stepNum,
            "stepCode" => $configUiJenis['steps'][$stepNum]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        //        $initMasterValues = heInitMasterValues_he_cart($this->jenisTr, $stepNum, $this->configUiJenis);
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $this->jenisTr . "?epreketek=yes&populate=1');";
        echo "</script>";

    }

    //----------------
    public function checklistOpname()
    {

        $pID = $_GET['id'];
        $cCode = $this->cCode;

        if (isset($_SESSION[$cCode]['items'][$pID])) {
            //---- masuk gerbang ceklist, di items
            $_SESSION[$cCode]['items'][$pID]['ceklist_opname'] = 1;
        }

        //        mati_disini("cek pID: $pID");
    }

    public function checklistOpnameNote()
    {
        //        arrPrint($_GET);
        $cCode = $this->cCode;
        $note1 = blobDecode($_GET['note1']);
        $note2 = blobDecode($_GET['note2']);

        if (isset($_SESSION[$cCode]['main'])) {
            if (isset($_GET['note1'])) {

                $_SESSION[$cCode]['main']['opnameNote_1'] = $note1;
                $_SESSION[$cCode]['main']['opnameNoteCeklist_1'] = 1;
            }
            if (isset($_GET['note2'])) {

                $_SESSION[$cCode]['main']['opnameNote_2'] = $note2;
                $_SESSION[$cCode]['main']['opnameNoteCeklist_2'] = 1;
            }
        }
    }

    //-----------------------------------
    public function buildValues()
    {
        $cCode = $this->cCode;
        $jenisTr = $this->jenisTr;
        $configUiJenis = $this->configUi[$jenisTr];
        $configCoreJenis = $this->configCore[$jenisTr];
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");
        $id = 0;
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($configUiJenis);
        $vg->setConfigCoreJenis($configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "divID" => my_div_id(),
            "divName" => my_div_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "jenis_usaha" => my_jenis_usaha(),
            "tokoID" => my_toko_id(),
            "tokoNama" => my_toko_nama(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUiJenis['steps'][1]['target'],
            "jenisTrName" => $configUiJenis['steps'][1]['label'],
            "stepNumber" => 1,
            "stepCode" => $configUiJenis['steps'][1]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($jenisTr, $id, $initMasterValues, $this->modul);

        echo "<script>";
        echo "top.$('#shopping_cart').load('" . base_url() . $this->modul . "/" . "_shoppingCart/viewCart/" . $jenisTr . "?epreketek=yes');";
        echo "</script>";
    }

    public function recordShoppingCart($cCode)
    {

        $toko_id = my_toko_id();
        $shopingcart_id = isset($_SESSION[$cCode]['main']['shoppingcart_order_id']) && $_SESSION[$cCode]['main']['shoppingcart_order_id']*1>0 ? $_SESSION[$cCode]['main']['shoppingcart_order_id']*1 : 0;
        $olehID = isset($this->session->login['id']) ? $this->session->login['id'] : 0;

        if($shopingcart_id*1>0 && $olehID*1 > 0){
            $file = fopen(__DIR__ . '/view/display_' . $toko_id . "_$olehID" . "_".$shopingcart_id.".json", "w");
            fwrite($file, json_encode( $_SESSION[$cCode] ));
            fclose($file);
        }

    }

    public function viewDisplayPenjualan()
    {

        $toko_id = my_toko_id();

        $TMC = explode("/", MODUL_CONFIG_PATH);
        $urlDisplay = APPPATH . $TMC[2] . "/" . $TMC[3] . "/view/" ."display/";

        $storage = fopen($urlDisplay . "" . $toko_id . ".json", "r");
        $txt = fread($storage, filesize($urlDisplay . "" . $toko_id . ".json"));

        echo $txt;
    }

    public function diskon_off(){

        $cCode = $this->cCode;
        $expls = explode("_", $_GET['t']);


        // arrPrint(url_segment());
        // arrPrintHijau($_GET);
        // arrPrintKuning($expls);
        $diskon_mode = $expls[0];
        $produk_id = $expls[1];
        $sesItems = $_SESSION[$cCode]['items'];
        $itemParams = $sesItems[$produk_id];
        // arrPrintWebs($itemParams);

        $harga_list = $itemParams['harga_list'];
        $jml = $itemParams['jml'];
        $qty = $itemParams['qty'];
        $qty_unit = $itemParams['qty_unit'];

        switch ($diskon_mode) {

            case "free":
            case "free_items":

                // ------------------------------------------------
                $itemParams["discPersen_off"] = $itemParams["discPersen"];
                unset($itemParams["discPersen"]);

                if(isset($itemParams["free_items_off"])){
                    $itemParams["free_items"] = $itemParams["free_items_off"];
                    unset($itemParams["free_items_off"]);
                }

            $grosir_status = 0;
            $free_status = 1;
                break;
            case "grosir":
            case "discPersen":

                // ----------------------------------------------------
                $itemParams["free_items_off"] = $itemParams["free_items"];
                unset($itemParams["free_items"]);

            if(isset($itemParams["discPersen_off"])){
                $itemParams["discPersen"] = $itemParams["discPersen_off"];
                unset($itemParams["discPersen_off"]);
            }

            $grosir_status = 1;
            $free_status = 0;
                break;
        }

        // arrPrintPink($itemParams);
        $_SESSION[$cCode]["items"][$produk_id] = $itemParams;

        $proses_select_produk = MODUL_PATH ."_processSelectProduct/select/582?id=$produk_id&newQty=$jml&qty_unit=$jml&grosir=$grosir_status&free=$free_status";
        // matiHere("$proses_select_produk");

        echo "<script>
                $('#search_result').load('$proses_select_produk');
        </script>";

        // matiHere(__FILE__ . __LINE__);
    }
}