<?php

/**
 * Created by PhpStorm.
 * User: aziz
 * Date: 9/18/2018
 * Time: 8:45 PM
 */

require_once "Modul_Controller.php";

class _processSelectNota extends Modul_Controller
{
    
//    private $jenisTr;
    protected $validateJenisTr = array();

    public function __construct()
    {
        parent::__construct();
        // $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;
        if (!isset($_SESSION[$cCode]['main']['refIDs'])) {
            $_SESSION[$cCode]['main']['refIDs'] = array();
        }
        if (!isset($_SESSION[$cCode]['main']['refs'])) {
            $_SESSION[$cCode]['main']['refs'] = "";
        }
        if (!isset($_SESSION[$cCode]['main']['refs_intext'])) {
            $_SESSION[$cCode]['main']['refs_intext'] = "";
        }

        $this->validateJenisTr = array(
            "771", "1771", //"475", "476", "477",
        );
    }

    public function select()
    {
        // $this->jenisTr = $this->uri->segment(4);
        $cCode = $this->cCode;
        $id = $_GET['transaksi_id'];

        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $componentAssConfig = isset($this->configUi[$this->jenisTr]['componentsAss']) ? $this->configUi[$this->jenisTr]['componentsAss'] : array();
        $relativeComNameDetails = isset($this->configUi[$this->jenisTr]['relativeComNameDetails']) ? $this->configUi[$this->jenisTr]['relativeComNameDetails'] : array();
        $isRadioSelect = isset($this->configUi[$this->jenisTr]['isPaymentRadioSelect']) ? $this->configUi[$this->jenisTr]['isPaymentRadioSelect'] : false;
        $trLabel = isset($this->configUi[$this->jenisTr]['label']) ? $this->configUi[$this->jenisTr]['label'] : "";

        if (in_array($this->jenisTr, $this->validateJenisTr)) {
            if (isset($_GET['extern_label2']) && ($_GET['extern_label2'] == null)) {
                die(lgShowAlert("$trLabel gagal dilanjutkan, karena jenis biaya tidak ditentukan saat request $trLabel."));
            }
        }


        if ($isRadioSelect) {
            $detailResetList = array(
                "items",
                "tableIn_detail",
                "tableIn_detail2",
                "tableIn_detail_values",
                "tableIn_detail2_sum",
                "tableIn_detail_values2_sum",
            );
            foreach ($detailResetList as $sSName) {
                $_SESSION[$cCode][$sSName] = null;
                unset($_SESSION[$cCode][$sSName]);
            }

            $_SESSION[$cCode]['main']['refIDs'] = null;
            unset($_SESSION[$cCode]['main']['refIDs']);


            if (sizeof($_SESSION[$cCode]['items']) > 0) {

            } else {
                $mainValueInjector = isset($this->configUi[$this->jenisTr]['mainValueInjectors']) ? $this->configUi[$this->jenisTr]['mainValueInjectors'] : array();
                if (sizeof($mainValueInjector) > 0) {
                    foreach ($mainValueInjector as $key => $val) {
                        $_SESSION[$cCode]['main'][$val] = null;
                        unset($_SESSION[$cCode]['main'][$val]);
                    }
                }
            }

            if (isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = null;
                unset($_SESSION[$cCode]['items2']);
            }

        }

        $initMain = array(
            "pihakID" => $_GET['extern_id'],
            "pihakName" => $_GET['extern_nama'],
            "valasDetails" => $_GET['valas_id'],
            "pihakMainName" => isset($_GET['extern_label2']) && sizeof($_GET['extern_label2']) > 0 ? $_GET['extern_label2'] : "",
            "other" => isset($_GET['extern_nilai4']) && sizeof($_GET['extern_nilai4']) > 0 ? $_GET['extern_nilai4'] : "",
            "relativeComName" => sizeof($relativeComNameDetails) > 0 ? $relativeComNameDetails[$_GET['extern_label2']] : "",
            "pph_23" => isset($_GET['pph_23']) ? $_GET['pph_23'] : 0,
            "terbayar_pph23" => isset($_GET['terbayar_pph23']) ? $_GET['terbayar_pph23'] : 0,

        );


        foreach ($initMain as $key => $src) {
            $_SESSION[$cCode]['main'][$key] = $src;
        }
        $row = $_GET;


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

        $id = $_GET['transaksi_id'];
        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $componentAssConfig = isset($this->configUi[$this->jenisTr]['componentsAss']) ? $this->configUi[$this->jenisTr]['componentsAss'] : array();


        if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
            cekMerah("akan memasukkan ITEMS");
            $tmp = array(
                "handler" => $this->uri->segment(1),
                "id" => $id,
                "refID" => $id,
                "jml" => 1,
                "harga" => 0,
                "satuan" => "-",
                "subtotal" => 0,
                //                "nama" => 0,
                //                "nomer" => 0,
            );

            foreach ($fieldSrcs as $key => $src) {
                $tmp[$key] = makeValue($src, $row, $row, 0);
            }
            if ($subAmountConfig != null) {
                $subtotal = makeValue($subAmountConfig, $row, $row, 0);
                $tmp["subtotal"] = $subtotal;
            } else {
                $tmp["subtotal"] = 0;
            }
            if (sizeof($componentAssConfig) > 0) {
                $this->load->model($componentAssConfig["model"]);
                $tr = new $componentAssConfig["model"]();
                $tmpReg = $tr->lookupRegistriesByMasterID($id)->result();
//                arrPrint($tmpReg);
                $itemsRegistries = array();
                if (sizeof($tmpReg) > 0) {
                    foreach ($tmpReg as $row) {
                        switch ($row->param) {
                            case "items"://
                                $itemsRegistries = unserialize(base64_decode($row->values));
                                break;
                        }
                    }

                }
                if (sizeof($relativeComNameDetails) > 0) {
                    $key = isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "";
                    cekHere($key);
                    cekHere("$relativeComNameDetails[$key] " . $relativeComNameDetails[$key]);
                    $tmp['relativeCom'] = isset($relativeComNameDetails[$key]) ? $relativeComNameDetails[$key] : "";
                    $tmp['rekName'] = isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "";
                }


            }


        } else {
            cekMerah("TIDAK akan memasukkan ITEMS");
        }


        $_SESSION[$cCode]['main']['refIDs'][$id] = $id;

        switch ($_GET['state']) {
            case "true":
                if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $_SESSION[$cCode]['items'][$id] = $tmp;
                }
                if (sizeof($componentAssConfig) > 0) {
                    if (!array_key_exists($id, $_SESSION[$cCode]['items2'])) {
                        $_SESSION[$cCode]['items2'][$id] = $itemsRegistries;
                    }
                }
                break;
            case "false":
                if (array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $detailResetList = array(
                        "items",
                        "tableIn_detail",
                        "tableIn_detail2",
                        "tableIn_detail_values",
                        "tableIn_detail2_sum",
                        "tableIn_detail_values2_sum",
                    );
                    foreach ($detailResetList as $sSName) {
                        $_SESSION[$cCode][$sSName][$id] = null;
                        unset($_SESSION[$cCode][$sSName][$id]);
                    }
                }
                if (isset($_SESSION[$cCode]['main']['refIDs'][$id])) {
                    $_SESSION[$cCode]['main']['refIDs'][$id] = null;
                    unset($_SESSION[$cCode]['main']['refIDs'][$id]);
                }

                if (sizeof($_SESSION[$cCode]['items']) > 0) {

                } else {

                    $mainValueInjector = isset($this->configUi[$this->jenisTr]['mainValueInjectors']) ? $this->configUi[$this->jenisTr]['mainValueInjectors'] : array();
                    if (sizeof($mainValueInjector) > 0) {
                        foreach ($mainValueInjector as $key => $val) {
                            $_SESSION[$cCode]['main'][$val] = null;

                            unset($_SESSION[$cCode]['main'][$val]);

                        }
                    }
                }
                if (isset($_SESSION[$cCode]['items2'][$id])) {
                    $_SESSION[$cCode]['items2'][$id] = null;
                    unset($_SESSION[$cCode]['items2'][$id]);
                }

                break;
        }
        if (sizeof($_SESSION[$cCode]['items2']) > 0) {
            cekBiru("bulding summary item_result...");
            $_SESSION[$cCode]['items2_sum'] = array();
            foreach ($_SESSION[$cCode]['items2'] as $pID => $pSpec) {
                foreach ($pSpec as $eSpec) {
                    if (!isset($_SESSION[$cCode]['items2_sum'][$eSpec['id']])) {
                        $_SESSION[$cCode]['items2_sum'][$eSpec['id']] = $eSpec;
                        $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['jml'] = 0;
                        $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['harga'] = 0;
                        $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['produk_ids'] = array();


                    }

                    $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['jml'] += $eSpec['jml'];
                    $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['harga'] += $eSpec['harga'];
                    $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['produk_ids'][$pID] = $pID;
                    if (sizeof($relativeComNameDetails) > 0) {
                        $key = isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "";
                        cekHere($key);
                        cekHere("$relativeComNameDetails[$key] " . $relativeComNameDetails[$key]);
                        $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['relativeCom'] = isset($relativeComNameDetails[$key]) ? $relativeComNameDetails[$key] : "";
                        $_SESSION[$cCode]['items2_sum'][$eSpec['id']]['rekName'] = isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "";
                    }


                }
            }
        }

        if (sizeof($_SESSION[$cCode]['items2_sum']) > 0) {
            foreach ($_SESSION[$cCode]['items2_sum'] as $bID => $pSpec) {
                $_SESSION[$cCode]['items2_sum'][$bID]['produk_ids'] = serialize(base64_encode($pSpec['produk_ids']));
            }
        }



        $_SESSION[$cCode]['main']['refs'] = base64_encode(serialize($_SESSION[$cCode]['main']['refIDs']));
        $_SESSION[$cCode]['main']['refs_intext'] = print_r($_SESSION[$cCode]['main']['refIDs'], true);


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

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

    }

    public function remove()
    {
        $id = $_GET['id'];
        $cCode = $this->cCode;
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();


        if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {
            cekBiru("melibatkan session");
            if (isset($_SESSION[$cCode]['items'][$id])) {
                cekBiru("ada barang, cek lokernya");
                $this->db->trans_start();

                $mdlName = $lockerConfig['mdlName'];
                $this->load->model("Mdls/" . $mdlName);

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


                $c = new $mdlName();
                $array_active_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "active");
                $where = array(
                    "id" => $array_active_sebelumnya['id'],
                );
                $data_active = array(
                    "jumlah" => $array_active_sebelumnya['jumlah'] + $array_hold_sebelumnya['jumlah'],
                );
                $c->updateData($where, $data_active);


                $this->db->trans_complete() or die("Gagal bro");
            } else {
                cekBiru("TIDAK ada barang, ga jadi cek loker");
            }
        } else {
            cekBiru("TIDAK melibatkan session");
        }

//        die();
        if (isset($_SESSION[$cCode]['items'][$id])) {
            $_SESSION[$cCode]['items'][$id] = null;
            unset($_SESSION[$cCode]['items'][$id]);
        }
//        if (sizeof($_SESSION[$cCode]['items']) < 1) {
//            $_SESSION[$cCode] = null;
//            unset($_SESSION[$cCode]);
//        }

        if (isset($_SESSION[$cCode]['main']['refIDs'][$id])) {
            $_SESSION[$cCode]['main']['refIDs'][$id] = null;
            unset($_SESSION[$cCode]['main']['refIDs'][$id]);
        }


        $_SESSION[$cCode]['main']['refs'] = base64_encode(serialize($_SESSION[$cCode]['main']['refIDs']));
        $_SESSION[$cCode]['main']['refs_intext'] = print_r($_SESSION[$cCode]['main']['refIDs'], true);


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

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

    public function updateValues()
    {
        $cCode = "_TR_" . $this->jenisTr;
        die("updating.............................. (will be available sooner or later)");
        $rawParam = $_GET['param'];
        $param = unserialize(base64_decode($rawParam));
        if (is_array($param) && sizeof($param) > 0) {

        }
    }

    //-------------------------------------------
    public function selectSettlement()
    {
        // $this->jenisTr = $this->uri->segment(4);
        $cCode = $this->cCode;
        //        $id = $_GET['transaksi_id'];

        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $componentAssConfig = isset($this->configUi[$this->jenisTr]['componentsAss']) ? $this->configUi[$this->jenisTr]['componentsAss'] : array();
        $relativeComNameDetails = isset($this->configUi[$this->jenisTr]['relativeComNameDetails']) ? $this->configUi[$this->jenisTr]['relativeComNameDetails'] : array();
        $isRadioSelect = isset($this->configUi[$this->jenisTr]['isPaymentRadioSelect']) ? $this->configUi[$this->jenisTr]['isPaymentRadioSelect'] : false;
        $trLabel = isset($this->configUi[$this->jenisTr]['label']) ? $this->configUi[$this->jenisTr]['label'] : "";
        $selectedProductFields =isset($this->configUi[$this->jenisTr]['settlementProduk']) ? $this->configUi[$this->jenisTr]['settlementProduk'] : array();
        if (in_array($this->jenisTr, $this->validateJenisTr)) {
            if (isset($_GET['extern_label2']) && ($_GET['extern_label2'] == null)) {
                die(lgShowAlert("$trLabel gagal dilanjutkan, karena jenis biaya tidak ditentukan saat request $trLabel."));
            }
        }

        //        arrPrintPink($_GET);
        //mati_disini("test...");

        if ($isRadioSelect) {
            $detailResetList = array(
                "items",

                "items2_sum",
                "items3_sum",
                "items4_sum",
                "items5_sum",

                "tableIn_detail",
                "tableIn_detail2",
                "tableIn_detail_values",
                "tableIn_detail2_sum",
                "tableIn_detail_values2_sum",
                "tableIn_detail3_sum",
                "tableIn_detail_values3_sum",
                "tableIn_detail4_sum",
                "tableIn_detail_values4_sum",
            );
            foreach ($detailResetList as $sSName) {
                $_SESSION[$cCode][$sSName] = null;
                unset($_SESSION[$cCode][$sSName]);
            }

            $_SESSION[$cCode]['main']['refIDs'] = null;
            unset($_SESSION[$cCode]['main']['refIDs']);

            if (sizeof($_SESSION[$cCode]['items']) > 0) {

            }
            else {
                $mainValueInjector = isset($this->configUi[$this->jenisTr]['mainValueInjectors']) ? $this->configUi[$this->jenisTr]['mainValueInjectors'] : array();
                if (sizeof($mainValueInjector) > 0) {
                    foreach ($mainValueInjector as $key => $val) {
                        $_SESSION[$cCode]['main'][$val] = null;
                        unset($_SESSION[$cCode]['main'][$val]);
                    }
                }
            }

            if (isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = null;
                unset($_SESSION[$cCode]['items2']);
            }

        }

        $initMain = array(
            "pihakID" => $_GET['extern_id'],
            "pihakName" => $_GET['extern_nama'],
            "valasDetails" => $_GET['valas_id'],
            "pihakMainName" => isset($_GET['extern_label2']) && sizeof($_GET['extern_label2']) > 0 ? $_GET['extern_label2'] : "",
            "other" => isset($_GET['extern_nilai4']) && sizeof($_GET['extern_nilai4']) > 0 ? $_GET['extern_nilai4'] : "",
            "relativeComName" => sizeof($relativeComNameDetails) > 0 ? $relativeComNameDetails[$_GET['extern_label2']] : "",
            "pph_23" => isset($_GET['pph_23']) ? $_GET['pph_23'] : 0,
            "terbayar_pph23" => isset($_GET['terbayar_pph23']) ? $_GET['terbayar_pph23'] : 0,
            "pphGate" => isset($_GET['extern_jenis']) && sizeof($_GET['extern_jenis']) > 0 ? $_GET['extern_jenis'] : "",
            "pphGateLabel" => isset($_GET['extern2_nama']) && sizeof($_GET['extern2_nama']) > 0 ? $_GET['extern2_nama'] : "",
            "pairPihakName" => isset($_GET['extern2_nama']) && sizeof($_GET['extern2_nama']) > 0 ? $_GET['extern2_nama'] : "",
            "pairPihakID" => isset($_GET['extern2_id']) && sizeof($_GET['extern2_id']) > 0 ? $_GET['extern2_id'] : "",
            "pphGateId" => isset($_GET['extern2_id']) && sizeof($_GET['extern2_id']) > 0 ? $_GET['extern2_id'] : "",

        );
        foreach ($initMain as $key => $src) {
            $_SESSION[$cCode]['main'][$key] = $src;
        }
        $row = $_GET;

        // arrPrint($_GET);
        $bahanIDs = array();

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

        $id = $_GET['id'];
//        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
//        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
//        $componentAssConfig = isset($this->configUi[$this->jenisTr]['componentsAss']) ? $this->configUi[$this->jenisTr]['componentsAss'] : array();
        $clonerGate = isset($this->configValues[$this->jenisTr]['cloningGate'][1]['kolom']) ? $this->configValues[$this->jenisTr]['cloningGate'][1]['kolom'] : array();
        $settlementInjectItems = isset($this->configUi[$this->jenisTr]['settlementInjectItems']) ? $this->configUi[$this->jenisTr]['settlementInjectItems'] : array();

        //-----------------------------------------------
        unset($_SESSION[$cCode]);
        // matiHere();
        if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
            //            cekMerah("akan memasukkan ITEMS");


            //region build gerbang ITEMS, sesuai yang diklik
            $tmp = array(
                "handler" => $this->uri->segment(1),
                "id" => $id,
                "refID" => $id,
                "jml" => 1,
                "harga" => 0,
                "satuan" => "-",
                "subtotal" => 0,
                //                "nama" => 0,
                //                "nomer" => 0,
            );

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

            if ($subAmountConfig != null) {
                $subtotal = makeValue($subAmountConfig, $row, $row, 0);
                $tmp["subtotal"] = $subtotal;
            }
            else {
                $tmp["subtotal"] = 0;
            }

            $_SESSION[$cCode]['items'][$id] = $tmp;
            //endregion


            //---membaca payment source
            $this->load->model("MdlTransaksi");
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $pymTmp = $tr->lookupPaymentSrcByID($id)->result();
            // showLast_query("biru");
            if (sizeof($pymTmp) > 0) {
                $unsetList = array(
                    "stepCode","jenisTrMaster","jenisTr","jenisTrMaster","jenisTrTop","jenisTrName","stepNumber"
                );
                $akumulasiBahanTotal = array();
                $akumulasiBahanTransaksi = array();
                $externValueBlobDecode = isset($pymTmp[0]->externValueBlob) ? blobDecode($pymTmp[0]->externValueBlob) : array();
//                 arrPrintPink($externValueBlobDecode);
//                 matiHEre();
                foreach ($externValueBlobDecode as $mode => $spec) {
                                       // cekHitam(":: $mode ::");
                    // arrPrintPink($spec);
                    // matiHEre();
                    switch ($mode) {
                        // membuat gerbang ITEMS2_SUM... TRANSAKSI PENJUALAN & ...
                        case "items":
                            foreach ($spec as $trNomer => $dataSpec) {
                                $idTrans= $dataSpec->nomor;
                                if (!isset($_SESSION[$cCode]['items2_sum'][$idTrans])) {
                                    $_SESSION[$cCode]['items2_sum'][$idTrans] = array();
                                }
                                $prevdataSpec = (array)$dataSpec;
                                // arrPrint($prevdataSpec);
                                foreach($unsetList as $ix =>$listunseted){
                                    unset($prevdataSpec[$listunseted]);
                                }
                                $_SESSION[$cCode]['items2_sum'][$idTrans] = $prevdataSpec + array("id"=>$dataSpec->transaksi_id);

                                // -----TRANSAKSI DATA---------------------------
                                if (!isset($_SESSION[$cCode]['items5_sum'][$idTrans])) {
                                    $_SESSION[$cCode]['items5_sum'][$idTrans] = array();
                                }
                                $itemsTrans = json_decode(base64_decode($dataSpec->produk),true);
                                // arrPrint($itemsTrans);
                                // matiHEre();
                                $_SESSION[$cCode]['items5_sum'][$idTrans] = $itemsTrans;


                                //region builkan berdasarkan payment nya
                                /*
                                 * paymentMethode[akun][nilai]+=nilai_transaksi
                                 * paymentMethode[akun][label]=label akun bank
                                 */
                                if(!isset($_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["harga"])){
                                    $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["harga"] =0;
                                }

                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["harga"] +=$dataSpec->grand_total;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["cash_account"] = $dataSpec->cash_account;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["cash_account__nama"] = $dataSpec->cash_account__label;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["toko_id"]=$dataSpec->tokoID;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["toko_nama"]=$dataSpec->tokoNama;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["cabang_id"]=$dataSpec->cabangID;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["gudang_id"]=$dataSpec->gudangID;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["cabang_nama"]=$dataSpec->cabangName;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["oleh_id"]=$dataSpec->olehID;
                                $_SESSION[$cCode]['items7_sum'][$dataSpec->paymentMethod_cash]["oleh_nama"]=$dataSpec->olehName;

                                //endregion

                                //-----KOMPOSISI DATA---------------------------
                                $komposisiByTransaksi = array();
                                // if(isset($dataSpec["komposisi"]) && sizeof($dataSpec["komposisi"])>0){
                                //     foreach ($dataSpec["komposisi"] as $pID => $kSpec){
                                //         if (!isset($_SESSION[$cCode]['items8_sum'][$trNomer][$pID])) {
                                //             $_SESSION[$cCode]['items8_sum'][$trNomer][$pID] = array();
                                //         }
                                //         $_SESSION[$cCode]['items8_sum'][$trNomer][$pID] = isset($kSpec['komposisi']) ? $kSpec['komposisi'] : array();
                                //
                                //
                                //
                                //
                                //         //---untuk checking komposisi dan akumulasi bahan, tidak amsuk session------------------------
                                //         $produkID = $pID;
                                //         $produkQty = $kSpec['produk_jadi']['produk_qty'];
                                //         foreach ($kSpec['komposisi'] as $specKomposisi){
                                //             $specKomposisi['jml_penggunaan_bahan'] = $specKomposisi['jml'] * $produkQty;
                                //             $specKomposisi['jml_produk_jadi'] = $produkQty;
                                //             $komposisiByTransaksi[$trNomer][$pID][] = $specKomposisi;
                                //             //-----
                                //             if(!isset($akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']])){
                                //                 $akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']]['nama_bahan'] = $specKomposisi['produk_dasar_nama'];
                                //                 $akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']]['jml_bahan'] = 0;
                                //             }
                                //             $akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']]['jml_bahan'] += $specKomposisi['jml'] * $produkQty;
                                //             //-----
                                //             if(!isset($akumulasiBahanTotal[$specKomposisi['produk_dasar_id']])){
                                //                 $akumulasiBahanTotal[$specKomposisi['produk_dasar_id']]['nama_bahan'] = $specKomposisi['produk_dasar_nama'];
                                //                 $akumulasiBahanTotal[$specKomposisi['produk_dasar_id']]['jml_bahan'] = 0;
                                //             }
                                //             $akumulasiBahanTotal[$specKomposisi['produk_dasar_id']]['jml_bahan'] += $specKomposisi['jml'] * $produkQty;
                                //             //-----
                                //
                                //
                                //
                                //         }
                                //         //-------------------------------
                                //     }
                                // }

                                //-----AKUMULASI BAHAN DIPAKAI PER-TRANSAKSI---------------------------
                                // if(isset($dataSpec["sum_komposisi"]) && sizeof($dataSpec["sum_komposisi"])>0){
                                //     foreach ($dataSpec["sum_komposisi"] as $bID => $bSpec){
                                //         $bSpec['id_bahan'] = $bID;
                                //         $bSpec['qty'] = $bSpec['total_penggunaan_bahan'];
                                //         $bSpec['jml'] = $bSpec['total_penggunaan_bahan'];
                                //
                                //         $bahanIDs[$bID] = $bID;
                                //
                                //         if(sizeof($clonerGate)>0){
                                //             foreach ($clonerGate as $c_key => $c_val){
                                //                 $bSpec[$c_key] = isset($dataSpec["transaksi"][$c_val]) ? $dataSpec["transaksi"][$c_val] : "";
                                //             }
                                //         }
                                //         if(!isset($_SESSION[$cCode]['items4_sum'][$trNomer][$bID])){
                                //             $_SESSION[$cCode]['items4_sum'][$trNomer][$bID] = array();
                                //         }
                                //         $_SESSION[$cCode]['items4_sum'][$trNomer][$bID] = $bSpec;
                                //
                                //
                                //         //---AKUMULASI BAHAN PER-SETTLEMENT----------------
                                //         if(!isset($_SESSION[$cCode]['items9_sum'][$bID])){
                                //             $_SESSION[$cCode]['items9_sum'][$bID] = $bSpec;
                                //             $_SESSION[$cCode]['items9_sum'][$bID]['total_penggunaan_bahan'] = 0;
                                //         }
                                //         $_SESSION[$cCode]['items9_sum'][$bID]['total_penggunaan_bahan'] += $bSpec['total_penggunaan_bahan'];
                                //         $_SESSION[$cCode]['items9_sum'][$bID]['jml'] += $bSpec['total_penggunaan_bahan'];
                                //         $_SESSION[$cCode]['items9_sum'][$bID]['qty'] += $bSpec['total_penggunaan_bahan'];
                                //     }
                                // }

                            }
                            break;
                        // membuat gerbang ITEMS3_SUM... AKUMULASI MENU
                        case "settlementDetails":
                            // $_SESSION[$cCode]['items3_sum'] = $spec;
                            break;
                        // membuat gerbang ITEMS4_SUM... AKUMULASI BAHAN
                        //                        case "settlementByBahan":
                        //                            $_SESSION[$cCode]['items4_sum'] = $spec;
                        //                            break;
                        // membuat gerbang items3_sum by transaksi->produk
                        case "trData":
                            // arrPrint($spec);
                            foreach ($spec as $trNomer => $dataSpec){
                                // arrPrint($dataSpec);
                                // matiHEre();
                                if(!isset($_SESSION[$cCode]['items3_sum'][$dataSpec->nomor][$dataSpec->produk_id])){
                                    $_SESSION[$cCode]['items3_sum'][$dataSpec->nomor][$dataSpec->produk_id]=array();
                                }
                                foreach($selectedProductFields as $key =>$keySrc){
                                    $_SESSION[$cCode]['items3_sum'][$dataSpec->nomor][$dataSpec->produk_id][$key]= isset($dataSpec->$keySrc) ? $dataSpec->$keySrc :"";
                                }

                                // $_SESSION[$cCode]['items3_sum'][$dataSpec->produk_id]=array();
                                // arrPrint($dataSpec);
                                // matiHEre();
                            }
                            // matiHEre();
                            // $_SESSION[$cCode]['items3_sum'] = $spec;
                            break;
                        //items6_sum,
                        case "sumProduk":
                            // arrPrintWebs($spec);
                            // matiHere();
                            $_SESSION[$cCode]['items6_sum']=$spec;
                            $_SESSION[$cCode]['items9_sum']=$spec;
                            foreach($spec as $bID =>$bidData){
                                $bahanIDs[$bID] = $bID;
                            }

                            break;
                        // membuat gerbang items7_sum by payment
                        case "settlementByPayment":
                            // $_SESSION[$cCode]['items7_sum'] = $spec;
                            break;
                        //                        case "komposisi":
                        ////                            $_SESSION[$cCode]['items8_sum'] = $spec;
                        ////                            arrPrintPink($spec);
                        //                            break;
                    }
                }
            }
        }
        else {
            cekMerah("TIDAK akan memasukkan ITEMS");
        }
//         arrPrint($_SESSION[$cCode]['items3_sum']);
// matiHere();

        $_SESSION[$cCode]['main']['refIDs'][$id] = $id;

        switch ($_GET['state']) {
            case "true":
                if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $_SESSION[$cCode]['items'][$id] = $tmp;
                }
                if (sizeof($componentAssConfig) > 0) {
                    if (!array_key_exists($id, $_SESSION[$cCode]['items2'])) {
                        $_SESSION[$cCode]['items2'][$id] = $itemsRegistries;
                    }
                }
                break;
            case "false":
                if (array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $detailResetList = array(
                        "items",
                        "tableIn_detail",
                        "tableIn_detail2",
                        "tableIn_detail_values",
                        "tableIn_detail2_sum",
                        "tableIn_detail_values2_sum",
                        "tableIn_detail3_sum",
                        "tableIn_detail_values3_sum",
                    );
                    foreach ($detailResetList as $sSName) {
                        $_SESSION[$cCode][$sSName][$id] = null;
                        unset($_SESSION[$cCode][$sSName][$id]);
                    }
                }
                if (isset($_SESSION[$cCode]['main']['refIDs'][$id])) {
                    $_SESSION[$cCode]['main']['refIDs'][$id] = null;
                    unset($_SESSION[$cCode]['main']['refIDs'][$id]);
                }
                if (sizeof($_SESSION[$cCode]['items']) > 0) {

                }
                else {
                    $mainValueInjector = isset($this->configUi[$this->jenisTr]['mainValueInjectors']) ? $this->configUi[$this->jenisTr]['mainValueInjectors'] : array();
                    if (sizeof($mainValueInjector) > 0) {
                        foreach ($mainValueInjector as $key => $val) {
                            $_SESSION[$cCode]['main'][$val] = null;
                            unset($_SESSION[$cCode]['main'][$val]);
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['items2'][$id])) {
                    $_SESSION[$cCode]['items2'][$id] = null;
                    unset($_SESSION[$cCode]['items2'][$id]);
                }
                break;
        }

        // matiHere();
        //-------------------------------------
        $bahanRekening = array();
        if(sizeof($bahanIDs)>0){
            $this->load->model("Mdls/MdlLockerStock");
            $cm = New MdlLockerStock();
            $cm->setFilters(array());
            $cm->addFilter("produk_id in ('" . implode("','", $bahanIDs) . "')");
            $cm->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
            $cm->addFilter("state='active'");
            $cmTmp = $cm->lookUpAll()->result();
            // showLast_query("biru");
            // arrPrint($cmTmp);
            if(sizeof($cmTmp)>0){
                foreach ($cmTmp as $cmSpec){
                    $bahanRekening[$cmSpec->produk_id] = $cmSpec->jumlah;
                }
            }
        }
        // arrPrint($bahanIDs);
        // matiHEre(__LINE__);
        // //--pairing ke items9_sum-----------------------------------
        // if(sizeof($_SESSION[$cCode]['items9_sum'])>0){
        //     $dataKekuranganProduk = array();
        //     foreach ($_SESSION[$cCode]['items9_sum'] as $bID => $bSpec){
        //         $qty_dipakai = isset($bSpec['qty']) ? $bSpec['qty'] : 0;
        //         // $qty_stok = isset($bahanRekening[$bID]) ? $bahanRekening[$bID] + $qty_dipakai : 0;
        //         $qty_stok = isset($bahanRekening[$bID]) ? $bahanRekening[$bID]  : 0;
        //         // $qty_kekurangan =  0;
        //         $qty_kekurangan =  ($bahanRekening[$bID] - $qty_dipakai) > 0 ? 0: ($bahanRekening[$bID] - $qty_dipakai) * -1;
        //         $saldo = $bahanRekening[$bID]-$qty_dipakai;
        //
        //         $_SESSION[$cCode]['items9_sum'][$bID]['qty_stok'] = $qty_stok;
        //         $_SESSION[$cCode]['items9_sum'][$bID]['qty_kekurangan'] = $qty_kekurangan;
        //         $_SESSION[$cCode]['items9_sum'][$bID]['qty_saldo'] = $saldo;
        //         if($qty_kekurangan>0){
        //             $_SESSION[$cCode]['items9_sum'][$bID]['class_css']="text-red text-bold";
        //             $_SESSION[$cCode]['items9_sum'][$bID]['btn_label']="klik disini untuk menambah stok";
        //
        //             $dataKekuranganProduk[$bID]=array(
        //                 "jml"=>$qty_kekurangan,
        //             );
        //         }
        //         else{
        //             $_SESSION[$cCode]['items9_sum'][$bID]['class_css']="";
        //         }
        //         if(sizeof($settlementInjectItems["items9_sum"])>0){
        //             foreach($settlementInjectItems["items9_sum"] as $i =>$keyToinject){
        //                 $_SESSION[$cCode]['items9_sum'][$bID][$keyToinject]=$_SESSION[$cCode]["main"][$keyToinject];
        //             }
        //         }
        //         else{
        //             arrprint($settlementInjectItems);
        //         }
        //     }
        //     //injector data dari main
        //     // arrPrint($_SESSION[$cCode]["items9_sum"]);
        //     // matiHEre();
        //
        //
        //     if(sizeof($dataKekuranganProduk)>0){
        //         $multi_produk=blobEncode($dataKekuranganProduk);
        //         $_SESSION[$cCode]['items10_sum']['btn_Label']= "input stok";
        //         $_SESSION[$cCode]['items10_sum']['btn_link']= base_url()."pembelian/_processSelectProduct/selectSettlement/466?multi=$multi_produk";
        //     }else{
        //         unset($_SESSION[$cCode]['items10_sum']);
        //     }
        // }
// arrPrint($_SESSION[$cCode]['main']);
// arrPrint($_SESSION[$cCode]['items9_sum']);
//         matiHEre();
        // region menuju ValueGate untuk rebuild gerbang nilai
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        // $configUiJenis = $this->configUi[$this->jenisTr];
        // $configCoreJenis = $this->configCore[$this->jenisTr];
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor(my_ppn_factor());
        $initMasterValues = array(
            "olehID"        => my_id(),
            "olehName"      => my_name(),
            "placeID"       => my_cabang_id(),
            "placeName"     => my_cabang_nama(),
            "divID"         => my_div_id(),
            "divName"       => my_div_nama(),
            "cabangID"      => my_cabang_id(),
            "cabangName"    => my_cabang_nama(),
            "gudangID"      => my_gudang_id(),
            "gudangName"    => my_gudang_nama(),
            "jenis_usaha"   => my_jenis_usaha(),
            "tokoID"        => my_toko_id(),
            "tokoNama"      => my_toko_nama(),
            "jenisTr"       => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop"    => $this->configUiJenis['steps'][1]['target'],
            "jenisTrName"   => $this->configUiJenis['steps'][1]['label'],
            "stepNumber"    => 1,
            "stepCode"      => $this->configUiJenis['steps'][1]['target'],
            "dtime"         => dtimeNow(),
            "fulldate"      => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        // arrPrint($initMasterValues);
        // matiHEre();
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);
        // endregion menuju ValueGate untuk rebuild gerbang nilai

        //--pairing ke items9_sum-----------------------------------
        if(sizeof($_SESSION[$cCode]['items9_sum'])>0){
            $dataKekuranganProduk = array();
            foreach ($_SESSION[$cCode]['items9_sum'] as $bID => $bSpec){
                $qty_dipakai = isset($bSpec['qty']) ? $bSpec['qty'] : 0;
                // $qty_stok = isset($bahanRekening[$bID]) ? $bahanRekening[$bID] + $qty_dipakai : 0;
                $qty_stok = isset($bahanRekening[$bID]) ? $bahanRekening[$bID]  : 0;
                // $qty_kekurangan =  0;
                $qty_kekurangan =  ($bahanRekening[$bID] - $qty_dipakai) > 0 ? 0: ($bahanRekening[$bID] - $qty_dipakai) * -1;
                $saldo = $bahanRekening[$bID]-$qty_dipakai;

                $_SESSION[$cCode]['items9_sum'][$bID]['qty_stok'] = $qty_stok;
                $_SESSION[$cCode]['items9_sum'][$bID]['qty_kekurangan'] = $qty_kekurangan;
                $_SESSION[$cCode]['items9_sum'][$bID]['qty_saldo'] = $saldo;
                if($qty_kekurangan>0){
                    $_SESSION[$cCode]['items9_sum'][$bID]['class_css']="text-red text-bold";
                    $_SESSION[$cCode]['items9_sum'][$bID]['btn_label']="klik disini untuk menambah stok";
                    $dataKekuranganProduk[$bID]=array(
                        "jml"=>$qty_kekurangan,
                    );
                }
                else{
                    $_SESSION[$cCode]['items9_sum'][$bID]['class_css']="";
                }
                if(sizeof($settlementInjectItems["items9_sum"])>0){
                    foreach($settlementInjectItems["items9_sum"] as $i =>$keyToinject){
                        $_SESSION[$cCode]['items9_sum'][$bID][$keyToinject]=$_SESSION[$cCode]["main"][$keyToinject];
                    }
                }
                else{
                    arrprint($settlementInjectItems);
                }
            }
            //injector data dari main
            // arrPrint($_SESSION[$cCode]["items9_sum"]);
            // matiHEre();

            if(sizeof($dataKekuranganProduk)>0){
                $multi_produk=blobEncode($dataKekuranganProduk);
                $_SESSION[$cCode]['items10_sum']['btn_Label']= "input stok(opname)";
                $_SESSION[$cCode]['items10_sum']['btn_LabelVendor']= "order stok";
                // $_SESSION[$cCode]['items10_sum']['btn_link']= base_url()."pembelian/_processSelectProduct/selectSettlement/466?multi=$multi_produk";//tanpa vendor
                $_SESSION[$cCode]['items10_sum']['btn_link_vendor']= base_url()."pembelian/_processSelectProduct/selectSettlement/466?multi=$multi_produk";//tanpa vendor
                $_SESSION[$cCode]['items10_sum']['btn_link']= base_url()."opname/_processSelectProduct/selectSettlement/1119?multi=$multi_produk";

                // arrPrint($dataKekuranganProduk);
                $this->load->model("Mdls/MdlProdukPerSupplier");
                $s = new MdlProdukPerSupplier();
                $listProds = array_keys($dataKekuranganProduk);
                $tempSupplier = $s->callProdukSupplier($listProds);
                $supplierData = array();
                $produklRelasiSupplier = array();
                foreach($tempSupplier as $pid =>$dataPID){
                    foreach($dataPID as $pid2 =>$tmpSupplierData){
                        $supplierData[$tmpSupplierData['supplier_id']] =$tmpSupplierData['supplier_nama'];
                        $produklRelasiSupplier[$tmpSupplierData['supplier_id']][$pid] =array(
                            "jml"=>$dataKekuranganProduk[$pid]['jml'],
                        );
                    }
                }


                $_SESSION[$cCode]['items10_sum']["supplier"]=$supplierData;
                $_SESSION[$cCode]['items10_sum']["supplier_produk"]=$produklRelasiSupplier;
                $_SESSION[$cCode]['items10_sum']["produk"]=$dataKekuranganProduk;
                // $_SESSION[$cCode]['items10_sum']['btn_link']= base_url()."pembelian/_processSelectProduct/selectSettlement/466?multi=$multi_produk";//tanpa vendor
                $_SESSION[$cCode]['items10_sum']['btn_link_vendor']= base_url()."pembelian/_processSelectProduct/selectSettlement/466?multi=$multi_produk";//tanpa vendor
                $_SESSION[$cCode]['items10_sum']['btn_link']= base_url()."opname/_processSelectProduct/selectSettlement/1119?multi=$multi_produk";


                // ceklIme($this->db->last_query());
                //
                // arrprint($tempSupplier);
                // arrprint($produklRelasiSupplier);
                // matiHEre(__LINE__."".__FUNCTION__);
            }else{
                unset($_SESSION[$cCode]['items10_sum']);
            }
        }
// matiHEre();
        echo "<script>";
        echo "  if(top.document.getElementById('shopping_cart')){";
        echo "  top.$('#shopping_cart').load('" . base_url() . $this->modul . "/_shoppingCart/viewCart/" . $this->jenisTr . "?selID=$id');";
        echo "  }";
        echo "</script>";

    }

    public function selectSettlementOLD()
    {
        // $this->jenisTr = $this->uri->segment(4);
        $cCode = $this->cCode;
        //        $id = $_GET['transaksi_id'];

        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $componentAssConfig = isset($this->configUi[$this->jenisTr]['componentsAss']) ? $this->configUi[$this->jenisTr]['componentsAss'] : array();
        $relativeComNameDetails = isset($this->configUi[$this->jenisTr]['relativeComNameDetails']) ? $this->configUi[$this->jenisTr]['relativeComNameDetails'] : array();
        $isRadioSelect = isset($this->configUi[$this->jenisTr]['isPaymentRadioSelect']) ? $this->configUi[$this->jenisTr]['isPaymentRadioSelect'] : false;
        $trLabel = isset($this->configUi[$this->jenisTr]['label']) ? $this->configUi[$this->jenisTr]['label'] : "";

        if (in_array($this->jenisTr, $this->validateJenisTr)) {
            if (isset($_GET['extern_label2']) && ($_GET['extern_label2'] == null)) {
                die(lgShowAlert("$trLabel gagal dilanjutkan, karena jenis biaya tidak ditentukan saat request $trLabel."));
            }
        }

        //        arrPrintPink($_GET);
        //mati_disini("test...");

        if ($isRadioSelect) {
            $detailResetList = array(
                "items",

                "items2_sum",
                "items3_sum",
                "items4_sum",
                "items5_sum",

                "tableIn_detail",
                "tableIn_detail2",
                "tableIn_detail_values",
                "tableIn_detail2_sum",
                "tableIn_detail_values2_sum",
                "tableIn_detail3_sum",
                "tableIn_detail_values3_sum",
                "tableIn_detail4_sum",
                "tableIn_detail_values4_sum",
            );
            foreach ($detailResetList as $sSName) {
                $_SESSION[$cCode][$sSName] = null;
                unset($_SESSION[$cCode][$sSName]);
            }

            $_SESSION[$cCode]['main']['refIDs'] = null;
            unset($_SESSION[$cCode]['main']['refIDs']);

            if (sizeof($_SESSION[$cCode]['items']) > 0) {

            }
            else {
                $mainValueInjector = isset($this->configUi[$this->jenisTr]['mainValueInjectors']) ? $this->configUi[$this->jenisTr]['mainValueInjectors'] : array();
                if (sizeof($mainValueInjector) > 0) {
                    foreach ($mainValueInjector as $key => $val) {
                        $_SESSION[$cCode]['main'][$val] = null;
                        unset($_SESSION[$cCode]['main'][$val]);
                    }
                }
            }

            if (isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = null;
                unset($_SESSION[$cCode]['items2']);
            }

        }

        $initMain = array(
            "pihakID" => $_GET['extern_id'],
            "pihakName" => $_GET['extern_nama'],
            "valasDetails" => $_GET['valas_id'],
            "pihakMainName" => isset($_GET['extern_label2']) && sizeof($_GET['extern_label2']) > 0 ? $_GET['extern_label2'] : "",
            "other" => isset($_GET['extern_nilai4']) && sizeof($_GET['extern_nilai4']) > 0 ? $_GET['extern_nilai4'] : "",
            "relativeComName" => sizeof($relativeComNameDetails) > 0 ? $relativeComNameDetails[$_GET['extern_label2']] : "",
            "pph_23" => isset($_GET['pph_23']) ? $_GET['pph_23'] : 0,
            "terbayar_pph23" => isset($_GET['terbayar_pph23']) ? $_GET['terbayar_pph23'] : 0,
            "pphGate" => isset($_GET['extern_jenis']) && sizeof($_GET['extern_jenis']) > 0 ? $_GET['extern_jenis'] : "",
            "pphGateLabel" => isset($_GET['extern2_nama']) && sizeof($_GET['extern2_nama']) > 0 ? $_GET['extern2_nama'] : "",
            "pairPihakName" => isset($_GET['extern2_nama']) && sizeof($_GET['extern2_nama']) > 0 ? $_GET['extern2_nama'] : "",
            "pairPihakID" => isset($_GET['extern2_id']) && sizeof($_GET['extern2_id']) > 0 ? $_GET['extern2_id'] : "",
            "pphGateId" => isset($_GET['extern2_id']) && sizeof($_GET['extern2_id']) > 0 ? $_GET['extern2_id'] : "",

        );
        foreach ($initMain as $key => $src) {
            $_SESSION[$cCode]['main'][$key] = $src;
        }
        $row = $_GET;

        // arrPrint($_GET);
        $bahanIDs = array();

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

        $id = $_GET['id'];
        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $componentAssConfig = isset($this->configUi[$this->jenisTr]['componentsAss']) ? $this->configUi[$this->jenisTr]['componentsAss'] : array();
        $clonerGate = isset($this->configValues[$this->jenisTr]['cloningGate'][1]['kolom']) ? $this->configValues[$this->jenisTr]['cloningGate'][1]['kolom'] : array();

        //-----------------------------------------------
        $_SESSION[$cCode]['items'] = array();
        if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
            //            cekMerah("akan memasukkan ITEMS");


            //region build gerbang ITEMS, sesuai yang diklik
            $tmp = array(
                "handler" => $this->uri->segment(1),
                "id" => $id,
                "refID" => $id,
                "jml" => 1,
                "harga" => 0,
                "satuan" => "-",
                "subtotal" => 0,
                //                "nama" => 0,
                //                "nomer" => 0,
            );

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

            if ($subAmountConfig != null) {
                $subtotal = makeValue($subAmountConfig, $row, $row, 0);
                $tmp["subtotal"] = $subtotal;
            }
            else {
                $tmp["subtotal"] = 0;
            }

            $_SESSION[$cCode]['items'][$id] = $tmp;
            //endregion


            //---membaca payment source
            $this->load->model("MdlTransaksi");
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $pymTmp = $tr->lookupPaymentSrcByID($id)->result();
             showLast_query("biru");
            if (sizeof($pymTmp) > 0) {
                $akumulasiBahanTotal = array();
                $akumulasiBahanTransaksi = array();
                $externValueBlobDecode = isset($pymTmp[0]->externValueBlob) ? blobDecode($pymTmp[0]->externValueBlob) : array();

                arrPrintWebs($externValueBlobDecode);
                matiHEre();
                foreach ($externValueBlobDecode as $mode => $spec) {
                    //                    cekHitam(":: $mode ::");
                    //arrPrintPink($spec);
                    switch ($mode) {
                        // membuat gerbang ITEMS2_SUM... TRANSAKSI PENJUALAN & ...
                        case "settlementData":
                            //                            cekHitam(":: $mode ::");
                            //                            arrPrintWebs($spec);
                            //                            cekHitam("------");
                            foreach ($spec as $trNomer => $dataSpec) {
                                $data_id = $dataSpec["transaksi"]["id"];
                                //----TRANSAKSI------------------------------
                                if (!isset($_SESSION[$cCode]['items2_sum'][$trNomer])) {
                                    $_SESSION[$cCode]['items2_sum'][$trNomer] = array();
                                }
                                $_SESSION[$cCode]['items2_sum'][$trNomer] = $dataSpec["transaksi"];

                                //-----TRANSAKSI DATA---------------------------
                                if (!isset($_SESSION[$cCode]['items5_sum'][$trNomer])) {
                                    $_SESSION[$cCode]['items5_sum'][$trNomer] = array();
                                }
                                $_SESSION[$cCode]['items5_sum'][$trNomer] = $dataSpec["produk"];

                                //-----KOMPOSISI DATA---------------------------
                                $komposisiByTransaksi = array();
                                if(isset($dataSpec["komposisi"]) && sizeof($dataSpec["komposisi"])>0){
                                    foreach ($dataSpec["komposisi"] as $pID => $kSpec){
                                        if (!isset($_SESSION[$cCode]['items8_sum'][$trNomer][$pID])) {
                                            $_SESSION[$cCode]['items8_sum'][$trNomer][$pID] = array();
                                        }
                                        $_SESSION[$cCode]['items8_sum'][$trNomer][$pID] = isset($kSpec['komposisi']) ? $kSpec['komposisi'] : array();




                                        //---untuk checking komposisi dan akumulasi bahan, tidak amsuk session------------------------
                                        $produkID = $pID;
                                        $produkQty = $kSpec['produk_jadi']['produk_qty'];
                                        foreach ($kSpec['komposisi'] as $specKomposisi){
                                            $specKomposisi['jml_penggunaan_bahan'] = $specKomposisi['jml'] * $produkQty;
                                            $specKomposisi['jml_produk_jadi'] = $produkQty;
                                            $komposisiByTransaksi[$trNomer][$pID][] = $specKomposisi;
                                            //-----
                                            if(!isset($akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']])){
                                                $akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']]['nama_bahan'] = $specKomposisi['produk_dasar_nama'];
                                                $akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']]['jml_bahan'] = 0;
                                            }
                                            $akumulasiBahanTransaksi[$trNomer][$specKomposisi['produk_dasar_id']]['jml_bahan'] += $specKomposisi['jml'] * $produkQty;
                                            //-----
                                            if(!isset($akumulasiBahanTotal[$specKomposisi['produk_dasar_id']])){
                                                $akumulasiBahanTotal[$specKomposisi['produk_dasar_id']]['nama_bahan'] = $specKomposisi['produk_dasar_nama'];
                                                $akumulasiBahanTotal[$specKomposisi['produk_dasar_id']]['jml_bahan'] = 0;
                                            }
                                            $akumulasiBahanTotal[$specKomposisi['produk_dasar_id']]['jml_bahan'] += $specKomposisi['jml'] * $produkQty;
                                            //-----



                                        }
                                        //-------------------------------
                                    }
                                }

                                //-----AKUMULASI BAHAN DIPAKAI PER-TRANSAKSI---------------------------
                                if(isset($dataSpec["sum_komposisi"]) && sizeof($dataSpec["sum_komposisi"])>0){
                                    foreach ($dataSpec["sum_komposisi"] as $bID => $bSpec){
                                        $bSpec['id_bahan'] = $bID;
                                        $bSpec['qty'] = $bSpec['total_penggunaan_bahan'];
                                        $bSpec['jml'] = $bSpec['total_penggunaan_bahan'];

                                        $bahanIDs[$bID] = $bID;

                                        if(sizeof($clonerGate)>0){
                                            foreach ($clonerGate as $c_key => $c_val){
                                                $bSpec[$c_key] = isset($dataSpec["transaksi"][$c_val]) ? $dataSpec["transaksi"][$c_val] : "";
                                            }
                                        }
                                        if(!isset($_SESSION[$cCode]['items4_sum'][$trNomer][$bID])){
                                            $_SESSION[$cCode]['items4_sum'][$trNomer][$bID] = array();
                                        }
                                        $_SESSION[$cCode]['items4_sum'][$trNomer][$bID] = $bSpec;


                                        //---AKUMULASI BAHAN PER-SETTLEMENT----------------
                                        if(!isset($_SESSION[$cCode]['items9_sum'][$bID])){
                                            $_SESSION[$cCode]['items9_sum'][$bID] = $bSpec;
                                            $_SESSION[$cCode]['items9_sum'][$bID]['total_penggunaan_bahan'] = 0;
                                        }
                                        $_SESSION[$cCode]['items9_sum'][$bID]['total_penggunaan_bahan'] += $bSpec['total_penggunaan_bahan'];
                                        $_SESSION[$cCode]['items9_sum'][$bID]['jml'] += $bSpec['total_penggunaan_bahan'];
                                        $_SESSION[$cCode]['items9_sum'][$bID]['qty'] += $bSpec['total_penggunaan_bahan'];
                                    }
                                }

                            }
                            break;
                        // membuat gerbang ITEMS3_SUM... AKUMULASI MENU
                        case "settlementDetails":
                            $_SESSION[$cCode]['items3_sum'] = $spec;
                            break;
                        // membuat gerbang ITEMS4_SUM... AKUMULASI BAHAN
                        //                        case "settlementByBahan":
                        //                            $_SESSION[$cCode]['items4_sum'] = $spec;
                        //                            break;
                        // membuat gerbang items6_sum by menu
                        case "settlementByMenu":
                            $_SESSION[$cCode]['items6_sum'] = $spec;
                            break;
                        // membuat gerbang items7_sum by payment
                        case "settlementByPayment":
                            $_SESSION[$cCode]['items7_sum'] = $spec;
                            break;
                        //                        case "komposisi":
                        ////                            $_SESSION[$cCode]['items8_sum'] = $spec;
                        ////                            arrPrintPink($spec);
                        //                            break;
                    }
                }
            }

        }
        else {
            cekMerah("TIDAK akan memasukkan ITEMS");
        }

        $_SESSION[$cCode]['main']['refIDs'][$id] = $id;

        switch ($_GET['state']) {
            case "true":
                if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $_SESSION[$cCode]['items'][$id] = $tmp;
                }
                if (sizeof($componentAssConfig) > 0) {
                    if (!array_key_exists($id, $_SESSION[$cCode]['items2'])) {
                        $_SESSION[$cCode]['items2'][$id] = $itemsRegistries;
                    }
                }
                break;
            case "false":
                if (array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $detailResetList = array(
                        "items",
                        "tableIn_detail",
                        "tableIn_detail2",
                        "tableIn_detail_values",
                        "tableIn_detail2_sum",
                        "tableIn_detail_values2_sum",
                        "tableIn_detail3_sum",
                        "tableIn_detail_values3_sum",
                    );
                    foreach ($detailResetList as $sSName) {
                        $_SESSION[$cCode][$sSName][$id] = null;
                        unset($_SESSION[$cCode][$sSName][$id]);
                    }
                }
                if (isset($_SESSION[$cCode]['main']['refIDs'][$id])) {
                    $_SESSION[$cCode]['main']['refIDs'][$id] = null;
                    unset($_SESSION[$cCode]['main']['refIDs'][$id]);
                }

                if (sizeof($_SESSION[$cCode]['items']) > 0) {

                }
                else {

                    $mainValueInjector = isset($this->configUi[$this->jenisTr]['mainValueInjectors']) ? $this->configUi[$this->jenisTr]['mainValueInjectors'] : array();
                    if (sizeof($mainValueInjector) > 0) {
                        foreach ($mainValueInjector as $key => $val) {
                            $_SESSION[$cCode]['main'][$val] = null;

                            unset($_SESSION[$cCode]['main'][$val]);

                        }
                    }
                }
                if (isset($_SESSION[$cCode]['items2'][$id])) {
                    $_SESSION[$cCode]['items2'][$id] = null;
                    unset($_SESSION[$cCode]['items2'][$id]);
                }

                break;
        }

// matiHere();
        //-------------------------------------
        $bahanRekening = array();
        if(sizeof($bahanIDs)>0){
            $this->load->model("Coms/ComRekeningPembantuSupplies");
            $cm = New ComRekeningPembantuSupplies();
            $cm->setFilters(array());
            $cm->addFilter("extern_id in ('" . implode("','", $bahanIDs) . "')");
            $cm->addFilter("toko_id='" . $this->session->login['toko_id'] . "'");
            $cmTmp = $cm->fetchBalances("010302");
            showLast_query("biru");
            if(sizeof($cmTmp)>0){
                foreach ($cmTmp as $cmSpec){
                    $bahanRekening[$cmSpec->extern_id] = $cmSpec->qty_debet;
                }
            }
        }
        //--pairing ke items9_sum-----------------------------------
        if(sizeof($_SESSION[$cCode]['items9_sum'])>0){
            foreach ($_SESSION[$cCode]['items9_sum'] as $bID => $bSpec){
                $qty_stok = isset($bahanRekening[$bID]) ? $bahanRekening[$bID] : 0;
                $qty_dipakai = isset($bSpec['total_penggunaan_bahan']) ? $bSpec['total_penggunaan_bahan'] : 0;
                $qty_kekurangan = ($qty_stok - $qty_dipakai) < 0 ? ($qty_stok - $qty_dipakai) * -1 : 0;

                $_SESSION[$cCode]['items9_sum'][$bID]['qty_stok'] = $qty_stok;
                $_SESSION[$cCode]['items9_sum'][$bID]['qty_kekurangan'] = $qty_kekurangan;
            }
        }

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

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

    }
}