<?php

require_once "Modul_Controller.php";

class _processSelectNotaItem extends Modul_Controller
{
    public function __construct()
    {
        parent::__construct();
        // $this->jenisTr = $this->uri->segment(4);
        $cCode = $this->cCode;
        if (!isset($_SESSION[$cCode])) {
            $_SESSION[$cCode] = array(
                "items" => array(),
            );
        }
        if (!isset($_SESSION[$cCode]['items'])) {
            $_SESSION[$cCode]['items'] = array();
        }
    }

    public function select()
    {
        $this->load->library("FieldCalculator");
        $this->load->model("MdlTransaksi");

        $cal = new FieldCalculator();
        $trs = new Mdltransaksi();

        $id = $_GET['id'];
        $jml = isset($_GET['jml']) ? $_GET['jml'] : 1;

        $cCode = $this->cCode;

        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
            $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"]);
            }
        }

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

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


        $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][1] : array();
        $priceConfig = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;
        $referenceConfig = isset($this->configUi[$this->jenisTr]['referenceFields']) ? $this->configUi[$this->jenisTr]['referenceFields'] : null;
        //        $externalConfig = isset($this->configCore[$referenceJenisTr]['externalValues']) ? $this->configCore[$referenceJenisTr]['externalValues'] : array();
//        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        //  membaca isi nota
        $tmpB = $b->lookupByID($id)->result();
        //        cekMerah(":: " . $this->db->last_query());
        // matiHere();


        //  membaca registry shipment (582spd)
        // $trs->addFilter("id='$id'");
        // $result = $trs->lookupMainTransaksi()->result();
        // $reg_index = isset($result[0]->indexing_registry) ? blobDecode($result[0]->indexing_registry) : array();
        //
        //
        // if(sizeof($reg_index) > 0){
        //     $trs = new Mdltransaksi();
        //     $trs->setFilters(array());
        //     $trs->addFilter("id in ('" . implode("','", $reg_index) . "')");
        //     $trs->setSortBy(array("kolom" => "id", "mode" => "asc"));
        //     $trs->setTableName($trs->getTableNames()['registry']);
        //     $tmpRegistry = $trs->lookupAll()->result();
        // }
        // else{
        //     $trs = new Mdltransaksi();
        //     $tmpRegistry = $trs->lookupRegistriesByMasterID($id)->result();
        // }

        $tmpRegistry = $trs->lookupDataRegistriesByMasterID($id)->result();
        // cekHitam($this->db->last_query());
        $regFilds = $trs->getFields()["dataRegistry"];
        // arrPrint($regFilds);
        // matiHEre();
        if (sizeof($tmpRegistry) > 0) {
            foreach ($tmpRegistry as $row) {
                foreach ($regFilds as $param) {
                    $$param = is_numeric($row->$param) ? $row->$param : blobDecode($row->$param);
                }
                // $param = $row->param;

            }
        }

        // arrprint($items);
//         arrPrint($tmpB);
//                 matiHEre();
        if (sizeof($tmpB) > 0) {

            $this->db->trans_start();

            $_SESSION[$cCode]['main']['seluruhnya'] = true;
            $detailValuesKey_blacklist = array("jml", "qty");
            $arrListValidasiStok = array();

            foreach ($tmpB as $row) {
                $id = $row->produk_id;
                $tr_id = $row->transaksi_id;
                $name = $row->produk_nama;
                $tmpJml = $row->produk_ord_jml;
                $tmpJmlReturn = $row->produk_ord_jml_return;
                $tmpJml_avail = $tmpJml - $tmpJmlReturn;
                $tmpDisabled = "0";
                if ($tmpJml_avail <= 0) {
                    $tmpJml = 0;
                    $tmpDisabled = "1";
                }
                else {
                    $tmpJml = $tmpJml_avail;
                    $tmpDisabled = "0";
                }

//                arrPrintWebs($tr_id);

                if ($tmpJml > 0) {

                    if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {
                        cekMerah("masuk locker config");

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

                        $c->addFilter("produk_id='$id'");
                        $c->addFilter("state='active'");
                        $c->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                        $c->addFilter("gudang_id=" . $this->session->login['gudang_id']);

                        if(isset($tr_id)){
                            $c->addFilter("transaksi_id=" . $tr_id);
                        }

                        $tmpC = $c->lookupAll($id)->result();
//                        cekMerah($this->db->last_query());

                        if (sizeof($tmpC) > 0) {

                            foreach ($tmpC as $row2) {
                                $satuan = strlen($row2->satuan) > 0 ? $row2->satuan : "n/a";
                                $nama = $row2->nama;
                                $jml_now = $row2->jumlah;
                                $jml_nambah=0;
                                if (isset($_SESSION[$cCode]['items']) && !array_key_exists($id, $_SESSION[$cCode]['items'])) {
                                    $jml_sudah_diambil = 0;
                                    $jml_diperlukan = 1;
                                    $jml_nambah = 1;
                                }
                                else {
                                    if (isset($_GET['newQty'])) {
                                        $jml_sudah_diambil = $_SESSION[$cCode]['items'][$id]['jml'];
                                        $jml_diperlukan = $_GET['newQty'];
                                        $jml_nambah = $jml_diperlukan - $jml_sudah_diambil;
                                    }
                                    else {
                                        $jml_sudah_diambil = isset($_SESSION[$cCode]['items'][$id]['jml']) ? $_SESSION[$cCode]['items'][$id]['jml'] : 0;
                                        $jml_diperlukan = $jml_sudah_diambil + $jml;
                                        $jml_nambah = $jml;
                                    }
                                }

//                                cekHitam("jml_nambah awal: $jml_nambah");

                                //  region validasi stok
                                if ($jml_nambah > $jml_now) {
                                    $arrListValidasiStok[$id] = "$nama perlu: $jml_diperlukan | now: $jml_now";
//                                    echo "<script>top.alert('stok $nama tidak cukup. (perlu $jml_diperlukan, nambah $jml_nambah stok $jml_now)')";
//                                    echo "</script>";
//                                    die();
                                }
                                else{
                                    //  region update locker active
                                    $where = array(
                                        "id" => $row2->id,
                                    );
                                    $data_active = array(
                                        "jumlah" => $jml_now - $jml_nambah,
                                        "state" => "active",
                                    );
                                    $c->updateData($where, $data_active);

//                                    cekOrange("jml_nambah: $jml_nambah");
//                                    cekBiru($this->db->last_query());
                                    //  endregion update locker active
                                    //  region locker hold
                                    $array_hold_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "hold", $this->session->login['id'], "0", $this->session->login['gudang_id'], $this->session->login['toko_id']);
//                                    cekUngu($this->db->last_query());
//                                    arrPrint($jml_nambah);
//                                    arrPrint($array_hold_sebelumnya);
//                                    matiHere("stop");

                                    if (count($array_hold_sebelumnya) > 0) {
                                        $where = array(
                                            "id" => $array_hold_sebelumnya['id'],
                                        );
                                        $data_hold = array(
                                            "jumlah" => $array_hold_sebelumnya['jumlah'] + $jml_nambah,
                                        );
                                        $c->updateData($where, $data_hold);
//                                        cekOrange($this->db->last_query());
                                    }
                                    else {
                                        $data_hold = array(
                                            "jenis" => "produk",
                                            "cabang_id" => $this->session->login['cabang_id'],
                                            "produk_id" => $id,
                                            "nama" => $nama,
                                            "satuan" => $satuan,
                                            "state" => "hold",
                                            "jumlah" => $jml_nambah,
                                            "oleh_id" => $this->session->login['id'],
                                            "oleh_nama" => $this->session->login['nama'],
                                            "gudang_id" => $this->session->login['gudang_id'],
                                            "toko_id" => $this->session->login['toko_id'],
                                        );
                                        $c->addData($data_hold);
//                                        cekHere($this->db->last_query());
                                    }

                                    //  endregion locker hold
                                }
                                //  endregion validasi stok
                                $tmpJml = $jml_diperlukan;

                            }

                        }
                        else {
                            mati_disini("tidak ditemukan item " . $row2->nama . " di locker stock.");
                        }

                    }


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

                    if (!isset($_SESSION[$cCode]['items']) || (!array_key_exists($id, $_SESSION[$cCode]['items']))) {
                        cekmerah("belum ada di items, mau menambahkan");
                        $tmp = array(
                            "handler" => $this->uri->segment(1) . "/" . $this->uri->segment(2),
                            "id" => $id,
                            "name" => $name,
                            "nama" => $name,
                            "jml" => $tmpJml,
                            "harga" => 0,
                            "subtotal" => 0,
                            "disabled" => $tmpDisabled,
                        );

                        //region mengambil harga beli per-item
                        if (sizeof($priceConfig) > 0) {
                            $mdlName = $priceConfig['model'];
                            $this->load->model("Mdls/" . $mdlName);
                            $h = new $mdlName();
                            $h->addFilter("produk_id='$id'");
                            $h->addFilter("status='1'");
                            $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                            $h->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                            $tmpH = $h->lookupAll($id)->result();
                            cekMerah($this->db->last_query());
                            if (sizeof($tmpH) > 0) {
                                foreach ($tmpH as $hSpec) {
                                    foreach ($priceConfig['key_label'] as $key => $val) {
                                        if ($key == $hSpec->jenis_value) {
                                            $tmp[$val] = isset($hSpec->nilai) ? ($hSpec->nilai + 0) : 0;
                                        }
                                    }
                                }
                            }
                        }
                        //endregion

                        //region injector ke items, detail isi nota
                        if (isset($tableIn_detail_values[$id]) && sizeof($tableIn_detail_values[$id]) > 0) {
                            foreach ($tableIn_detail_values[$id] as $key => $val) {
                                if (!in_array($key, $detailValuesKey_blacklist)) {
                                    cekKuning($key . " diisi dengan " . $val);
                                    $tmp[$key] = $val;
                                }
                            }

                        }
                        //endregion

                        //                        arrprint($row);
                        foreach ($fieldSrcs as $key2 => $src2) {
                            $tmp[$key2] = makeValue($src2, $tmp, $tmp, $row->$src2);
                            //                            $tmp[$key2] = makeValue($src2, $tmp, $tmp, "");
                            cekmerah("$key2 diisi dengan " . $tmp[$key2]);
                        }

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


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

                        $tmp["subtotal"] = $subtotal;
//                        arrPrintWebs($tmp);
//                        matiHere($name);
                        $_SESSION[$cCode]['items'][$id] = $tmp;

                    }
                    else {
                        cekmerah("sudah ada di items, mau update subtotal");
                        if ($subAmountConfig != null) {
                            $subtotal = makeValue($subAmountConfig, $_SESSION[$cCode]['items'][$id], $_SESSION[$cCode]['items'][$id], 0);
                        }
                        else {
                            $subtotal = 0;
                            cekHijau("subtotal NOL");
                        }
                    }

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

//            matiHere();
            if(!empty($arrListValidasiStok)){
                $reasonValidity = "";
                foreach( $arrListValidasiStok as $ppid => $reason ){
                    $reasonValidity .= "<div>" . $reason . "</div>";
                    unset($_SESSION[$cCode]['items'][$ppid]);
                }

                $judulValidasi = "<b>Produk2 dibawah ini tidak bisa direturn</b><br>";

                echo "<script>top.swal({title: 'produk stok', html: '$judulValidasi $reasonValidity', type: 'warning'})";
                echo "</script>";
            }

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

            if (isset($master_add_fields) && sizeof($master_add_fields) > 0) {
                foreach ($master_add_fields as $key => $value) {
                    $_SESSION[$cCode]['main_add_fields'][$key] = $value;
                    $_SESSION[$cCode]['main'][$key] = $value;
                }
            }
            if (isset($master_add_values) && sizeof($master_add_values) > 0) {
                foreach ($master_add_values as $key => $value) {
                    $_SESSION[$cCode]['main_add_values'][$key] = $value;
                    $_SESSION[$cCode]['main'][$key] = $value;
                }
            }
            if (isset($tableIn_master_values) && sizeof($tableIn_master_values) > 0) {
                foreach ($tableIn_master_values as $key => $value) {
                    $_SESSION[$cCode]['main'][$key] = $value;
                }
            }
            if (sizeof($_SESSION[$cCode]['items']) > 0) {
                $_SESSION[$cCode]['main']['harga'] = 0;
                foreach ($_SESSION[$cCode]['items'] as $id => $iSpec) {
                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                }
            }
        }
        else {
            cekMerah("tidak ada itemnya!");
            die();
        }

        // region menuju ValueGate untuk rebuild gerbang nilai
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $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"),
            "ppnFactor"=>my_ppn_factor(),
//            "nomer_top"=> $_SESSION[$cCode]['main']['referenceNomer'],
            // "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;
        $referenceJenisTr = $this->configUi[$this->jenisTr]['referenceJenisTr'];
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $externalConfig = isset($this->configCore[$referenceJenisTr]['externalValues']) ? $this->configCore[$referenceJenisTr]['externalValues'] : array();
        $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHEre("undefine ppn factor, please logout and login again");

        $_SESSION[$cCode]['main']['seluruhnya'] = false;


        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'], "0", $this->session->login['gudang_id'], $this->session->login['toko_id']);
                $where = array(
                    "id" => $array_hold_sebelumnya['id'],
                );
                $data_hold = array(
                    "jumlah" => 0,
                );
                $c->updateData($where, $data_hold);


                $c = new $mdlName();
                $array_active_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "active", "0", "0", $this->session->login['gudang_id'], $this->session->login['toko_id']);
                $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");
        }


        $detailResetList = array(
            "items",
            "out_detail",
            "out_detail2",
            "tableIn_detail",
            "tableIn_detail2",
            "tableIn_detail_values",
            "tableIn_detail2_sum",
            "tableIn_detail_values2_sum",
        );
        foreach ($detailResetList as $sSName) {
            cekkuning("resetting $sSName");
            $_SESSION[$cCode]["$sSName"][$id] = null;
            unset($_SESSION[$cCode]["$sSName"][$id]);
        }

        if (sizeof($externalConfig) > 0) {
            foreach ($externalConfig as $keyName => $arrVal) {

                if (isset($arrVal['mdlName']) && strlen($arrVal['mdlName']) > 0) {
                    $key = $keyName . "_src";
                    if (isset($_SESSION[$cCode]['main_add_fields'][$key])) {
                        $_SESSION[$cCode]['main_add_fields'][$key] = null;
                        unset($_SESSION[$cCode]['main_add_fields'][$key]);
                    }
                }

                if (isset($arrVal['taxFactor'])) {
                    $key = $keyName . "_tax";
                    if (isset($_SESSION[$cCode]['main'][$key])) {
                        $_SESSION[$cCode]['main'][$key] = null;
                        unset($_SESSION[$cCode]['main'][$key]);
                    }
                    //                    if (isset($_SESSION[$cCode]['out_master'][$key])) {
                    //                        $_SESSION[$cCode]['out_master'][$key] = null;
                    //                        unset($_SESSION[$cCode]['out_master'][$key]);
                    //                    }
                    if (isset($_SESSION[$cCode]['main_add_values'][$key])) {
                        $_SESSION[$cCode]['main_add_values'][$key] = null;
                        unset($_SESSION[$cCode]['main_add_values'][$key]);
                    }
                }

                $key = $keyName;
                if (isset($_SESSION[$cCode]['main'][$key])) {
                    $_SESSION[$cCode]['main'][$key] = null;
                    unset($_SESSION[$cCode]['main'][$key]);
                }
                //                if (isset($_SESSION[$cCode]['out_master'][$key])) {
                //                    $_SESSION[$cCode]['out_master'][$key] = null;
                //                    unset($_SESSION[$cCode]['out_master'][$key]);
                //                }
                if (isset($_SESSION[$cCode]['main_add_values'][$key])) {
                    $_SESSION[$cCode]['main_add_values'][$key] = null;
                    unset($_SESSION[$cCode]['main_add_values'][$key]);
                }


            }
        }

        // region menuju ValueGate untuk rebuild gerbang nilai
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor($ppnFactor);

        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "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"),
            "ppnFactor"=>my_ppn_factor(),
            // "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 edit()
    {
        $id = $_GET['id'];
        $cCode = $this->cCode;
        $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheck']) ? $this->configUi[$this->jenisTr]['lockerCheck'] : array();
        $referenceJenisTr = $this->configUi[$this->jenisTr]['referenceJenisTr'];
        $externalConfig = isset($this->configCore[$referenceJenisTr]['externalValues']) ? $this->configCore[$referenceJenisTr]['externalValues'] : array();
        $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][1] : null;

        $_SESSION[$cCode]['main']['seluruhnya'] = true;

//        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'], "0", $this->session->login['gudang_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", "0", "0", $this->session->login['gudang_id']);
//
//                $where = array(
//                    "id" => $array_active_sebelumnya['id'],
//                );
//                $data_active = array(
//                    "jumlah" => $array_active_sebelumnya['jumlah'] + $array_hold_sebelumnya['jumlah'],
//                );
//                $c->updateData($where, $data_active);
//
//                $jml_active_sblm = $array_active_sebelumnya['jumlah'];
//                $jml_hold_sblm = $array_hold_sebelumnya['jumlah'];
//
////                matiHere("mati dulu | jml_active_sblm: $jml_active_sblm | jml_hold_sblm: $jml_hold_sblm");
//
//                $this->db->trans_complete() or die("Gagal bro");
//            }
//            else {
//                cekBiru("TIDAK ada barang, ga jadi cek loker");
//            }
//        }

        if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {
            cekMerah("masuk locker config");

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

            $c->addFilter("produk_id='$id'");
            $c->addFilter("state='active'");
            $c->addFilter("cabang_id=" . $this->session->login['cabang_id']);
            $c->addFilter("gudang_id=" . $this->session->login['gudang_id']);
            $c->addFilter("toko_id=" . $this->session->login['toko_id']);

            $tmpC = $c->lookupAll($id)->result();

            cekHere($this->db->last_query());

            //                    $persediaan = sizeof($tmpC) > 0 ? $tmpC[0]->persediaan : "0";
            if (sizeof($tmpC) > 0) {
                arrPrint($tmpC);
                foreach ($tmpC as $row2) {
                    $satuan = strlen($row2->satuan) > 0 ? $row2->satuan : "n/a";
                    $nama = $row2->nama;

                    $jml_now = $row2->jumlah;
                    if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                        $jml_sudah_diambil = 0;
                        $jml_diperlukan = 1;
                        $jml_nambah = 1;
                    }
                    else {
                        if (isset($_GET['newQty'])) {
                            $jml_sudah_diambil = $_SESSION[$cCode]['items'][$id]['jml'];
                            $jml_diperlukan = $_GET['newQty'];
                            $jml_nambah = $jml_diperlukan - $jml_sudah_diambil;
                        }
                        else {
                            $jml_sudah_diambil = $_SESSION[$cCode]['items'][$id]['jml'];
                            $jml_diperlukan = $jml_sudah_diambil + $jml;
                            $jml_nambah = $jml;
                        }
                    }
                    //  region validasi stok
                    if ($jml_nambah > $jml_now) {
                        echo "<script>top.alert('stok $nama tidak cukup. (perlu $jml_diperlukan, nambah $jml_nambah stok $jml_now)')";
                        echo "</script>";
                        die();
                    }
                    //  endregion validasi stok


                    $this->db->trans_start();

                    //  region update locker active
                    $where = array(
                        "id" => $row2->id,
                    );
                    $data_active = array(
                        "jumlah" => $jml_now - $jml_nambah,
                        "state" => "active",
                    );
                    $c->updateData($where, $data_active);
                    cekHere($this->db->last_query());
                    //  endregion update locker active


                    //  region locker hold
                    $array_hold_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "hold", $this->session->login['id'], "0", $this->session->login['gudang_id'], $this->session->login['toko_id']);
                    if (sizeof($array_hold_sebelumnya) > 0) {
                        $where = array(
                            "id" => $array_hold_sebelumnya['id'],
                        );
                        $data_hold = array(
                            "jumlah" => $array_hold_sebelumnya['jumlah'] + $jml_nambah,
                        );
                        $c->updateData($where, $data_hold);
                        cekHere($this->db->last_query());
                    }
                    else {
                        $data_hold = array(
                            "jenis" => "produk",
                            "cabang_id" => $this->session->login['cabang_id'],
                            "produk_id" => $id,
                            "nama" => $nama,
                            "satuan" => $satuan,
                            "state" => "hold",
                            "jumlah" => $jml_nambah,
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "gudang_id" => $this->session->login['gudang_id'],
                            "toko_id" => $this->session->login['toko_id'],
                        );
                        $c->addData($data_hold);
                        cekHere($this->db->last_query());
                    }
                    //  endregion locker hold

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

                    $tmpJml = $jml_diperlukan;

                }
            }
            else {
                mati_disini("tidak ditemukan item " . $row2->nama . " di locker stock.");
            }

        }
        else {
            cekBiru("TIDAK melibatkan session");
        }

        if (isset($_SESSION[$cCode]['items'][$id])) {
            if (isset($_GET['newQty'])) {
                $_SESSION[$cCode]['items'][$id]['jml'] = $_GET['newQty'];
                if ($subAmountConfig != null) {
                    $subtotal = makeValue($subAmountConfig, $_SESSION[$cCode]['items'][$id], $_SESSION[$cCode]['items'][$id], 0);
                }
                else {
                    $subtotal = 0;
                    cekHijau("subtotal NOL");
                }
                $_SESSION[$cCode]['items'][$id]['subtotal'] = $subtotal;
                if (sizeof($externalConfig) > 0) {
                    foreach ($externalConfig as $keyName => $arrVal) {
                        if (isset($arrVal['mdlName']) && strlen($arrVal['mdlName']) > 0) {
                            $key = $keyName . "_src";
                            if (isset($_SESSION[$cCode]['main'][$key])) {
                                $_SESSION[$cCode]['main'][$key] = null;
                                unset($_SESSION[$cCode]['main'][$key]);
                            }
                            if (isset($_SESSION[$cCode]['main_add_fields'][$key])) {
                                $_SESSION[$cCode]['main_add_fields'][$key] = null;
                                unset($_SESSION[$cCode]['main_add_fields'][$key]);
                            }
                        }
                        if (isset($arrVal['taxFactor'])) {
                            $key = $keyName . "_tax";
                            if (isset($_SESSION[$cCode]['main'][$key])) {
                                $_SESSION[$cCode]['main'][$key] = null;
                                unset($_SESSION[$cCode]['main'][$key]);
                            }
                            if (isset($_SESSION[$cCode]['main_add_values'][$key])) {
                                $_SESSION[$cCode]['main_add_values'][$key] = null;
                                unset($_SESSION[$cCode]['main_add_values'][$key]);
                            }
                        }

                        $key = $keyName;
                        if (isset($_SESSION[$cCode]['main'][$key])) {
                            $_SESSION[$cCode]['main'][$key] = null;
                            unset($_SESSION[$cCode]['main'][$key]);
                        }
                        if (isset($_SESSION[$cCode]['main_add_values'][$key])) {
                            $_SESSION[$cCode]['main_add_values'][$key] = null;
                            unset($_SESSION[$cCode]['main_add_values'][$key]);
                        }
                    }
                }
            }
        }

        // region menuju ValueGate untuk rebuild gerbang nilai
        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $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'],
        );
        $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()
    {

        die("updating.............................. (will be available sooner or later)");
        $rawParam = $_GET['param'];
        $param = unserialize(base64_decode($rawParam));
        if (is_array($param) && sizeof($param) > 0) {

        }
    }
}