<?php

/**
 * Created by PhpStorm.
 * User: chepy
 * Date: 02/11/2023
 * Time: 14:05
 */
require_once "Modul_Controller.php";

class _pembayaran_pos extends Modul_Controller
{

    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();
        $validasiHpp = isset($this->configUi[$this->jenisTr]['validasiHpp']) ? $this->configUi[$this->jenisTr]['validasiHpp'] : false;

        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']];
                }
            }
        }
        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'] : "",
                        "tipe_produk"        => isset($iSpec['tipe_produk']) ? $iSpec['tipe_produk'] : "",
                    );
                    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;

                    //                    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
        * ---------------------------------------------------------------------------------*/
        $main_tmp = array();
        $tidak_dipakai = 1;
        if ($tidak_dipakai == 0) {
            $str_customer = "";
            $info_member_style = "";

            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;

                $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');
                $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'];

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

                            if (($trans_nilai >= $gro_minim_db) && ($trans_nilai <= $gro_maxim)) {

                                /* --------------------------------------------------------------
                                     * pembatasan tgl setting diskon
                                     * --------------------------------------------------------------*/
                                $d_pokok = 0;
                                $gro_minim = 0;
                                if ($tgl_now >= $gro_start && $tgl_now <= $gro_stop) {
                                    // cekHijau("$tgl_now >= $gro_start && $tgl_now <= $gro_stop");
                                    // cekHijau();
                                    $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;
                            }

                        }
                    }
                }

                // 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_transaksi'] = (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'];

                // 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]['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'];

                /* ---------------------------------------------
                     * 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");
                $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>";
                $str_customer .= "<div class='col-md-3 bg-success info-member'></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();
        $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) {
                            foreach ($addRowsConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                                if (isset($oValSpec['addPoints']) && in_array(1, $oValSpec['addPoints'])) {
                                    $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)){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;";

                                    switch($oValueName){
                                        case "card_number":
                                            $clearDefVal = FormatCreditCard( sprintf('%.0f', $defVal) );
                                            $blurStr = "if(this.value!=this.defaultValue){hiliteDiv(this);document.getElementById('result').src=$relInputTarget;}";
                                            $relInputTarget = "'" . MODUL_PATH . get_class($this) . "/recordAddRow/" . $this->jenisTr . "/$oValueName/?val='+this.value";
                                            break;
                                        case "appr_code":
                                            $clearDefVal = $defVal;
                                            break;
                                        default:
                                            $clearDefVal = addCommas($defVal);
                                            break;
                                    }

                                    $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='$clearDefVal' $minValStr $maxValStr
                                                                onfocus='this.select()'
                                                                onkeyup=\"$keyupStr\"
                                                                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 no-padding'>";

                        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>";
                                        }
                                        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] .= "
                                            <div class='checkbox'>
                                            <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>
                                            </div>\n";
                                        }
                                    }
                                }
                                break;
                            case "open":
                                if (sizeof($tmpo) > 0) {
                                    foreach ($tmpo as $row) {
                                        $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                        $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                        $elStr[$eName] .= "<input value='" . $row->$keySrc . "' $selected>";
                                    }
                                }
                                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 .= "<div class='panel-body no-padding'>";
                                $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=''>";
                        $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 == "" ? "bg-red" : "bg-info",
                            "iconOke" => $defValue == "" ? "" : "<i class='fa fa-check-circle text-green'></i>&nbsp;",
                        );


                        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 == "" ? "bg-red" : "bg-info",
                            "iconOke" => $defaultValue == "" ? "" : "<i class='fa fa-check-circle text-green'></i>&nbsp;",
                        );

                        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) {
                                                $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 no-padding'>";
                                        $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=''>";
                                $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"   => sizeof($tmpo) > 0 ? $elStr[$eName] : $nonStr[$eName],
                                                               "editStr"  => $editStr,
                                                               "addStr"   => $addStr,
                                                               "bgColor"  => $defValue == "" ? "bg-red" : "bg-info",
                                                               "iconOke"  => $defValue == "" ? "" : "<i class='fa fa-check-circle text-green'></i>&nbsp;",
                                                               "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 == "" ? "bg-red" : "bg-info",
                                                               "iconOke"  => $defaultValue == "" ? "" : "<i class='fa fa-check-circle text-green'></i>&nbsp;",
                                                               "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();

        /* --------------------------- ---------------------------
         * pengenalan diskon yg harus dipilih
         * --------------------------- ---------------------------*/
        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];
                }
            }

            $sesItems = $_SESSION[$cCode]['items'];
            // arrPrintWebs($sesItems);
            $ikoloms = array(
                "discPersen",
                "free_items",
            );
            $itemDiskons = array();
            foreach ($sesItems as $iproduk_id => $iparams) {

                $idatas = array();
                foreach ($ikoloms as $ikolom) {
                    $idatas[$ikolom] = isset($iparams[$ikolom]) ? $iparams[$ikolom] : "";
        }
                $idata_diskon = array_filter($idatas);

                if(count($idata_diskon) > 1){
                    $itemDiskons[$iproduk_id] = $idata_diskon;
        }
            }
        }
        // arrPrintKuning(($itemDiskons));

        //-------------------------------------------------------------------------------
        $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 . "/";

        $data = array(
            "main"               => $main,
            "showScheme"         => $arrCons,
            "showItems"          => $showItems,
            "cCode"              => $cCode,
            "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,

            "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(),

            //--------------------------------------------
            "arrHeaderElement"       => isset($arrHeaderElement) ? $arrHeaderElement : array(),
            // --
            "subItemLabels"          => $shoppingCartFieldsSubItems,
            "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"           => isset($str_customer) ? $str_customer : "",
            "info_member_style"      => isset($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']),
            "validasiHpp"            => $validasiHpp,
            "sesItems"            => $sesItems,
            "itemDiskons"            => $itemDiskons,
        );

        //==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);
            }
        }

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

    }

    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;

        $key = $_GET['key'];

        //reset dulu
        if (!empty($_SESSION[$cCode]['main_elements'])) {
            foreach ($_SESSION[$cCode]['main_elements'] as $elem => $rowElem) {
                if (isset($this->configUiJenis['relativeElements'][$elName][$key][$elem])) {
                    unset($_SESSION[$cCode]['main_elements'][$elem]);
                }
            }
        }

        unset($_SESSION[$cCode]['main']['bayar']);
        unset($_SESSION[$cCode]['main']['kembali']);
        unset($_SESSION[$cCode]['main']['total_disc']);

        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(),
            "machineID"     => $this->session->login['machineID'],
            "CPU_INFO"      => $this->session->login['CPU_INFO'],
            "COM_INFO"      => $this->session->login['COM_INFO'],
            "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"),
        );

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

        echo "<script>";

        //        echo "top.$('.viewModalPembayaran').load('" . base_url() . $this->modul . "/" . "_pembayaran_pos/viewCart/" . $jenisTr . "?epreketek=yes&populate=1');";

        echo "  if( top.$('.modal.pembayaran.in') ){
                    top.$('.btn-reload-modal-pembayaran').click();
                }
                else{
                    top.$('.viewModalPembayaran').load('" . base_url() . $this->modul . "/" . "_pembayaran_pos/viewCart/" . $jenisTr . "?epreketek=yes&populate=1');
                }
        ";

        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);

        $cabangID = $mains["cabangID"];
        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();
        $emp->addFilter("oto_settlement=1");
        $emp->addFilter("cabang_id='$cabangID'");
        $arrEmployee = $emp->lookUpAll()->result();

        if ($rowName == 'add_disc') {
            //unset($_SESSION[$cCode]['main']['oto_diskon']);
            $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'][$rowName]*1 == 0 && $val*1 > 0 && $_SESSION[$cCode]['main'][$rowName]*1 != $val*1) {

            if ($val * 1 > 0 && $_SESSION[$cCode]['main']['oto_diskon'] == 0) {
                //                $_SESSION[$cCode]['main']['oto_diskon'] = 0;
                $_SESSION[$cCode]['main'][$rowName] = 0;

                $emplyeeOption = "";

//                if (!empty($arrEmployee)) {
//                    $emplyeeOption .= "<div class='input-group input-group-md pull-right'>";
//                    $emplyeeOption .= "<select class='form-control select-otorisator text-bold text-uppercase'>";
//                    $emplyeeOption .= "<option value='0'>PILIH OTORISATOR</option>";
//                    foreach($arrEmployee as $i => $eRow ){
////                        echo "<option value='".$eRow->id."' class='text-bold text-uppercase'>".$eRow->nama."</option>";
//                        $emplyeeOption .= "<option value='".$eRow->id."' class='text-bold text-uppercase'>".$eRow->nama."</option>";
//                    }
//                    $emplyeeOption .= "</select>";

                    $emplyeeOption .= "<div class='col-lg-4 no-padding text-right'>";
                    $emplyeeOption .= "<div style='font-size: 14px;' class='text-bold text-muted text-capitalize'>&nbsp;</div>";
                    $emplyeeOption .= "<div class='input-group input-group-md pull-left'>";
                    $emplyeeOption .= "<select class='form-control select-otorisator text-bold text-uppercase'>";
                    $emplyeeOption .= "<option value='0'>PILIH OTORISATOR</option>";

                    if (!empty($arrEmployee)) {
                        foreach ($arrEmployee as $i => $eRow) {
                            $emplyeeOption .= "<option value='" . $eRow->id . "' class='text-bold text-uppercase'>" . $eRow->nama . "</option>";
                        }
                    }

                    $emplyeeOption .= "</select></div></div>";

                    $emplyeeOption .= "<div class='col-lg-8 no-padding text-left pull-right'>";
                    $emplyeeOption .= "<div style='font-size: 14px;' class='text-bold text-muted text-capitalize'>Masukan PIN/OTP SUPERVISOR</div>";
                    $emplyeeOption .= "<div class='input-group input-group-md'>";
                    $emplyeeOption .= "<form autocomplete='off'>";
                    $emplyeeOption .= "<input type='text' autocomplete='false' class='' style='display: none;'>";
                    $emplyeeOption .= "<input type='password' readonly onfocus='this.removeAttribute(`readonly`);' autocomplete='false' name='diskonPinOtp' id='diskonPinOtp' class='form-control' placeholder='PIN / OTP'>";
                    $emplyeeOption .= "</form>";
                    $emplyeeOption .= "<span class='input-group-btn'>";
                    $emplyeeOption .= "<div types='button' disabled id='btn-otorisasi' class='btn btn-info btn-flat btn-kirim'><i class='fa fa-send'></i> OTORISASI DISKON</div>";
                    $emplyeeOption .= "<div types='button' onclick='swal.close()' class='btn btn-danger btn-flat btn-close-kirim'><i class='fa fa-times'></i></div>";
                    $emplyeeOption .= "</span>";
                    $emplyeeOption .= "</div>";
                    $emplyeeOption .= "</div>";

                    $emplyeeOption .= "</div>";
                    $emplyeeOption .= "</div>";
                    $emplyeeOption .= "</div>";

//                }
//                else{
//
//                }

                echo "<script>
                    var otto_selected;
                    var showViewOtorisasiDiskon = function(){
                        top.$('.modal input#add_disc').val(0).trigger('mouseout')
                        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>add diskon $val<br><br>' +
                           \"<div class=''>\" +
                           \"$emplyeeOption\" +
                           \"</div>\" +
                           '',
                           type: 'warning',
                           showConfirmButton: false,
                           allowOutsideClick: false,
                           onOpen: function(){
                                if(otto_selected!=null){
                                    top.$('select.select-otorisator').val(otto_selected).change()
                                }
                                top.$('#diskonPinOtp').on('keyup', top.delay_v2( function(){
                                    if( this.value.length >= 6){
                                        activeBtnNextDiskon()
                                    }
                                }, 500) )
                                var activeBtnNextDiskon = function(){
                                    top.$('#btn-otorisasi').attr('disabled', false);
                                    top.$('#btn-otorisasi').off('click');
                                    top.$('#btn-otorisasi').on('click', function(){
                                        var pin_otp = top.$('#diskonPinOtp').val();
                                        var oto_settlement_id = otto_selected = top.$('select.select-otorisator option:checked').val();
                                        var oto_settlement_nama = top.$('select.select-otorisator option:checked').text();
                                        if( pin_otp != '' && oto_settlement_id !='0' ){
                                            top.$.ajax({
                                                url: '" . base_url() . $this->modul . "/_shoppingCart/add_discOtorisator/" . $this->jenisTr . "',
                                                method: 'post',
                                                data: {
                                                    pin_diskon: pin_otp,
                                                    oto_settlement_id: oto_settlement_id,
                                                },
                                                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');
                                                        top.swal.enableLoading();
                                                        setTimeout(function(){
                                                            showViewOtorisasiDiskon()
                                                        },2500)
                                                    }
                                                }
                                            })
                                        }
                                        else{
                                            if(oto_settlement_id==0){
                                                top.swal('Isian Kurang Lengkap', 'OTORISATOR HARUS DIPILIH DULU', 'warning');
                                                top.swal.enableLoading();
                                                setTimeout(function(){
                                                    showViewOtorisasiDiskon()
                                                }, 2500)
                                            }
                                            else if(pin_otp==''){
                                                top.swal('Isian Kurang Lengkap', 'PIN/OTP HARUS DI ISI DULU', 'warning');
                                                top.swal.enableLoading();
                                                setTimeout(function(){
                                                    showViewOtorisasiDiskon()
                                                }, 2500)
                                            }
                                            else{
                                                top.swal('Isian Kurang Lengkap', 'PIN/OTP dan NAMA OTORISATOR HARUS DIPILIH DULU', 'warning');
                                                top.swal.enableLoading();
                                                setTimeout(function(){
                                                    showViewOtorisasiDiskon()
                                                }, 2500)
                                            }
                                        }
                                    })
                                }
                           }
                        });
                    }
                    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);
                }

                echo $this->db->last_query() . "<br>";
                echo $cCode . "<br>";
                echo $_SESSION[$cCode]['main']['oto_diskon'] . "<br>";

                die();
            }

            if ($_SESSION[$cCode]['main']['oto_diskon'] == 1 && $_SESSION[$cCode]['main'][$rowName] == 0) {
                $_SESSION[$cCode]['main']['oto_diskon'] = 0;
                $_SESSION[$cCode]['main'][$rowName] = 0;
            }

            if ($_SESSION[$cCode]['main']['oto_diskon'] == 1 && $_SESSION[$cCode]['main'][$rowName] > 0) {
                $_SESSION[$cCode]['main']['oto_diskon'] = 0;
            }

            $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);
                      top.$(document).off('focusin.modal');
                  </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(),
            "machineID"     => $this->session->login['machineID'],
            "CPU_INFO"      => $this->session->login['CPU_INFO'],
            "COM_INFO"      => $this->session->login['COM_INFO'],
            "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);

        if($rowName=="bayar"){

        }
        else{
            echo "<script> top.$('.btn-reload-modal-pembayaran').click(); </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;
    }

}