<?php

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

class _processSelectProduct extends Modul_Controller
{
    public function __construct()
    {
        parent::__construct();

    }

    public function select()
    {
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        $actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $id = $produk_id = $_GET['id'];
        $jml = isset($_GET['jml'])&&$_GET['jml']*1>0 ? $_GET['jml']*1 : 1;
        $stepNum = $this->uri->segment(5) > 0 ? $this->uri->segment(5) : 1;
        $qty_unit = isset($_GET['qty_unit'])&&$_GET['qty_unit']*1>0 ? $_GET['qty_unit']*1 : $jml;
        $cCode = $this->cCode;
        $barcodesatuan = isset($_GET['barcodesatuan']) ? $_GET['barcodesatuan'] : array();
        $selectorModel = isset($_SESSION[$cCode]['main']['pihakMdlName']) ? $_SESSION[$cCode]['main']['pihakMdlName'] : $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = isset($_SESSION[$cCode]['main']['pihakMdlNameSrc']) ? $_SESSION[$cCode]['main']['pihakMdlNameSrc'] : $this->configUi[$this->jenisTr]['selectorSrcModel'];

        // detektor tanda kurawal {}
        if (substr($selectorModel, 0, 1) == "{") {
            $selectorModel = trim($selectorModel, "{");
            $selectorModel = trim($selectorModel, "}");
            $selectorModel = str_replace($selectorModel, $_SESSION[$cCode]['main'][$selectorModel], $selectorModel);
        }
        else {
            cekkuning("TIDAK mengandung kurawal @" . __LINE__ . __CLASS__);
        }
        if (substr($selectorSrcModel, 0, 1) == "{") {
            $selectorSrcModel = trim($selectorSrcModel, "{");
            $selectorSrcModel = trim($selectorSrcModel, "}");
            $selectorSrcModel = str_replace($selectorSrcModel, $_SESSION[$cCode]['main'][$selectorSrcModel], $selectorSrcModel);
        }
        else {
            cekkuning("TIDAK mengandung kurawal @" . __LINE__ . " " . __METHOD__);
        }

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

        $priceSrcConfig = $this->config->item('hePrices') != null ? $this->config->item('hePrices') : array();
        $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();
        $priceMainConfig = isset($this->configUi[$this->jenisTr]['selectedMainPrice']) ? $this->configUi[$this->jenisTr]['selectedMainPrice'] : 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;
        $connectedDiscountConfig = isset($this->configUi[$this->jenisTr]['connectedDiscount']) ? $this->configUi[$this->jenisTr]['connectedDiscount'] : array();
        $priceFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter']) ? $this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter'] : array();
        $resetFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $validateMeasurement = isset($this->configUi[$this->jenisTr]['validateMeasurement'][1]) ? $this->configUi[$this->jenisTr]['validateMeasurement'][1] : array();
        $shopingCartItemOptionFields = isset($this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][1]) ? $this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][1] : array();
        $valueGateConfig = isset($this->configValues[$this->jenisTr]['detailInjectedValues']) ? $this->configValues[$this->jenisTr]['detailInjectedValues'] : array();
        $autoCreateOrderId = isset($this->configUi[$this->jenisTr]['autoCreateOrderId']) ? $this->configUi[$this->jenisTr]['autoCreateOrderId'] : false;
        $validasiHpp = isset($this->configUi[$this->jenisTr]['validasiHpp']) ? $this->configUi[$this->jenisTr]['validasiHpp'] : false;

        if($autoCreateOrderId){
            if( !isset($_SESSION[$cCode]['main']['shoppingcart_order_id']) ){
                $_SESSION[$cCode]['main']['shoppingcart_order_id'] = strtotime(date("Y-m-d H:i:s"));
            }
        }

        $tmpB = $b->lookupByID($id)->result();
//        showLast_query("lime");
//        arrPrint($tmpB);
//        mati_disini(__LINE__);
        if (sizeof($tmpB) > 0) {
            foreach ($tmpB as $row) {
                $rows = $row;
                $valValidate_items = array();
                if (sizeof($validateMeasurement) > 0) {
                    $iValidate = 0;
                    foreach ($validateMeasurement as $keyVal => $validateKol) {
                        $valValidate = $row->$keyVal;
                        if ($valValidate == 0) {
                            $msg = "<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr><br><red class='text-red'>$validateKol = $valValidate </red><br>silahkan hubungi bagian entry data untuk melengkapi data produk";
                            $alerts = array(
                                "type" => "warning",
                                "title" => strtoupper("Data ukuran produk belum lengkap "),
                                "html" => $msg,
                            );
                            echo swalAlert($alerts);
                            die($msg);
                        }
                    }
                }

                if (sizeof($valValidate_items) > 0) {
                    $msg = "Data pendukung produk belum lengkap<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr>$jml_now $satuan stock available";
                    $alerts = array(
                        "type" => "warning",
                        "title" => strtoupper($kode),
                        "html" => $msg,
                    );
                    echo swalAlert($alerts);
                    die($msg);
                }

                $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";

                $tmpJml = $qty_unit;
                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());

                    if (sizeof($tmpC) > 0) {
                        $kode = $row->kode;
                        foreach ($tmpC as $row) {
                            $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                            $nama = $row->nama;
                            $jml_now = $row->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) {
                                $msg = "Insufficient stock of:<br><red class='text-red'>$kode $nama</red><hr>$jml_now $satuan stock available";
                                $alerts = array(
                                    "type" => "warning",
                                    "title" => strtoupper($kode),
                                    "html" => $msg,
                                );
                                echo swalAlert($alerts);
                                die($msg);
                            }
                            //  endregion validasi stok

                            $this->db->trans_start();

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

                            //  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']);
                            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" => $row->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'],
                                );
                                $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 " . $row->nama . " di locker stock.");
                    }
                }

                if (sizeof($connectedDiscountConfig) > 0) {
                    if ($connectedDiscountConfig['enabled'] == 1) {
                        $mdlNameRelation = $connectedDiscountConfig['mdlNameRelation'];
                        $mdlNameSource = $connectedDiscountConfig['mdlNameSource'];

                        $this->load->model("Mdls/" . $mdlNameRelation);
                        $dr = new $mdlNameRelation();
                        $dr->addFilter("produk_id='$id'");
                        $dr->addFilter("status='1'");
                        $tmpDr = $dr->lookupAll($id)->result();

                        $produkQty = isset($_GET['jml']) ? $_GET['jml'] : $tmpJml;
                        foreach ($tmpDr as $drSpec) {
                            $this->load->model("Mdls/" . $mdlNameSource);
                            $sr = new $mdlNameSource();
                            $sr->addFilter("id='" . $drSpec->diskon_id . "'");
                            $sr->addFilter("status='1'");
                            $tmpSr = $sr->lookupAll($id)->result();
                            showLast_query("merah");
                            foreach ($tmpSr as $srSpec) {
                                if ($produkQty > $srSpec->max_qty) {
                                    $discountPersen = $srSpec->discount_persen;
                                    $discountQty = $srSpec->discount_qty;
                                }
                                elseif (($produkQty >= $srSpec->min_qty) && ($produkQty <= $srSpec->max_qty)) {
                                    $discountPersen = $srSpec->discount_persen;
                                    $discountQty = $srSpec->discount_qty;
                                }
                                else {
                                    $discountPersen = 0;
                                    $discountQty = 0;
                                }
                                $arrDiscount[$id] = array(
                                    "persen" => $discountPersen,
                                    "qty" => $discountQty,
                                );
                                cekMerah("pID: $id ::: persen: $discountPersen ::: qty: $discountQty");
                            }
                        }
                    }
                }

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

                if(!empty($barcodesatuan)){
                    $arrBarcodeSatuan = blobDecode($barcodesatuan);
                    $tmpJml = $arrBarcodeSatuan['satuan_qty']*$qty_unit;
                    $satuan = $arrBarcodeSatuan['satuan_nama'];
                    $satuan_factor_id = $arrBarcodeSatuan['satuan_id'];
                    $satuan_factor_nama = $satuan;
                    $satuan_factor_qty = $arrBarcodeSatuan['satuan_qty'];
                }

                /* ----------------------------------------------------------------
                 * inisisasi cCode Items
                 * ----------------------------------------------------------------*/
                if (!isset($_SESSION[$cCode]['items']) || !array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $tmp = array(
                        "handler" => $this->modul . "/" . $this->uri->segment(2),
                        "id" => $id,
                        "jml" => $row->jenis=="digital" ? 1 : $tmpJml,
                        "qty_unit" => $row->jenis=="digital" ? 1 : $qty_unit,
                        "harga" => 0,
                        "subtotal" => 0,
                        "satuan" => $satuan,
                        "tipe_pajak" => $row->tipe_pajak,
                        "tipe_produk" => $row->jenis,
                    );

                    //------------------------------------------------------
                    foreach ($fieldSrcs as $key => $src) {
                        if (is_array($src) && sizeof($src) > 0) {
                            foreach ($src as $srcSpec) {
                                if (isset($tmp[$srcSpec]) || isset($rows->$srcSpec)) {
                                    cekBiru("ambil gerbang key -> $srcSpec");
                                    $tmp[$key] = makeValue($srcSpec, $tmp, $tmp, isset($rows->$srcSpec) ? $rows->$srcSpec : 0);
                                }
                            }
                        }
                        else {
                            $tmp[$key] = makeValue($src, $tmp, $tmp, isset($rows->$src) ? $rows->$src : 0);
                        }
                    }

                    if (isset($satuan_factor_id) && isset($satuan_factor_nama) && isset($satuan_factor_qty)) {
                        $tmp['satuan_factor_id'] = $satuan_factor_id;
                        $tmp['satuan_factor_nama'] = $satuan_factor_nama;
                        $tmp['satuan_factor_qty'] = $satuan_factor_qty;
                        $tmp['satuan_id'] = $satuan_factor_id;
                    }

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

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

                    /*
                     * bagian option satuan
                     */
                    // if (sizeof($shopingCartItemOptionFields) > 0) {
                    //     foreach ($shopingCartItemOptionFields as $keyField => $tempDataSrc) {
                    //         $targetSession = $tempDataSrc["targetSession"];
                    //         $targetkeySrc = $tempDataSrc["keySrc"];
                    //         if (isset($tempDataSrc["usedFields"])) {
                    //             foreach ($tempDataSrc["usedFields"] as $keySrcOption => $keyOptionKey) {
                    //                 // cekHitam("key items $keySrcOption ". $keyOptionKey);
                    //                 if (isset($tmp[$keyOptionKey])) {
                    //                     if (!isset($_SESSION[$cCode][$targetSession][$id][$keyField][$tmp[$targetkeySrc]][$keyOptionKey])) {
                    //                         // cekLime("key items $keySrcOption " . $keyOptionKey);
                    //                         $_SESSION[$cCode][$targetSession][$id][$keyField][$tmp[$targetkeySrc]][$keyOptionKey] = $tmp[$keyOptionKey];
                    //
                    //                     }
                    //                 }
                    //             }
                    //         }
                    //     }
                    // }

                    //region sambungin ke relasi satuan
                    if (sizeof($shopingCartItemOptionFields) > 0) {
                        foreach ($shopingCartItemOptionFields as $keyIndex => $dataExtSatuan) {
                            $mdl = $dataExtSatuan["mdlName"];
                            $targetSes = $dataExtSatuan["targetSession"];
                            $methode = $dataExtSatuan["methode"];
                            $indexKey = $dataExtSatuan["keySrc"];
                            $this->load->model("Mdls/" . $mdl);
                            $mm = new $mdl();
                            $mm->setTokoId(my_toko_id());
                            $prevCon = $mm->$methode($id);

                            if (sizeof($prevCon) > 0) {
                                foreach ($prevCon[$id] as $prevCon_0) {
                                    foreach ($dataExtSatuan["usedFields"] as $src => $target) {
                                        if (!isset($_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target])) {
                                            $_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target] = $prevCon_0[$src];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (sizeof($priceMainConfig) > 0) {
                        if (isset($priceMainConfig[$_SESSION[$cCode]['main']['pihakMainName']])) {
                            $priceConfig = $priceMainConfig[$_SESSION[$cCode]['main']['pihakMainName']];
                            cekUngu("masuk disini...");
                        }
                    }
                    if (sizeof($priceConfig) > 0) {
                        $mdlName = $priceConfig['model'];
                        $this->load->model("Mdls/" . $mdlName);
                        $h = new $mdlName();
                        if (isset($resetFilter['resetFilter']) && $resetFilter['resetFilter'] == true) {
                            $h->addFilter("produk_id='$id'");
                        }
                        else {
                            $h->addFilter("produk_id='$id'");
                            $h->addFilter("status='1'");
                            $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                        }
                        if (sizeof($priceFilter) > 0) {
                            foreach ($priceFilter as $f) {
                                $f_ex = explode("=", $f);
                                if (!isset($f_ex[1])) {
                                    $f_ey = explode(">", $f_ex[0]);
                                    if (substr($f_ey[1], 0, 1) == ".") {
                                        $h->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                                    }
                                    else {
                                        if (isset($_SESSION[$cCode]['main'][$f_ey[1]])) {
                                            $h->addFilter($f_ey[0] . ">'" . $_SESSION[$cCode]['main'][$f_ey[1]] . "'");
                                        }
                                        else {
                                            $h->addFilter($f_ey[0] . ">0");
                                        }
                                    }
                                }
                                else {
                                    if (substr($f_ex[1], 0, 1) == ".") {
                                        $h->addFilter($f_ex[0] . "='" . ltrim($f_ex[1], ".") . "'");
                                    }
                                    else {
                                        if (isset($_SESSION[$cCode]['main'][$f_ex[1]])) {
                                            $h->addFilter($f_ex[0] . "='" . $_SESSION[$cCode]['main'][$f_ex[1]] . "'");
                                        }
                                        else {
                                            $h->addFilter($f_ex[0] . "=''");
                                        }
                                    }
                                }
                            }
                        }
                        $tmpH = $h->lookupAll($id)->result();
                        if (sizeof($tmpH) > 0) {
                            $rawPrices = array();
                            foreach ($tmpH as $hSpec) {
                                foreach ($priceConfig['key_label'] as $key => $val) {
                                    if (isset($resetFilter['resetFilter'])) {
                                        //cekBiru("sino$key ||" . $hSpec->$key);
                                        $rawPrices[$key] = isset($hSpec->$key) ? $hSpec->$key : 0;
                                    }
                                    else {
                                        //cekBiru("sini ($key)" . __LINE__);
                                        if ($key == $hSpec->jenis_value) {
                                            $rawPrices[$key] = isset($hSpec->nilai) ? $hSpec->nilai : 0;
                                        }
                                    }
                                }
                            }
                            $prices = normalizePrices("produk", $rawPrices);
                            if (sizeof($prices) > 0) {
                                foreach ($prices as $k => $v) {
                                    $tmp[$k] = $v;
                                }
                                $tmp['harga'] = isset($tmp[$priceConfig['mainSrc']]) ? $tmp[$priceConfig['mainSrc']] : 0;
//                                $tmp['harga'] = isset($tmp[$priceConfig['mainSrc']]) ? $tmp[$priceConfig['mainSrc']] : 0;

                                //cek and protect HPP
                                //price_last_purchase
                                $this->load->model("Mdls/MdlHargaProdukLastPurchase");
                                $lp = new MdlHargaProdukLastPurchase();
                                $this->db->where( array('produk_id'=>$id, "jenis_value"=> "hpp", 'cabang_id'=> -1 ) );
                                $tmpLp = $lp->lookupAll($id)->result();
                                $tmp['hpp_produk_last_purchase'] = isset($tmpLp[0]->nilai) ? $tmpLp[0]->nilai : 0;

                                //fifo_avg
                                $this->load->model("Mdls/MdlFifoAverage");
                                $hp = new MdlFifoAverage();
                                $this->db->where( array('produk_id'=>$id, 'cabang_id'=>my_cabang_id()) );
                                $tmpHp = $hp->lookupAll($id)->result();

                                arrPrint($tmpHp);
                                //jika stok atas kosong
                                if( isset($tmpHp[0]->jml) && $tmpHp[0]->jml*1 == 0 ){
                                    $hpp_dipakai = 0;
                                    if( $tmp['hpp_produk_last_purchase']*1>0 && $tmpHp[0]->hpp*1>0 ){

                                        if( $tmp['hpp_produk_last_purchase']*1 < $tmpHp[0]->hpp*1){
                                            $hpp_dipakai = isset($tmpHp[0]->hpp) && $tmpHp[0]->hpp*1 > 0 ? $tmpHp[0]->hpp : 0;
                                        }
                                        elseif( $tmp['hpp_produk_last_purchase']*1 > $tmpHp[0]->hpp*1 ){
                                            $hpp_dipakai = isset($tmp['hpp_produk_last_purchase']) && $tmp['hpp_produk_last_purchase']*1 > 0 ? $tmp['hpp_produk_last_purchase']*1 : 0;
                                        }
                                        else{
                                            $hpp_dipakai = isset($tmpHp[0]->hpp) && $tmpHp[0]->hpp*1 > 0 ? $tmpHp[0]->hpp : 0;
                                        }

                                    }
                                    else{
                                        $hpp_dipakai = isset($tmp['hpp']) && $tmp['hpp']*1>0 ? $tmp['hpp'] : 0;
                                    }
                                    $tmp['hpp_produk'] = $hpp_dipakai;
                                }
                                else{
                                    $tmp['hpp_produk'] = isset($tmpHp[0]->hpp) && $tmpHp[0]->hpp*1 > 0 ? $tmpHp[0]->hpp : (isset($tmp['hpp']) && $tmp['hpp']*1>0 ? $tmp['hpp'] : 0);
                                }

                                $tmp['laba_jual'] = ($tmp['harga']*1) - ($tmp['hpp_produk']*1);
                                $tmp['laba_jual_satuan'] = $tmp['hpp_produk']*1;
                                $tmp['stok_cabang'] = $tmpHp[0]->jml*1;

                                /* ------------------------------------------------
                                 * $validasiHpp diatur dr coTransaksiUi
                                 * ------------------------------------------------*/
                                if( ($tmp['harga']*1) < ($tmp['hpp_produk']*1) ){

                                    if($validasiHpp){
                                        $this->validasiHpp($tmp,$cCode,$actual_link);
                                    }
                                    else{
                                        if( ($tmp['harga']*1) <= 0 ){
                                            matiHere("Harga jual belum diseting, silahkan hubungi admin toko untuk melakukan seting harga");
                                    }
                                    else{
                                        $_SESSION[$cCode]['items'][$produk_id] = $tmp;
                                    }
                                    }
                                }
                                else {
                                    if( ($tmp['harga']*1) <= 0 ){
                                        matiHere("*Harga jual belum diseting, silahkan hubungi admin toko untuk melakukan seting harga");
                                }
                                else {
                                        $_SESSION[$cCode]['items'][$produk_id] = $tmp;
                                    }
                                }
                                //endregion
                            }
                            else{
                                matiHere("**Harga jual belum diseting, silahkan hubungi admin toko untuk melakukan seting harga");
                            }
                        }
                        else {
                            matiHere("***Harga jual belum diseting, silahkan hubungi admin toko untuk melakukan seting harga");
                        }
                    }
                }
                else {
                    cekBiru("ada id ($id) tapi tidak ada di session items @" . __LINE__);
                    if(!empty($barcodesatuan)){

                        if( $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] != $satuan_factor_qty ){
                            if( $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] > $satuan_factor_qty ){
                                $jml_down = $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] * $_SESSION[$cCode]['items'][$id]['qty_unit'];
                                $qty_down = $jml_down;
                                $qty_tambah = $qty_down + $satuan_factor_qty;
                            }
                            else{
                                //jika before lebih kecil dari pada after
                                cekKuning("before lebih kecil dari pada after");
                                if($_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] > 1){
                                    //jika ternyata satuan sebelumnya belum satuan terkecil,
                                    //maka wajib di convert menjadi satuan terkecil dulu

                                    //convert satuan sebelumnya ke satuan terkecil dulu
                                    $jml_before = $_SESSION[$cCode]['items'][$id]['jml'];
                                    $unit_before = $_SESSION[$cCode]['items'][$id]['qty_unit'];
                                    $satuan_unit_before = $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];

                                    $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] = 1;
                                    $_SESSION[$cCode]['items'][$id]['satuan_factor_id'] = $row->satuan_id;
                                    $_SESSION[$cCode]['items'][$id]['satuan_factor_nama'] = $row->satuan;

                                    $jml_after = $unit_before*$satuan_unit_before;
                                    $unit_after = $jml_after;

                                    //setelah dapat angka jml dan qty dalam satuan terkecil,
                                    //tambahkan dengan jml dan unit total yang baru masuk juga dalam satuan terkecil,
                                    //perlu convert jika satuan yg baru bukan satuan terkecil,
                                    //untuk mengurangi kesalahan, disini converter akan langsung memposisikan segala jenis satuan ke satuan terkecil

                                    $jml_smallest = $tmpJml;
                                    $qty_smallest = $jml_smallest;  //nilai sama karena di convert ke satuan terkecilnya...

                                    $_SESSION[$cCode]['items'][$id]['jml'] = $jml_after+$jml_smallest;
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] = $unit_after+$qty_smallest;

                                }
                                else if($_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] == 1){
                                    //jika satuan sekarang adalah satuan terkecilnya,
                                    //maka satuan sebelumnya bisa langsung di tambahkan,
                                    //tentunya harus di kali kan dulu dengan faktor kali satuan yg baru

                                    $qty_before = $_SESSION[$cCode]['items'][$id]['qty_unit'];
                                    $qty_after = $_SESSION[$cCode]['items'][$id]['qty_unit'] + $tmpJml;
                                    $new_factor = $satuan_factor_qty;

                                    $_SESSION[$cCode]['items'][$id]['jml'] = $qty_after;
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] = $qty_after;

                                    //satuan tetap karena udh dari satuan terkecil sebelum nya..
                                    //matiHere("before lebih kecil dari pada after DAN faktor sebelum = 1 <br>qty_before:$qty_before | qty_after: $qty_after<br>new_factor: $new_factor | tmpJml: $tmpJml");
                                }
                                else{

                                }
                            }
                        }
                        else{
                            cekHijau("TIDAK BERUBAH SATUAN");
                        }
                    }
                    else{
                        if(isset($_GET['newQty'])) {
                            //boleh edit kebawah ??
                            $allowDown=1; //0 = perlu otorisasi 1= tidak perlu otorisasi
                            $sesAllowDown = isset($_SESSION[$cCode]['items'][$id]['allowDown']) && $_SESSION[$cCode]['items'][$id]['allowDown']==1 ? 1 : 0;
                            if($_SESSION[$cCode]['items'][$id]['qty_unit'] > $_GET['newQty'] && !$allowDown && !$sesAllowDown){

                                $oto_qty_unit_set = 1;
                                $qty_unit_before_set = $_SESSION[$cCode]['items'][$id]['qty_unit'];
                                $qty_unit_target_set = $_GET['newQty'];
                                $cCode_set = $cCode;
                                $id_set = $id;
                                $gate_set = "items";
                                $shoppingcart_order_id = $_SESSION[$cCode]['main']['shoppingcart_order_id'];

                                echo "<script>

                                    var showViewOtorisasiQty = function(){
                                        top.swal({
                                           title: 'Perlu Otorisasi Admin/SPV',
                                           html: 'Mengurangi kuantiti produk harus melalui Otorisasi.<br>Masukan PIN/OTP dari SPV Anda...???<br><br><br>' +
                                           \"<div class=''>\" +
                                           \"<div style='' class='col-md-12 col-xs-12'>\" +
                                           \"<div class='input-group'>\" +

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

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

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

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

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

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

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

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

                                                            setTimeout(function(){
                                                                showViewOtorisasiQty()
                                                            },1000)
                                                        }
                                                    })
                                                }

                                                var pushRequestQty = function(){

                                                    top.$('#qtyPinOtp').attr('disabled', true)
                                                    top.$.ajax({
                                                        url: '". base_url() . $this->modul . "/_shoppingCart/reqQtySave/".$this->jenisTr."',
                                                        method: 'post',
                                                        data: {
                                                            oto_qty_unit_set: $oto_qty_unit_set,
                                                            qty_unit_before_set: $qty_unit_before_set,
                                                            qty_unit_target_set: $qty_unit_target_set,
                                                            cCode_set: '$cCode_set',
                                                            gate_set: '$gate_set',
                                                            id_set: $id_set,
                                                            shoppingcart_order_id: $shoppingcart_order_id,
                                                            jenisTr: '".$this->jenisTr."',
                                                        },
                                                        success: function(a){
                                                            jsonData = JSON.parse(a);
                                                            if(jsonData.status){
                                                                top.$('#qtyPinOtp').attr('disabled', false)
                                                            }
                                                            else{

                                                            }
                                                        }
                                                    })
                                                }
                                                pushRequestQty()
                                           }
                                        });
                                    }

                                    showViewOtorisasiQty()

                                </script>";

                            }
                            else{

                                if( !isset( $_SESSION[$cCode]['items'][$id]['allowHpp'] ) ){
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] = isset($_GET['newQty']) && $_GET['newQty']*1>0 ? $_GET['newQty']*1 : 1;
                                    $_SESSION[$cCode]['items'][$id]['jml'] = isset($_GET['newQty']) && $_GET['newQty']*1>0 ? $_GET['newQty'] * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] : $_SESSION[$cCode]['items'][$id]['satuan_factor_qty']*1;
                                    if(isset($_SESSION[$cCode]['items'][$id]['allowDown'])){
                                        unset($_SESSION[$cCode]['items'][$id]['allowDown']);
                                    }
                                }
                                else{
                                    $allowHppQty = $_SESSION[$cCode]['items'][$id]['allowHppQty'];
                                    $allowHppUom = $_SESSION[$cCode]['items'][$id]['allowHppUom'];
                                    $tmp_qty_unit = isset($_GET['newQty']) && $_GET['newQty']*1>0 ? $_GET['newQty']*1 : 1;
                                    $tmp_jml = isset($_GET['newQty']) && $_GET['newQty']*1>0 ? $_GET['newQty'] * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] : $_SESSION[$cCode]['items'][$id]['satuan_factor_qty']*1;
                                    if( $allowHppQty != $tmp_qty_unit || $allowHppUom != $_SESSION[$cCode]['items'][$id]['satuan_factor_nama'] ){
                                        $sesTmp = $_SESSION[$cCode]['items'][$id];
                                        $sesTmp['jml'] = $tmp_jml;
                                        $sesTmp['qty_unit'] = $tmp_qty_unit;
                                        $this->validasiHpp($sesTmp, $cCode, $actual_link);
                                    }
                                }
                            }
                        }
                        else {
                            if( $_SESSION[$cCode]['items'][$id]['tipe_produk'] == "digital"){
                                $_SESSION[$cCode]['items'][$id]['jml'] = 1;
                                $_SESSION[$cCode]['items'][$id]['qty_unit'] = 1;
                            }
                            else{
                                if( !isset( $_SESSION[$cCode]['items'][$id]['allowHpp'] ) ){
                                    $_SESSION[$cCode]['items'][$id]['jml'] += $qty_unit;
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] += $qty_unit * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];
                                }
                                else{

                                }
                            }
                        }
                        if (isset($arrDiscount[$id]) && sizeof($arrDiscount[$id]) > 0) {
                            foreach ($arrDiscount[$id] as $dKey => $dVal) {
                                if (!isset($_SESSION[$cCode]['items'][$id]['discount_' . $dKey])) {
                                    $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = 0;
                                }
                                $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = $dVal;
                            }
                        }
                        if (sizeof($itemNumLabels) > 0) {
                            cekHere("iterating subNums..");
                            foreach ($itemNumLabels as $key => $label) {
                                if (isset($_GET[$key]) && strlen($_GET[$key]) > 0) {
                                    $newValue = $_GET[$key];
                                    $tmp[$key] = $newValue;
                                    $_SESSION[$cCode]['items'][$id][$key] = $newValue;
                                    cekHere("replacing value for $key with " . $newValue . "<br>");
                                }
                            }
                            if ($subAmountConfig != null) {
                                $tmp['subtotal'] = makeValue($subAmountConfig, $_SESSION[$cCode]['items'][$id], $_SESSION[$cCode]['items'][$id], 0);
                            }
                            else {
                                $tmp['subtotal'] = 0;
                            }
                            $_SESSION[$cCode]['items'][$id]['subtotal'] = $tmp['subtotal'];
                        }
                    }
                }

//                arrPrintWebs($_SESSION[$cCode]['items'][$id]);
//                arrPrintPink($tmp);
//                mati_disini(__LINE__);
                /* ----------------------------------------------------------
                 * diskon-diskonan-grosir
                 * ----------------------------------------------------------*/
                $tmp = isset($_SESSION[$cCode]['items'][$id]) ? $_SESSION[$cCode]['items'][$id] : $tmp;
                $pro_premi = $row->premi_jual;
                $pro_harga = $tmp['harga_list'] + (($pro_premi / 100) * $tmp['harga_list']);

//                $pro_harga = $tmp['jual'] + (($pro_premi / 100) * $tmp['jual']);

                // cekBiru("$pro_premi || $pro_harga");
                $grosir_status = isset($_GET['grosir']) ? $_GET['grosir'] : "1";
                $free_status = isset($_GET['free']) ? $_GET['free'] : "1";
                $pro_jml = $tmp['jml'];
                $calc_hasil = $this->selectorDiskon($id, $pro_harga, $pro_jml, $grosir_status);

                // arrPrintKuning($calc_hasil);

                $tmp['discPersen']  = $calc_hasil['persen'];
                $tmp['lastNett']    = $calc_hasil['harga_af'];
                $tmp['harga']       = $calc_hasil['harga_af'];

                $tmp['harga_jual']  = $calc_hasil['harga_be']*$tmp['satuan_factor_qty'];
                $tmp['harga_disc']  = ($calc_hasil['harga_af']*$tmp['satuan_factor_qty'])*$tmp['qty_unit'];

                $tmp['discNilai']   = $calc_hasil['nilai']*$tmp['satuan_factor_qty'];
                $tmp['id']          = $id;

                $tmp['subtotal'] = $calc_hasil['harga_af']*$pro_jml;
                $_SESSION[$cCode]['items'][$produk_id] = $tmp;
//arrPrintPink($tmp);
                // $calc_free_produk = $this->selectorDiskonFreeProduk($id, $pro_harga, $pro_jml);
                // arrPrintWebs($calc_free_produk);
                // cekMerah($calc_hasil['free_produk_note']);
                // arrPrintWebs(count($calc_hasil['free_produk']));
                // arrPrintPink($calc_hasil);

                if( isset($calc_hasil['free_produk']) && $calc_hasil['free_produk']==1 ){
                    $nomer_diskon       = $calc_hasil['nomer_diskon'];
                    $ori_produk_id      = $calc_hasil['ori_produk_id'];
                    $ori_produk_nama    = $calc_hasil['ori_produk_nama'];
                    $free_produk_id     = $calc_hasil['free_produk_id'];
                    $free_produk_id     = $calc_hasil['free_produk_id'];
                    $free_produk_nama   = $calc_hasil['free_produk_nama'];
                    $free_qty           = $calc_hasil['free_qty'];
                    $free_produk_note   = $calc_hasil['free_produk_note'];
                    $produk_beli_jml    = $calc_hasil['produk_beli_jml'];
                    $kelipatan          = $calc_hasil['kelipatan'];
                    $minim              = $calc_hasil['minim'];
                    $quota_global       = $calc_hasil['quota_global'];
                    $quota_used         = $calc_hasil['quota_used'];
                    $quota_sisa         = $calc_hasil['quota_sisa'];

                    // cekAlert("$grosir_status");
                    if($grosir_status == 1 && $free_status == 1){
                    $_SESSION[$cCode]['free_items'][$produk_id][$nomer_diskon] = array(
                        "ori_produk_id" => $ori_produk_id,
                        "ori_produk_nama" => $ori_produk_nama,
                        "produk_beli_jml" => $produk_beli_jml,
                        "free_produk_id" => $free_produk_id,
                        "free_produk_nama" => $free_produk_nama,
                        "free_qty" => $free_qty,
                        "free_produk_note" => $free_produk_note,
                        "kelipatan" => $kelipatan,
                        "minimal" => $minim,
                        "quota_global" => $quota_global,
                        "quota_used" => $quota_used,
                        "quota_sisa" => $quota_sisa,
                        "date" => date('Y-m-d H:i:s'),
                    );

                    $_SESSION[$cCode]['items'][$produk_id]['free_items'] = $_SESSION[$cCode]['free_items'][$produk_id];
                }
                }
                else{
                    if(isset($calc_hasil['free_produk_note'])){
                        $_SESSION[$cCode]['items'][$produk_id]['free_produk_note'] = $calc_hasil['free_produk_note'];
                    }
                    unset($_SESSION[$cCode]['free_items'][$produk_id]);
                    unset($_SESSION[$cCode]['items'][$produk_id]['free_items']);
                }

                $tmpMains = $_SESSION[$cCode]['main'];
                $m_harga_nett2 = $tmpMains['harga_nett2'];
                arrPrintHijau($tmpMains);
                // matiHere(__LINE__);
            }
        }
        else {
            cekMerah("tidak ada itemnya! @" . __LINE__ . " " . __METHOD__);
            die();
        }


        //dipakai untuk debug saja
        //dipakai untuk debug only
        //jika belum ada produk maka di unset dulu.
//        cekHijau("HASIL AKHIR AKAN DI INJECT");
//        cekHijau($_SESSION[$cCode]['items'][$id]);
//        unset($_SESSION[$cCode]['items'][$id]);
        // arrPrint($_SESSION[$cCode]['items']);
//         mati_disini(__LINE__);
        $f_selector = "";
        if (isset($_GET['selector'])) {
            $f_selector = "selector&";
        }

        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor(my_ppn_factor());

        if (isset($_GET['mb'])) {
            mati_disini(__FILE__ . "<hr> @" . __LINE__);
            $initMaster = array(
                "olehID" => $this->session->login['id'],
                "olehName" => $this->session->login['nama'],
                "placeID" => $this->session->login['cabang_id'],
                "placeName" => $this->session->login['cabang_nama'],
                "divID" => isset($this->session->login['div_id']) ? $this->session->login['div_id'] : 0,
                "divName" => isset($this->session->login['div_nama']) ? $this->session->login['div_nama'] : 0,
                "cabangID" => $this->session->login['cabang_id'],
                "cabangName" => $this->session->login['cabang_nama'],
                "gudangID" => $this->session->login['gudang_id'],
                "gudangName" => $this->session->login['gudang_nama'],
                "jenis_usaha" => isset($this->session->login['jenis_usaha']) ? $this->session->login['jenis_usaha'] : '-',
                "jenisTr" => $this->jenisTr,
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $this->config->item('heTransaksi_ui')[$this->jenisTr]['steps'][1]['target'],
                "jenisTrName" => $this->jenisTrName,
                "stepNumber" => $stepNum,
                "stepCode" => $this->config->item('heTransaksi_ui')[$this->jenisTr]['steps'][$stepNum]['target'],
                "dtime" => date("Y-m-d H:i:s"),
                "fulldate" => date("Y-m-d"),
                // "jenis_pajak"=>$this->session->login['jenis_usaha'],
                "tokoID" => $this->session->login['toko_id'],
                "tokoNama" => $this->session->login['toko_nama'],
            );
            // hevalueGateInisisai($initMaster);
            echo "<script>";
            echo "top.document.getElementById('result').src='" . base_url() . "ValueGate/buildValues/" . $this->jenisTr . "?" . $f_selector . "selID=$id';";
            echo "top.load_shoppingcart();";
            echo "</script>";
        }
        else {
            $initMasterValues = array(
                "olehID" => my_id(),
                "olehName" => my_name(),
                "placeID" => my_cabang_id(),
                "placeName" => my_cabang_nama(),
                "divID" => my_div_id(),
                "divName" => my_div_nama(),
                "cabangID" => my_cabang_id(),
                "cabangName" => my_cabang_nama(),
                "gudangID" => my_gudang_id(),
                "gudangName" => my_gudang_nama(),
                "jenis_usaha" => my_jenis_usaha(),
                "tokoID" => my_toko_id(),
                "tokoNama" => my_toko_nama(),
                "machineID" => $this->session->login['machineID'],
                "CPU_INFO" => $this->session->login['CPU_INFO'],
                "COM_INFO" => $this->session->login['COM_INFO'],
                "jenisTr" => $this->jenisTr,
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $this->configUiJenis['steps'][1]['target'],
                "jenisTrName" => $this->configUiJenis['steps'][1]['label'],
                "stepNumber" => $stepNum,
                "stepCode" => $this->configUiJenis['steps'][$stepNum]['target'],
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow("Y-m-d"),
                // "jenis_pajak"=>$this->session->login['jenis_usaha'],
            );
            // $vg->buildValue($this->jenisTr, $id, $initMasterValues, $configUiJenis);
            $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);
            // mati_disini(__FILE__ . "<hr> @" . __LINE__);
            // echo "<script>";
            // echo "top.document.getElementById('result').src='" . base_url() . "ValueGate/buildValues/" . $this->jenisTr . "?".$f_selector."selID=$id&modul=".$this->modul."';";
            // echo "</script>";

            // matiHere(__METHOD__ . __LINE__);
            /* --------------------------------------------------
             * ngereload shoping cart dlm modul
             * --------------------------------------------------*/
            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 multiSelect()
    {
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        $items = $_GET['items'];
        $idss = isset($_GET["ids"]) ? $_GET["ids"] : "0";
        $arrItems = isset($_GET['items']) ? unserialize(base64_decode($items)) : array();
        $arrTrID = isset($_GET['trs']) ? unserialize(base64_decode($_GET['trs'])) : array();
        $arrMain = isset($_GET['main']) ? unserialize(base64_decode($_GET['main'])) : array();

        $cCode = "_TR_" . $this->jenisTr;
        $toko_id = my_toko_id();

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

        if (sizeof($arrItems) > 0) {
            // arrPrint($arrItems);
            foreach ($arrItems as $id => $jmlParam) {
                $tmpB = $b->lookupByID($id)->result();
                $produk_id = $id;
                $jml = $jmlParam;
                if (sizeof($tmpB) > 0) {
                    foreach ($tmpB as $row) {
                        $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                        $tmpJml = $jmlParam;
                        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']);
                            $tmpC = $c->lookupAll($id)->result();
                            cekHere($this->db->last_query());

                            if (sizeof($tmpC) > 0) {
                                arrPrint($tmpC);
                                foreach ($tmpC as $row) {
                                    $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                                    $nama = $row->nama;
                                    $jml_now = $row->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" => $row->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']);
                                    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" => $row->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'],
                                        );
                                        $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 " . $row->nama . " di locker stock.");
                            }
                        }
                        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
                        if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                            $tmp = array(
                                "handler" => $this->uri->segment(1) . "/" . $this->uri->segment(2),
                                "id" => $id,
                                "qty_unit" => $tmpJml,
                                "harga" => 0,
                                "subtotal" => 0,
                            );

                            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='" . $priceConfig['label'] . "'");
                                $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                                $h->addFilter("toko_id=" . $toko_id);
                                $tmpH = $h->lookupAll($id)->result();
                                cekMerah($this->db->last_query());
                                if (sizeof($tmpH) > 0) {
                                    $rawPrices = array();
                                    foreach ($tmpH as $hSpec) {
                                        foreach ($priceConfig['key_label'] as $key => $val) {
                                            if ($key == $hSpec->jenis_value) {
                                                $rawPrices[$key] = isset($hSpec->nilai) ? $hSpec->nilai : 0;
                                            }
                                        }
                                    }
                                    $prices = normalizePrices("produk", $rawPrices);
                                    if (sizeof($prices) > 0) {
                                        foreach ($prices as $k => $v) {
                                            $tmp[$k] = $v;
                                        }
                                        $tmp['harga'] = isset($tmp[$priceConfig['mainSrc']]) ? $tmp[$priceConfig['mainSrc']] : 0;
                                    }
                                }
                            }

                            foreach ($fieldSrcs as $key => $src) {
                                if (is_array($src) && sizeof($src) > 0) {
                                    foreach ($src as $srcSpec) {
                                        if (isset($tmp[$srcSpec]) || isset($row->$srcSpec)) {
                                            cekBiru("ambil gerbang key -> $srcSpec");
                                            $tmp[$key] = makeValue($srcSpec, $tmp, $tmp, isset($row->$srcSpec) ? $row->$srcSpec : 0);
                                        }
                                    }
                                }
                                else {
                                    $tmp[$key] = makeValue($src, $tmp, $tmp, isset($row->$src) ? $row->$src : 0);
                                }
                            }
                            //===perhitungan subtotal
//                            if (sizeof($arrMain) > 0) {
//                                foreach ($arrMain as $key => $val) {
//                                    // matiHEre($key);//dimatiin biar tidak teroverwrite saat swap transaksi main
//                                    // $_SESSION[$cCode]["main"][$key] = $val;
//                                }
//                            }

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

                            //region sambungin ke relasi satuan
                            if (sizeof($shopingCartItemOptionFields) > 0) {
                                foreach ($shopingCartItemOptionFields as $keyIndex => $dataExtSatuan) {
                                    $mdl = $dataExtSatuan["mdlName"];
                                    $targetSes = $dataExtSatuan["targetSession"];
                                    $methode = $dataExtSatuan["methode"];
                                    $indexKey = $dataExtSatuan["keySrc"];
                                    $this->load->model("Mdls/" . $mdl);
                                    $mm = new $mdl();
                                    $mm->setTokoId(my_toko_id());
                                    $prevCon = $mm->$methode($id);
                                    // arrPrint($prevCon);
                                    if (sizeof($prevCon) > 0) {
                                        foreach ($prevCon[$id] as $prevCon_0) {
                                            foreach ($dataExtSatuan["usedFields"] as $src => $target) {
                                                if (!isset($_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target])) {
                                                    // cekMerah($prevCon_0[$indexKey]."  $target =>".$prevCon_0[$src]);
                                                    $_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target] = $prevCon_0[$src];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //endregion

                            /* ----------------------------------------------------------
                             * diskon-diskonan-grosir
                             * ----------------------------------------------------------*/
                            $produk_id = $id;
                            cekHitam("diskon produk_id $produk_id || tokid " . my_toko_id());
                            $this->load->library("Diskon");
                            $dp = new Diskon();
                            $dp->setTokoId(my_toko_id());
                            $src_diskon = $dp->CallProdukDiskon($produk_id);

                            // diskon
                            $pro_harga = $tmp['harga'] * 1;
                            $pro_jml = $tmp['jml'];
                            cekPink("$pro_harga || $pro_jml");
                            /*---menentukan diskon pokok dari produk atau grosir----*/
                            $d_pokok = isset($src_diskon['produk']) ? $src_diskon['produk'] : 0;

                            $jml_spek_grosir = sizeof($src_diskon['grosir']);
                            if ($jml_spek_grosir > 0) {
                                $gro_count = 0;
                                foreach ($src_diskon['grosir'] as $item) {
                                    $gro_count++;
                                    $gro_minim = $item['minim'];
                                    $gro_maxim = $gro_count == $jml_spek_grosir ? INF : $item['maxim'];
                                    $gro_persen = $item['persen'];
                                    cekPink2("$pro_jml >= $gro_minim) && ($pro_jml <= $gro_maxim)");
                                    if (($pro_jml >= $gro_minim) && ($pro_jml <= $gro_maxim)) {
                                        $d_pokok = $gro_persen;
                                        cekBiru("---- $d_pokok");
                                        break;
                                    }
                                }
                            }
                            else {
                                // $d_pokok = isset($src_diskon['produk']) ? $src_diskon['produk'] : 0;
                            }

                            $diskon_pokok["produk"] = $d_pokok;
                            $diskon_event = array();

                            $calc_hasil = $dp->calcDiskon($pro_harga, $diskon_pokok, $diskon_event, "diskon");

                            $tmp['discPersen'] = $calc_hasil['persen'];
                            $tmp['harga_disc'] = $calc_hasil['harga_af'];
                            $tmp['lastNett'] = $calc_hasil['harga_af'];
                            $tmp['harga'] = $calc_hasil['harga_af'];
                            $tmp['discNilai'] = $calc_hasil['nilai'];

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

                        }
                        else {
                            if (isset($_GET['newQty'])) {
                                $_SESSION[$cCode]['items'][$id]['jml'] = $_GET['newQty'];
                                $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * $_SESSION[$cCode]['items'][$id]['harga']);
                            }
                            else {
                                $_SESSION[$cCode]['items'][$id]['jml'] += $jml;
                                $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * $_SESSION[$cCode]['items'][$id]['harga']);
                            }

                            if (sizeof($itemNumLabels) > 0) {
                                echo("iterating subNums..");
                                foreach ($itemNumLabels as $key => $label) {
                                    if (isset($_GET[$key]) && $_GET[$key] > 0) {
                                        $newValue = $_GET[$key];
                                        $tmp[$key] = $newValue;
                                        $_SESSION[$cCode]['items'][$id][$key] = $newValue;
                                        echo "replacing value for $key with " . $newValue . "<br>";
                                    }
                                }
                                foreach ($itemNumLabels as $key => $label) {
                                    $_SESSION[$cCode]['items'][$id]["sub_" . $key] = ($_SESSION[$cCode]['items'][$id][$key] * $_SESSION[$cCode]['items'][$id]["jml"]);
                                }
                                $_SESSION[$cCode]['items'][$id]['sub_nett'] = ($_SESSION[$cCode]['items'][$id]['nett'] * $_SESSION[$cCode]['items'][$id]['jml']);
                                $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * $_SESSION[$cCode]['items'][$id]['harga']);
                            }
                        }
                    }
                    if (sizeof($_SESSION[$cCode]['items']) > 0) {
                        $_SESSION[$cCode]['main']['harga'] = 0;
                        $_SESSION[$cCode]['out_master']['harga'] = 0;

                        /*
                         * akumulasi item ke main
                         * */
                        foreach ($_SESSION[$cCode]['items'] as $id => $iSpec) {
                            $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                            $_SESSION[$cCode]['out_master']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                        }

                        /* ----------------------------------------------------------
                         * diskon-diskonan-grosir
                         * ----------------------------------------------------------*/
                        $tmp = $_SESSION[$cCode]['items'][$id];

                        $pro_premi = $row->premi_jual;
                        $pro_harga = $tmp['harga_list'] + (($pro_premi / 100) * $tmp['harga_list']);
//                        $pro_harga = $tmp['jual'] + (($pro_premi / 100) * $tmp['jual']);
                        $pro_jml = $tmp['qty_unit'];
                        $calc_hasil = $this->selectorDiskon($id, $pro_harga, $pro_jml);

                        $tmp['discPersen'] = $calc_hasil['persen'];
                        $tmp['harga_disc'] = $calc_hasil['harga_af'];
                        $tmp['lastNett'] = $calc_hasil['harga_af'];
                        $tmp['harga'] = $calc_hasil['harga_af'];
                        $tmp['harga_jual'] = $calc_hasil['harga_be'];
                        $tmp['discNilai'] = $calc_hasil['nilai'];

                        $_SESSION[$cCode]['items'][$produk_id] = $tmp;

                    }
                }
                else {
                    cekMerah("tidak ada itemnya!");
                    die();
                }
            }
        }
        if (sizeof($arrTrID) > 0) {
            $_SESSION[$cCode]['main']['references'] = $arrTrID;
//            $_SESSION[$cCode]['out_master']['references'] = $arrTrID;
        }

        if (isset($_GET['singleRefID']) && strlen($_GET['singleRefID']) > 0) {
            $_SESSION[$cCode]['main']['singleReference'] = $_GET['singleRefID'];
//            $_SESSION[$cCode]['out_master']['singleReference'] = $_GET['singleRefID'];
        }
        mati_disini(__FILE__ . __LINE__);
        $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" => isset($stepNum) ? $stepNum : ($stepNum = 0),
            "stepCode" => isset($this->configUiJenis['steps'][$stepNum]['target']) ? $this->configUiJenis['steps'][$stepNum]['target'] : 0,
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            "ppnFactor" => my_ppn_factor(),
        );

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

        echo "<script>";
        echo "  if(top.document.getElementById('shopping_cart')){";
        echo "  top.$('#shopping_cart').load('" . base_url() . $this->modul . "/_shoppingCart/viewCart/" . $this->jenisTr . "?selID=$idss');";
        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();
        $stepNum = $this->uri->segment(5) > 0 ? $this->uri->segment(5) : 1;

        //detect items
        //klo sisa 1 ya abis, hrus reset session
        if( count($_SESSION[$cCode]['items']) == 1 ){
            echo "<script>";
            echo "top.$('#result').load('" . base_url() . $this->modul . "/_shoppingCart/reset/".$this->jenisTr."');";
//            echo "console.log('" . base_url() . $this->modul . "/_shoppingCart/reset/".$this->jenisTr."');";
            echo "</script>";
            die();
        }

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


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

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

        $f_selector = "";
        if (isset($_GET['selector'])) {
            $f_selector = "selector&";
        }

        $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" => isset($this->configUiJenis['steps'][1]['target']) ? $this->configUiJenis['steps'][1]['target'] : 0,
            "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);

        if (isset($_GET['mb'])) {
            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>";
        }
        else {

            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()
    {
        echo "---------------------------your input params needed------------------------------";
        arrprint($_POST);
        $cCode = "_TR_" . $this->jenisTr;
        //        $rawParam = $_POST['param'];
        //        arrPrint($rawParam);
        //        arrPrint($cCode);
        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 selectNoQty()
    {
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        $id = $_GET['id'];
        $jml = isset($_GET['jml']) ? $_GET['jml'] : 1;
        $stepNum = $this->uri->segment(5) > 0 ? $this->uri->segment(5) : 1;

        $cCode = $this->cCode;

        $selectorModel = isset($_SESSION[$cCode]['main']['pihakMdlName']) ? $_SESSION[$cCode]['main']['pihakMdlName'] : $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = isset($_SESSION[$cCode]['main']['pihakMdlName']) ? $_SESSION[$cCode]['main']['pihakMdlName'] : $this->configUi[$this->jenisTr]['selectorSrcModel'];

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


        $priceSrcConfig = $this->config->item('hePrices') != null ? $this->config->item('hePrices') : array();
        $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;
        $connectedDiscountConfig = isset($this->configUi[$this->jenisTr]['connectedDiscount']) ? $this->configUi[$this->jenisTr]['connectedDiscount'] : array();
        $priceFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter']) ? $this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter'] : array();
        $resetFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $validateMeasurement = isset($this->configUi[$this->jenisTr]['validateMeasurement'][1]) ? $this->configUi[$this->jenisTr]['validateMeasurement'][1] : array();


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

        if (sizeof($tmpB) > 0) {
            foreach ($tmpB as $row) {
                $rows = $row;
                $valValidate_items = array();
                if (sizeof($validateMeasurement) > 0) {
                    $iValidate = 0;
                    foreach ($validateMeasurement as $keyVal => $validateKol) {
                        $valValidate = $row->$keyVal;
                        if ($valValidate == 0) {
                            $msg = "<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr><br><red class='text-red'>$validateKol = $valValidate </red><br>silahkan hubungi bagian entry data untuk melengkapi data produk";
                            $alerts = array(
                                "type" => "warning",
                                "title" => strtoupper("Data ukuran produk belum lengkap "),
                                "html" => $msg,
                            );
                            echo swalAlert($alerts);
                            die($msg);
                        }
                    }

                }


                if (sizeof($valValidate_items) > 0) {
                    //                    arrPrint($valValidate_items);
                    $msg = "Data pendukung produk belum lengkap<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr>$jml_now $satuan stock available";
                    $alerts = array(
                        "type" => "warning",
                        "title" => strtoupper($kode),
                        "html" => $msg,
                    );
                    echo swalAlert($alerts);
                    die($msg);
                }
                $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                $tmpJml = 1;
                if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {
                    $mdlName = $lockerConfig['mdlName'];

                    cekMerah("masuk locker config $mdlName");

                    $this->load->model("Mdls/" . $mdlName);
                    $c = new $mdlName();
                    $c->addFilter("produk_id='$id'");
                    //                    $c->addFilter("id='$id'");//==id locker
                    $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=" . my_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);
                        // arrPrint($row);
                        $kode = $row->kode;
                        foreach ($tmpC as $row) {
                            $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                            $nama = $row->nama;

                            $jml_now = $row->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>";
                                $msg = "Insufficient stock of:<br><red class='text-red'>$kode $nama</red><hr>$jml_now $satuan stock available";
                                $alerts = array(
                                    "type" => "warning",
                                    "title" => strtoupper($kode),
                                    "html" => $msg,
                                );
                                echo swalAlert($alerts);
                                die($msg);

                            }
                            //  endregion validasi stok


                            $this->db->trans_start();

                            //  region update locker active
                            $where = array(
                                "id" => $row->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']);
                            //                            arrPrint($array_hold_sebelumnya);
                            //                            mati_disini();
                            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" => $row->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'],
                                );
                                $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 " . $row->nama . " di locker stock.");
                    }

                }


                if (sizeof($connectedDiscountConfig) > 0) {
                    if ($connectedDiscountConfig['enabled'] == 1) {
                        $mdlNameRelation = $connectedDiscountConfig['mdlNameRelation'];
                        $mdlNameSource = $connectedDiscountConfig['mdlNameSource'];

                        $this->load->model("Mdls/" . $mdlNameRelation);
                        $dr = new $mdlNameRelation();
                        $dr->addFilter("produk_id='$id'");
                        $dr->addFilter("status='1'");
                        $dr->addFilter("toko_id=" . my_toko_id());
                        $tmpDr = $dr->lookupAll($id)->result();
                        //                        cekMerah($this->db->last_query());
                        //                        arrPrint($tmpDr);
                        $produkQty = isset($_GET['jml']) ? $_GET['jml'] : $tmpJml;
                        foreach ($tmpDr as $drSpec) {
                            $this->load->model("Mdls/" . $mdlNameSource);
                            $sr = new $mdlNameSource();
                            $sr->addFilter("id='" . $drSpec->diskon_id . "'");
                            $sr->addFilter("status='1'");
                            $tmpSr = $sr->lookupAll($id)->result();
                            //                            cekBiru($this->db->last_query());
                            //                            arrPrint($tmpSr);
                            foreach ($tmpSr as $srSpec) {
                                arrPrint($srSpec);
                                if ($produkQty > $srSpec->max_qty) {
                                    $discountPersen = $srSpec->discount_persen;
                                    $discountQty = $srSpec->discount_qty;
                                }
                                elseif (($produkQty >= $srSpec->min_qty) && ($produkQty <= $srSpec->max_qty)) {
                                    $discountPersen = $srSpec->discount_persen;
                                    $discountQty = $srSpec->discount_qty;
                                }
                                else {
                                    $discountPersen = 0;
                                    $discountQty = 0;
                                }
                                $arrDiscount[$id] = array(
                                    "persen" => $discountPersen,
                                    "qty" => $discountQty,
                                );
                                cekMerah("pID: $id ::: persen: $discountPersen ::: qty: $discountQty");
                            }
                        }
                    }
                }


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

                if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $tmp = array(
                        "handler" => $this->modul . "/" . $this->uri->segment(2),
                        "id" => $id,
                        "jml" => $tmpJml,
                        "harga" => 0,
                        "subtotal" => 0,
                        "satuan" => strlen($rows->satuan) > 0 ? $rows->satuan : "n/a",
                        "discount_persen" => isset($arrDiscount[$id]['persen']) ? $arrDiscount[$id]['persen'] : 0,
                        "discount_qty" => isset($arrDiscount[$id]['qty']) ? $arrDiscount[$id]['qty'] : 0,
                    );


                    if (sizeof($priceConfig) > 0) {
                        $mdlName = $priceConfig['model'];
                        $this->load->model("Mdls/" . $mdlName);
                        $h = new $mdlName();

                        if (isset($resetFilter['resetFilter']) && $resetFilter['resetFilter'] == true) {
                            $h->addFilter("produk_id='$id'");
                            // $h->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                            $h->addFilter("toko_id=" . my_toko_id());
                        }
                        else {
                            $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']);
                            $h->addFilter("toko_id=" . my_toko_id());
                        }

                        cekKuning("masukkk pak eko");
                        if (sizeof($priceFilter) > 0) {
                            foreach ($priceFilter as $f) {
                                $f_ex = explode("=", $f);
                                if (!isset($f_ex[1])) {
                                    $f_ey = explode(">", $f_ex[0]);
                                    if (substr($f_ey[1], 0, 1) == ".") {
                                        $h->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                                    }
                                    else {
                                        if (isset($_SESSION[$cCode]['main'][$f_ey[1]])) {
                                            $h->addFilter($f_ey[0] . ">'" . $_SESSION[$cCode]['main'][$f_ey[1]] . "'");
                                        }
                                        else {
                                            $h->addFilter($f_ey[0] . ">0");
                                        }
                                    }
                                }
                                else {
                                    if (substr($f_ex[1], 0, 1) == ".") {
                                        $h->addFilter($f_ex[0] . "='" . ltrim($f_ex[1], ".") . "'");
                                    }
                                    else {
                                        if (isset($_SESSION[$cCode]['main'][$f_ex[1]])) {
                                            $h->addFilter($f_ex[0] . "='" . $_SESSION[$cCode]['main'][$f_ex[1]] . "'");
                                        }
                                        else {
                                            $h->addFilter($f_ex[0] . "=''");
                                        }

                                    }
                                }
                            }
                        }


                        $tmpH = $h->lookupAll($id)->result();
                        //                        cekmerah($this->db->last_query());
                        //                        matiHere();
                        if (sizeof($tmpH) > 0) {
                            $rawPrices = array();
                            foreach ($tmpH as $hSpec) {
                                foreach ($priceConfig['key_label'] as $key => $val) {

                                    cekHitam($key);
                                    if ($resetFilter['resetFilter']) {
                                        cekBiru("sino$key ||" . $hSpec->$key);
                                        //                                        if ($key == $hSpec->h) {
                                        //                                            cekLime($hSpec->$key);
                                        $rawPrices[$key] = isset($hSpec->$key) ? $hSpec->$key : 0;
                                        //                                        }
                                    }
                                    else {
                                        cekBiru("sini");
                                        if ($key == $hSpec->jenis_value) {
                                            $rawPrices[$key] = isset($hSpec->nilai) ? $hSpec->nilai : 0;
                                        }
                                    }

                                }

                            }
                            //                            arrPrint($rawPrices);
                            $prices = normalizePrices("produk", $rawPrices);
                            if (sizeof($prices) > 0) {
                                foreach ($prices as $k => $v) {
                                    $tmp[$k] = $v;
                                }
                                $tmp['harga'] = isset($tmp[$priceConfig['mainSrc']]) ? $tmp[$priceConfig['mainSrc']] : 0;
                            }
                        }

                    }


                    foreach ($fieldSrcs as $key => $src) {
                        cekUngu(":: $key => $src ::");
                        //                        $tmp[$key] = makeValue($src, $_SESSION[$cCode]['items'][$id], $tmp, $tmpB[0]->$src);
                        $tmp[$key] = makeValue($src, $tmp, $tmp, isset($rows->$src) ? $rows->$src : 0);
                    }

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

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


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

                }
                else {

                    if (isset($_GET['newQty'])) {
                        //                        $_SESSION[$cCode]['items'][$id]['jml'] = $_GET['newQty'];
                        $_SESSION[$cCode]['items'][$id]['jml'] = $jml;
                        $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * ($_SESSION[$cCode]['items'][$id]['harga'] + $_SESSION[$cCode]['items'][$id]['ppn']));
                    }
                    else {
                        $_SESSION[$cCode]['items'][$id]['jml'] = $jml;
                        $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * ($_SESSION[$cCode]['items'][$id]['harga'] + $_SESSION[$cCode]['items'][$id]['ppn']));
                    }


                    if (isset($_GET['qty_opname'])) {
                        $_SESSION[$cCode]['items'][$id]['qty_opname'] = $_GET['qty_opname'];
                        $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * ($_SESSION[$cCode]['items'][$id]['harga'] + $_SESSION[$cCode]['items'][$id]['ppn']));

                        $selisih = $_GET['qty_opname'] - $_SESSION[$cCode]['items'][$id]['stok'];
                        if ($selisih > 0) {
                            $_SESSION[$cCode]['items'][$id]['qty_debet'] = $selisih;
                            $_SESSION[$cCode]['items'][$id]['qty_kredit'] = 0;
                            $_SESSION[$cCode]['items'][$id]['debet'] = $selisih * $_SESSION[$cCode]['items'][$id]['harga'];
                            $_SESSION[$cCode]['items'][$id]['kredit'] = 0;
                        }
                        elseif ($selisih < 0) {
                            $_SESSION[$cCode]['items'][$id]['qty_debet'] = 0;
                            $_SESSION[$cCode]['items'][$id]['qty_kredit'] = ($selisih * -1);
                            $_SESSION[$cCode]['items'][$id]['debet'] = 0;
                            $_SESSION[$cCode]['items'][$id]['kredit'] = ($selisih * -1) * $_SESSION[$cCode]['items'][$id]['harga'];
                        }
                        else {
                            $_SESSION[$cCode]['items'][$id]['qty_debet'] = 0;
                            $_SESSION[$cCode]['items'][$id]['qty_kredit'] = 0;
                            $_SESSION[$cCode]['items'][$id]['debet'] = 0;
                            $_SESSION[$cCode]['items'][$id]['kredit'] = 0;
                        }
                        $_SESSION[$cCode]['items'][$id]['qty_selisih'] = $selisih;
                    }


                    if (isset($arrDiscount[$id]) && sizeof($arrDiscount[$id]) > 0) {
                        foreach ($arrDiscount[$id] as $dKey => $dVal) {
                            if (!isset($_SESSION[$cCode]['items'][$id]['discount_' . $dKey])) {
                                $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = 0;
                            }
                            $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = $dVal;
                        }
                    }


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

                        }


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


                }
            }

        }
        else {
            cekMerah("tidak ada itemnya!");
            die();
        }


        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $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" => isset($this->configUiJenis['steps'][1]['target']) ? $this->configUiJenis['steps'][1]['target'] : 0,
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
            // "jenis_pajak"=>$this->session->login['jenis_usaha'],
        );
        $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

        /* --------------------------------------------------
         * ngereload shoping cart dlm modul
         * --------------------------------------------------*/
        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>";

    }

    //tambahan selector satuan
    public function selectFactorSatuan()
    {
        $cCode = $this->cCode;
        arrPrint($_GET);
        // arrPrint($this->uri->segment_array());
        $this->load->model("Mdls/MdlProdukSatuanRelasi");
        $p = new MdlProdukSatuanRelasi();
        $id = isset($_GET['id']) ? $_GET['id'] : "0";
        $stepNum = $this->uri->segment(5) > 0 ? $this->uri->segment(5) : 1;
        $pID = $produk_id = $_GET['pid'];
        $kID = $_GET['key'];
        $kValue = $_GET['value'];
        $qparams = blobDecode($_GET["qparams"]);
        // arrPrint($qparams);
        // arrPrint($_GET);
        // matiHere();
        // arrprint($_SESSION[$cCode]["items3"]);

        $p->addFilter("toko_id='" . my_toko_id() . "'");
        $p->addFilter("produk_id='$pID'");
        $p->addFilter("$kID='$kValue'");
        $p->setTokoId(my_toko_id());
        $temp = $p->lookUpRelasiSatuan($pID);

        $toUpDate = array();
        foreach ($temp[$pID] as $temp_0) {
            if ($temp_0[$kID] == $kValue) {
                foreach ($qparams as $src => $srcTarget) {
                    $toUpDate[$srcTarget] = $temp_0[$src];
                }
            }
        }

        foreach ($toUpDate as $key => $values) {
            $_SESSION[$cCode]["items"][$pID][$key] = $values;
        }

        $selectorModel = isset($_SESSION[$cCode]['main']['pihakMdlName']) ? $_SESSION[$cCode]['main']['pihakMdlName'] : $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = isset($_SESSION[$cCode]['main']['pihakMdlNameSrc']) ? $_SESSION[$cCode]['main']['pihakMdlNameSrc'] : $this->configUi[$this->jenisTr]['selectorSrcModel'];

        // detektor tanda kurawal {}
        if (substr($selectorModel, 0, 1) == "{") {
            $selectorModel = trim($selectorModel, "{");
            $selectorModel = trim($selectorModel, "}");
            $selectorModel = str_replace($selectorModel, $_SESSION[$cCode]['main'][$selectorModel], $selectorModel);
        }
        else {
            cekkuning("TIDAK mengandung kurawal @" . __LINE__ . __CLASS__);
        }
        if (substr($selectorSrcModel, 0, 1) == "{") {
            $selectorSrcModel = trim($selectorSrcModel, "{");
            $selectorSrcModel = trim($selectorSrcModel, "}");
            $selectorSrcModel = str_replace($selectorSrcModel, $_SESSION[$cCode]['main'][$selectorSrcModel], $selectorSrcModel);
        }
        else {
            cekkuning("TIDAK mengandung kurawal @" . __LINE__ . " " . __METHOD__);
        }

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

        $tmpB = $b->lookupByID($pID)->result();
        showLast_query("lime");

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

                /* ----------------------------------------------------------
                 * diskon-diskonan-grosir
                 * ----------------------------------------------------------*/
                $tmp = $_SESSION[$cCode]['items'][$pID];
                $pro_premi = $row->premi_jual;
                $pro_harga = $tmp['harga_list'] + (($pro_premi / 100) * $tmp['harga_list']);
//                $pro_harga = $tmp['jual'] + (($pro_premi / 100) * $tmp['jual']);

                cekBiru("$pro_premi || $pro_harga");

                $pro_jml = $tmp['jml'];
                $calc_hasil = $this->selectorDiskon($pID, $pro_harga, $pro_jml);

                arrPrintKuning($calc_hasil);

                $tmp['discPersen']  = $calc_hasil['persen'];
                $tmp['harga_disc']  = $calc_hasil['harga_af']*$tmp['satuan_factor_qty'];
                $tmp['lastNett']    = $calc_hasil['harga_af'];
                $tmp['harga']       = $calc_hasil['harga_af'];
                $tmp['harga_jual']  = $calc_hasil['harga_be']*$tmp['satuan_factor_qty'];
                $tmp['discNilai']   = $calc_hasil['nilai'];
                $tmp['id']          = $pID;

//                $tmp['bayar'] = 0; //reset bayar

                $tmp['subtotal'] = $calc_hasil['harga_af']*$pro_jml;

                // arrPrintPink($_SESSION[$cCode]['items'], __LINE__ . " " . __METHOD__);

//                cekMerah("hasil update + diskon sbb:");
//                arrPrintWebs($tmp);


                $_SESSION[$cCode]['items'][$produk_id] = $tmp;
                // matiHere(__METHOD__ . __LINE__);

            }
        }


        $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());
        if (isset($_GET['spc'])) {
            // matiHEre(__LINE__." file ".__FILE__);
            $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'][$stepNum]['target'],
                "jenisTrName" => $this->configUiJenis['steps'][$stepNum]['label'],
                "stepNumber" => $stepNum,
                "stepCode" => $this->configUiJenis['steps'][$stepNum]['target'],
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow("Y-m-d"),
                // "jenis_pajak"=>$this->session->login['jenis_usaha'],
            );
            // $vg->buildValue($this->jenisTr, $id, $initMasterValues, $configUiJenis);
            $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);


            // matiHere(__METHOD__ . __LINE__);
            /* --------------------------------------------------
             * ngereload shoping cart dlm modul
             * --------------------------------------------------*/
            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 "if(top.document.getElementById('shopping_cart')){
                    localStorage.setItem('loadShoppingCart', 10);
                    top.$('#btn_kalkulasi').removeClass('hidden');
                  }";
            echo "</script>";

            // echo "<script>";
            // echo "top.document.getElementById('result').src='" . base_url() . $this->modul . "/_shoppingCart/viewCart/" . $this->jenisTr . "?" . $f_selector . "selID=$id';";
            // echo "top.load_shoppingcart();";
            // echo "</script>";
        }
        else {
            $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'][$stepNum]['target'],
                "jenisTrName" => $this->configUiJenis['steps'][$stepNum]['label'],
                "stepNumber" => $stepNum,
                "stepCode" => $this->configUiJenis['steps'][$stepNum]['target'],
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow("Y-m-d"),
                // "jenis_pajak"=>$this->session->login['jenis_usaha'],
            );
            // $vg->buildValue($this->jenisTr, $id, $initMasterValues, $configUiJenis);
            $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);
            // arrPrintKuning($_SESSION[$cCode]['items']);

            /* --------------------------------------------------
             * ngereload shoping cart dlm modul
             * --------------------------------------------------*/
            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>";
        }
    }

    private function selectorDiskon($produk_id, $produk_harga, $produk_jml, $grosir = "")
    {

        // cekHitam("produk_id $produk_id || tokid " . my_toko_id());
        $this->load->library("Diskon");
        $dp = new Diskon();
        $dp->setTokoId(my_toko_id());
        $src_diskon = $dp->CallProdukDiskon($produk_id);

        // arrPrintHijau($src_diskon);
        // diskon

        $pro_harga = $produk_harga * 1;
        $pro_jml = $produk_jml;

        // cekPink("$pro_harga || $pro_jml");
        /*---menentukan diskon pokok dari produk atau grosir----*/
        $d_pokok = isset($src_diskon['produk']) ? $src_diskon['produk'] : 0;

        $jml_spek_grosir = sizeof($src_diskon['grosir']);

        if ($jml_spek_grosir > 0) {
            $gro_count = 0;
            foreach ($src_diskon['grosir'] as $item) {
                $gro_count++;
                $gro_minim = $item['minim'];
                $gro_maxim = $gro_count == $jml_spek_grosir ? INF : $item['maxim'];
                $gro_persen = $item['persen'];
                if (($pro_jml >= $gro_minim) && ($pro_jml <= $gro_maxim)) {
                    $d_pokok = $gro_persen;
                    break;
                }
            }
        }
        else {
            // $d_pokok = isset($src_diskon['produk']) ? $src_diskon['produk'] : 0;
        }

        //=============== FREE PRODUK ===============
        $p_pokok = array();
        $jml_spek_free = sizeof($src_diskon['freeproduk']);

        if ($jml_spek_free > 0) {
            foreach ($src_diskon['freeproduk'] as $item) {

                $buy_minim = $item['minim'];
                $buy_maxim = $item['maxim'];
                $buy_kelipatan = $item['kelipatan'];
                $quota_used = $item['quota_used'];
                $quota_global = $item['quota_global'];
                $quota_sisa = isset($item['quota_global']) && $item['quota_global']*1> 0 ? $item['quota_global'] : ($quota_global-$quota_used);

                if( $buy_kelipatan ){
                    if( $pro_jml>=$buy_minim ){
                        $lipatan = floor($pro_jml/$buy_minim);
                        $free_produk_qty = $item['free_produk_qty'] * $lipatan;

                        if( $quota_sisa < $free_produk_qty ){
                            $qty_reverse = ($free_produk_qty-$quota_sisa);
                            $free_qty_reverse = ($free_produk_qty - $qty_reverse);
                            $p_pokok = $item;
                            $p_pokok['free_qty'] = $free_qty_reverse;
                            $p_pokok['produk_beli_jml'] = $pro_jml;
                            $p_pokok['free_produk_notif'] = " ini notif";
//                            cekOrange("quota_sisa: $quota_sisa || free_produk_qty: $free_produk_qty");
//                            cekOrange("qty_reverse: $free_qty_reverse");
//                            matiHere('LINE: ' . __LINE__);
                        }
                        else{
                            $p_pokok = $item;
                            $p_pokok['free_qty'] = $free_produk_qty;
                            $p_pokok['produk_beli_jml'] = $pro_jml;
//                            matiHere('LINE: ' . __LINE__);
                        }

                        break;
                    }
                }
                else{
                    if(($pro_jml>=$buy_minim)){

                        if( $quota_sisa >= $item['free_produk_qty'] ){
                            $p_pokok = $item;
                            $p_pokok['free_qty'] = $item['free_produk_qty'];
                            $p_pokok['produk_beli_jml'] = $pro_jml;
//                            matiHere('LINE: ' . __LINE__);
                        }
                        else{

                            cekHere("quota_global: $quota_global");
                            cekHere("quota_used: $quota_used");
                            cekHere("quota_sisa: $quota_sisa");
                            cekHere("free_produk_qty: ".$item['free_produk_qty']);
                            matiHere('LINE: ' . __LINE__ . __FILE__);

                        }

                        break;
                    }
                }
            }
        }
        else {
            // $p_pokok = isset($src_diskon['freeproduk']) ? $src_diskon['freeproduk'] : array();
//            matiHere('LINE: ' . __LINE__);
        }

        $d_pokok_00 = $grosir == 0 ? 0 : $d_pokok;

        cekHere("$d_pokok_00 || $grosir");

        $diskon_pokok["produk"] = $d_pokok_00;
        $diskon_event = array();
        $diskon_free_produk['note_free_produk'] = isset($src_diskon['freeproduk']) ? $src_diskon['freeproduk'] : array();
        $diskon_free_produk['free_produk'] = $p_pokok;

        $calc_hasil = $dp->calcDiskon($pro_harga, $diskon_pokok, $diskon_event, $diskon_free_produk ,"diskon");

        return $calc_hasil;
    }

    private function selectorDiskonFreeProduk_gak_dipakai_cuuk($produk_id, $produk_harga, $produk_jml)
    {

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

        $d_pokok = isset($src_diskon['produk']) ? $src_diskon['produk'] : array();

        $pro_harga = $produk_harga * 1;
        $pro_jml = $produk_jml;
        $jml_spek_free = sizeof($src_diskon['freeproduk']);

        if ($jml_spek_free > 0) {
            foreach ($src_diskon['freeproduk'] as $item) {
                $buy_minim = $item['minim'];
                $buy_maxim = $item['maxim'];
                if(($pro_jml>=$buy_minim)&&($pro_jml<=$buy_maxim)){
                    $d_pokok = $item;
                    break;
                }
            }
        }
        else {
            // $d_pokok = isset($src_diskon['produk']) ? $src_diskon['produk'] : 0;
        }

        $diskon_pokok = array();
        $diskon_event = array();
        $diskon_free_produk['note_free_produk'] = isset($src_diskon['freeproduk']) ? $src_diskon['freeproduk'] : array();
        $diskon_free_produk['free_produk'] = $d_pokok;

        $calc_hasil = $dp->calcDiskon($pro_harga, $diskon_pokok, $diskon_event, $diskon_free_produk, "diskon");

        return $calc_hasil;
    }

    private function freeProdukQuota($nomer_diskon){
        if(empty($nomer_diskon)){
            die( swalToAlert('nomer diskon belum ditentukan') );
        }

    }

    public function selectReturn()
    {
// arrPrint($this->uri->segment_array());
// arrPrint($_GET);
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        $id = $produk_id = $_GET['id'];
        $jml = isset($_GET['jml']) ? $_GET['jml'] : 1;
        $stepNum = $this->uri->segment(5) > 0 ? $this->uri->segment(5) : 1;
        $qty_unit = isset($_GET['qty_unit']) ? $_GET['qty_unit'] : 1;
        $cCode = $this->cCode;
        $pihakID = $_SESSION[$cCode]["main"]["pihakID"];
        $selectorModel = isset($_SESSION[$cCode]['main']['pihakMdlName']) ? $_SESSION[$cCode]['main']['pihakMdlName'] : $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = isset($_SESSION[$cCode]['main']['pihakMdlNameSrc']) ? $_SESSION[$cCode]['main']['pihakMdlNameSrc'] : $this->configUi[$this->jenisTr]['selectorSrcModel'];

        // detektor tanda kurawal {}
        if (substr($selectorModel, 0, 1) == "{") {
            $selectorModel = trim($selectorModel, "{");
            $selectorModel = trim($selectorModel, "}");
            $selectorModel = str_replace($selectorModel, $_SESSION[$cCode]['main'][$selectorModel], $selectorModel);
        }
        else {
            cekkuning("TIDAK mengandung kurawal @" . __LINE__ . __CLASS__);
        }
        if (substr($selectorSrcModel, 0, 1) == "{") {
            $selectorSrcModel = trim($selectorSrcModel, "{");
            $selectorSrcModel = trim($selectorSrcModel, "}");
            $selectorSrcModel = str_replace($selectorSrcModel, $_SESSION[$cCode]['main'][$selectorSrcModel], $selectorSrcModel);
        }
        else {
            cekkuning("TIDAK mengandung kurawal @" . __LINE__ . " " . __METHOD__);
        }


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


        $priceSrcConfig = $this->config->item('hePrices') != null ? $this->config->item('hePrices') : array();
        $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();
        $priceMainConfig = isset($this->configUi[$this->jenisTr]['selectedMainPrice']) ? $this->configUi[$this->jenisTr]['selectedMainPrice'] : 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;
        $connectedDiscountConfig = isset($this->configUi[$this->jenisTr]['connectedDiscount']) ? $this->configUi[$this->jenisTr]['connectedDiscount'] : array();
        $priceFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter']) ? $this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter'] : array();
        $resetFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
        $validateMeasurement = isset($this->configUi[$this->jenisTr]['validateMeasurement'][1]) ? $this->configUi[$this->jenisTr]['validateMeasurement'][1] : array();
        $shopingCartItemOptionFields = isset($this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][1]) ? $this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][1] : array();
        $valueGateConfig = isset($this->configValues[$this->jenisTr]['detailInjectedValues']) ? $this->configValues[$this->jenisTr]['detailInjectedValues'] : array();
        $selectorProcessorParam = isset($this->configUi[$this->jenisTr]['selectorProcessorParam']) ? $this->configUi[$this->jenisTr]['selectorProcessorParam'] : array();
        $tmpB = $b->lookupByID($id)->result();
        // showLast_query("lime");
        // matiHere(__LINE__ . " " .__METHOD__);

        if (sizeof($tmpB) > 0) {
            foreach ($tmpB as $row) {
                $rows = $row;
                $valValidate_items = array();

                if (sizeof($validateMeasurement) > 0) {
                    $iValidate = 0;
                    foreach ($validateMeasurement as $keyVal => $validateKol) {
                        $valValidate = $row->$keyVal;
                        if ($valValidate == 0) {
                            $msg = "<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr><br><red class='text-red'>$validateKol = $valValidate </red><br>silahkan hubungi bagian entry data untuk melengkapi data produk";
                            $alerts = array(
                                "type" => "warning",
                                "title" => strtoupper("Data ukuran produk belum lengkap "),
                                "html" => $msg,
                            );
                            echo swalAlert($alerts);
                            die($msg);
                        }
                    }

                }

                if (sizeof($valValidate_items) > 0) {
                    //                    arrPrint($valValidate_items);
                    $msg = "Data pendukung produk belum lengkap<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr>$jml_now $satuan stock available";
                    $alerts = array(
                        "type" => "warning",
                        "title" => strtoupper($kode),
                        "html" => $msg,
                    );
                    echo swalAlert($alerts);
                    die($msg);
                }

                $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";

                $tmpJml = 1;


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

                /* ----------------------------------------------------------------
                 * inisisasi cCode Items
                 * untuk harga ambil dari stock_locker_penjualan_cache degnan index custtomerid dan produk id
                 * ----------------------------------------------------------------*/
                if (!isset($_SESSION[$cCode]['items']) || !array_key_exists($id, $_SESSION[$cCode]['items'])) {
                    $tmp = array(
                        "handler" => $this->modul . "/" . $this->uri->segment(2),
                        "id" => $id,
                        "jml" => $tmpJml,
                        "qty_unit" => $qty_unit,
                        "harga" => 0,
                        "subtotal" => 0,
                        "satuan" => strlen($rows->satuan) > 0 ? $rows->satuan : "n/a",
                        "discount_persen" => isset($arrDiscount[$id]['persen']) ? $arrDiscount[$id]['persen'] : 0,
                        "discount_qty" => isset($arrDiscount[$id]['qty']) ? $arrDiscount[$id]['qty'] : 0,
                    );

                    if (sizeof($priceMainConfig) > 0) {
                        if (isset($priceMainConfig[$_SESSION[$cCode]['main']['pihakMainName']])) {
                            $priceConfig = $priceMainConfig[$_SESSION[$cCode]['main']['pihakMainName']];
                            cekUngu("masuk disini...");
                        }
                    }
                    cekBiru(__LINE__);
                    /*
                     * pengganti price config
                     */
                    $this->load->model("Mdls/MdlLockerStockPenjualanCache");
                    $pr = new MdlLockerStockPenjualanCache();
                    $pr->addFilter("extern_id='$id'");
                    $pr->addFilter("extern2_id='$pihakID'");
                    $tmpLocker = $pr->lookUpAll()->result();
                    if (sizeof($tmpLocker) > 0) {
                        foreach ($tmpLocker as $tmpLocker_0) {
                            foreach ($selectorProcessorParam as $key_tbl => $key_target) {
                                $tmp[$key_target] = $tmpLocker_0->$key_tbl;
                            }
                        }
                    }

//                    arrPrint($tmpLocker);
//                    arrPrint($selectorProcessorParam);


                    // if (sizeof($priceConfig) > 0) {
                    //     $mdlName = $priceConfig['model'];
                    //     $this->load->model("Mdls/" . $mdlName);
                    //     $h = new $mdlName();
                    //     if (isset($resetFilter['resetFilter']) && $resetFilter['resetFilter'] == true) {
                    //         $h->addFilter("produk_id='$id'");
                    //         // $h->addFilter("cabang_id=" . $this->session->login['cabang_id']);
                    //         // $h->addFilter("toko_id=" . my_toko_id());
                    //     }
                    //     else {
                    //         $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']);
                    //         // $h->addFilter("toko_id=" . my_toko_id());
                    //     }
                    //
                    //     if (sizeof($priceFilter) > 0) {
                    //         foreach ($priceFilter as $f) {
                    //             $f_ex = explode("=", $f);
                    //             if (!isset($f_ex[1])) {
                    //                 $f_ey = explode(">", $f_ex[0]);
                    //                 if (substr($f_ey[1], 0, 1) == ".") {
                    //                     $h->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                    //                 }
                    //                 else {
                    //                     if (isset($_SESSION[$cCode]['main'][$f_ey[1]])) {
                    //                         $h->addFilter($f_ey[0] . ">'" . $_SESSION[$cCode]['main'][$f_ey[1]] . "'");
                    //                     }
                    //                     else {
                    //                         $h->addFilter($f_ey[0] . ">0");
                    //                     }
                    //                 }
                    //             }
                    //             else {
                    //                 if (substr($f_ex[1], 0, 1) == ".") {
                    //                     $h->addFilter($f_ex[0] . "='" . ltrim($f_ex[1], ".") . "'");
                    //                 }
                    //                 else {
                    //                     if (isset($_SESSION[$cCode]['main'][$f_ex[1]])) {
                    //                         $h->addFilter($f_ex[0] . "='" . $_SESSION[$cCode]['main'][$f_ex[1]] . "'");
                    //                     }
                    //                     else {
                    //                         $h->addFilter($f_ex[0] . "=''");
                    //                     }
                    //
                    //                 }
                    //             }
                    //         }
                    //     }
                    //     $tmpH = $h->lookupAll($id)->result();
                    //     // showLast_query("kuning");
                    //
                    //     if (sizeof($tmpH) > 0) {
                    //         $rawPrices = array();
                    //         foreach ($tmpH as $hSpec) {
                    //             foreach ($priceConfig['key_label'] as $key => $val) {
                    //                 //                                    cekHitam($key);
                    //                 if (isset($resetFilter['resetFilter'])) {
                    //                     cekBiru("sino$key ||" . $hSpec->$key);
                    //                     //                                        if ($key == $hSpec->h) {
                    //                     //                                            cekLime($hSpec->$key);
                    //                     $rawPrices[$key] = isset($hSpec->$key) ? $hSpec->$key : 0;
                    //                     //                                        }
                    //                 }
                    //                 else {
                    //                     cekBiru("sini " . __LINE__);
                    //                     if ($key == $hSpec->jenis_value) {
                    //                         $rawPrices[$key] = isset($hSpec->nilai) ? $hSpec->nilai : 0;
                    //                     }
                    //                 }
                    //
                    //             }
                    //
                    //         }
                    //         $prices = normalizePrices("produk", $rawPrices);
                    //         if (sizeof($prices) > 0) {
                    //             foreach ($prices as $k => $v) {
                    //                 $tmp[$k] = $v;
                    //             }
                    //             // $tmp['harga'] = isset($tmp[$priceConfig['mainSrc']]) ? $tmp[$priceConfig['mainSrc']] : 0;
                    //         }
                    //     }
                    //
                    // }
                    //------------------------------------------------------
                    // arrPrint( $fieldSrcs);
                    foreach ($fieldSrcs as $key => $src) {
                        if (is_array($src) && sizeof($src) > 0) {
                            foreach ($src as $srcSpec) {
                                if (isset($tmp[$srcSpec]) || isset($rows->$srcSpec)) {
                                    // cekBiru("ambil gerbang key -> $srcSpec");
                                    $tmp[$key] = makeValue($srcSpec, $tmp, $tmp, isset($rows->$srcSpec) ? $rows->$srcSpec : 0);
                                }
                            }
                        }
                        else {
                            $tmp[$key] = makeValue($src, $tmp, $tmp, isset($rows->$src) ? $rows->$src : 0);
                            //                            cekHere("hasilnya $key -> " . $tmp[$key]);
                        }
                    }

                    // matiHEre(__LINE__);

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


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

                    /*
                     * bagian option satuan
                     */
                    // arrPrint($shopingCartItemOptionFields);
                    //region sambungin ke relasi satuan
                    if (sizeof($shopingCartItemOptionFields) > 0) {
                        foreach ($shopingCartItemOptionFields as $keyIndex => $dataExtSatuan) {
                            $mdl = $dataExtSatuan["mdlName"];
                            // $field = $dataExtSatuan["selectField"];
                            $targetSes = $dataExtSatuan["targetSession"];
                            $methode = $dataExtSatuan["methode"];
                            $indexKey = $dataExtSatuan["keySrc"];
                            $this->load->model("Mdls/" . $mdl);
                            $mm = new $mdl();
                            $mm->setTokoId(my_toko_id());
                            $prevCon = $mm->$methode($id);
                            // arrprint($prevCon);
                            // matiHEre();
                            if (sizeof($prevCon) > 0) {
                                foreach ($prevCon[$id] as $prevCon_0) {
                                    foreach ($dataExtSatuan["usedFields"] as $src => $target) {
                                        if (!isset($_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target])) {
                                            // cekMerah($prevCon_0[$indexKey]."  $target =>".$prevCon_0[$src]);
                                            $_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target] = $prevCon_0[$src];
                                        }

                                    }
                                }
                            }
                        }
                    }
                    // matiHere();
                    $_SESSION[$cCode]['items'][$produk_id] = $tmp;
                    //endregion
                    // matiHEre(__LINE__);
                }
                else {
                    cekBiru("ada id $id tapi tidak ada cCode items @" . __LINE__);

                    //validasi stok
                    $stok_unit = $_SESSION[$cCode]['items'][$id]["stok"];
                    $newReq_qty = $_GET['newQty'] * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];

                    if ($newReq_qty <= $stok_unit) {
                        //skip boleh lanjut
                    }
                    else {
                        $errMsg = "Ditolak karena qty retur " . htmlspecialchars($_SESSION[$cCode]["items"][$id]["nama"]) . " melebihi total pembelian  dari konsumen (" . htmlspecialchars($_SESSION[$cCode]["items"][$id]["customerName"]) . ") Silahkan periksa kembali pemilihan satuan, maupun qty yang di minta";

                        $msg = "<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr><br><red class='text-red'>$validateKol = $valValidate </red><br>silahkan hubungi bagian entry data untuk melengkapi data produk";
                        $alerts = array(
                            "type" => "warning",
                            "title" => strtoupper("PERHATIAN"),
                            "html" => $errMsg,
                        );
                        echo swalAlert($alerts);
                        die($msg);
                    }

                    if (isset($_GET['newQty'])) {
                        // $_SESSION[$cCode]['items'][$id]['jml'] = $_GET['newQty'];
                        // $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * ($_SESSION[$cCode]['items'][$id]['harga'] + $_SESSION[$cCode]['items'][$id]['ppn']));
                        $_SESSION[$cCode]['items'][$id]['qty_unit'] = $_GET['newQty'];
                        $_SESSION[$cCode]['items'][$id]['jml'] = $_GET['newQty'] * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];

                    }
                    else {
                        // $_SESSION[$cCode]['items'][$id]['jml'] += $jml;
                        // $_SESSION[$cCode]['items'][$id]['subtotal'] = ($_SESSION[$cCode]['items'][$id]['jml'] * ($_SESSION[$cCode]['items'][$id]['harga'] + (isset($_SESSION[$cCode]['items'][$id]['ppn']) ? $_SESSION[$cCode]['items'][$id]['ppn'] : 0)));
                        if (($_SESSION[$cCode]['items'][$id]['qty_unit'] + $qty_unit) > $stok_unit) {
                            $_SESSION[$cCode]['items'][$id]['qty_unit'] = $stok_unit;
                            $_SESSION[$cCode]['items'][$id]['jml'] = $stok_unit * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];
                        }
                        else {
                            $_SESSION[$cCode]['items'][$id]['qty_unit'] += $qty_unit;
                            $_SESSION[$cCode]['items'][$id]['jml'] += $qty_unit * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];
                        }


                    }


                    // if (isset($arrDiscount[$id]) && sizeof($arrDiscount[$id]) > 0) {
                    //     foreach ($arrDiscount[$id] as $dKey => $dVal) {
                    //         if (!isset($_SESSION[$cCode]['items'][$id]['discount_' . $dKey])) {
                    //             $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = 0;
                    //         }
                    //         $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = $dVal;
                    //     }
                    // }

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

                        }


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


                }

                // matiHEre(__LINE__);
                /* ----------------------------------------------------------
                 * diskon-diskonan-grosir
                 * ----------------------------------------------------------*/
                // $tmp = $_SESSION[$cCode]['items'][$id];
                // $pro_premi = $row->premi_jual;
                // $pro_harga = $tmp['harga_list'] + (($pro_premi / 100) * $tmp['harga_list']);
                // $pro_harga = $tmp['jual'] + (($pro_premi / 100) * $tmp['jual']);
                // cekBiru("$pro_premi || $pro_harga");
                // $pro_jml = $tmp['jml'];
                // $calc_hasil = $this->selectorDiskon($id, $pro_harga, $pro_jml);
                // arrPrintKuning($calc_hasil);
                // $tmp['discPersen'] = $calc_hasil['persen'];
                // $tmp['harga_disc'] = $calc_hasil['harga_af'];
                // $tmp['lastNett'] = $calc_hasil['harga_af'];
                // $tmp['harga'] = $calc_hasil['harga_af'];
                // $tmp['harga_jual'] = $calc_hasil['harga_be'];
                // $tmp['discNilai'] = $calc_hasil['nilai'];
                // $tmp['id'] = $id;


                // $_SESSION[$cCode]['items'][$produk_id] = $tmp;// untuk return digeser ke builder session lihat !isset() <----

            }


        }
        else {
            cekMerah("tidak ada itemnya! @" . __LINE__ . " " . __METHOD__);
            die();
        }

        // arrPrint($_SESSION[$cCode]['items']);
        // mati_disini(__LINE__);
        $f_selector = "";
        if (isset($_GET['selector'])) {
            $f_selector = "selector&";
        }

        $this->load->library("ValueGate");
        $vg = new ValueGate();
        $vg->setConfigUiJenis($this->configUiJenis);
        $vg->setConfigCoreJenis($this->configCoreJenis);
        $vg->setConfigValuesJenis($this->configValuesJenis);
        $vg->setPpnFactor(my_ppn_factor());

        if (isset($_GET['mb'])) {
            mati_disini(__FILE__ . "<hr> @" . __LINE__);
            $initMaster = array(
                "olehID" => $this->session->login['id'],
                "olehName" => $this->session->login['nama'],
                "placeID" => $this->session->login['cabang_id'],
                "placeName" => $this->session->login['cabang_nama'],
                "divID" => isset($this->session->login['div_id']) ? $this->session->login['div_id'] : 0,
                "divName" => isset($this->session->login['div_nama']) ? $this->session->login['div_nama'] : 0,
                "cabangID" => $this->session->login['cabang_id'],
                "cabangName" => $this->session->login['cabang_nama'],
                "gudangID" => $this->session->login['gudang_id'],
                "gudangName" => $this->session->login['gudang_nama'],
                "jenis_usaha" => isset($this->session->login['jenis_usaha']) ? $this->session->login['jenis_usaha'] : '-',
                "jenisTr" => $this->jenisTr,
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $this->config->item('heTransaksi_ui')[$this->jenisTr]['steps'][1]['target'],
                "jenisTrName" => $this->jenisTrName,
                "stepNumber" => $stepNum,
                "stepCode" => $this->config->item('heTransaksi_ui')[$this->jenisTr]['steps'][$stepNum]['target'],
                "dtime" => date("Y-m-d H:i:s"),
                "fulldate" => date("Y-m-d"),
                // "jenis_pajak"=>$this->session->login['jenis_usaha'],
                "tokoID" => $this->session->login['toko_id'],
                "tokoNama" => $this->session->login['toko_nama'],
            );
            // hevalueGateInisisai($initMaster);
            echo "<script>";
            echo "top.document.getElementById('result').src='" . base_url() . "ValueGate/buildValues/" . $this->jenisTr . "?" . $f_selector . "selID=$id';";
            echo "top.load_shoppingcart();";
            echo "</script>";
        }
        else {
            $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" => $stepNum,
                "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, $configUiJenis);
            $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);
            // mati_disini(__FILE__ . "<hr> @" . __LINE__);
            // echo "<script>";
            // echo "top.document.getElementById('result').src='" . base_url() . "ValueGate/buildValues/" . $this->jenisTr . "?".$f_selector."selID=$id&modul=".$this->modul."';";
            // echo "</script>";

            // matiHere(__METHOD__ . __LINE__);
            /* --------------------------------------------------
             * ngereload shoping cart dlm modul
             * --------------------------------------------------*/
            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 autoSelect()
    {
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();
        $cCode = $this->cCode;

        $selectorModel = isset($_SESSION[$cCode]['main']['pihakMdlName']) ? $_SESSION[$cCode]['main']['pihakMdlName'] : $this->configUi[$this->jenisTr]['selectorModel'];
        $selectorSrcModel = isset($_SESSION[$cCode]['main']['pihakMdlNameSrc']) ? $_SESSION[$cCode]['main']['pihakMdlNameSrc'] : $this->configUi[$this->jenisTr]['selectorSrcModel'];

        $set_qty = isset($_GET['qty']) && $_GET['qty']!='' ? trim($_GET['qty']) : "";

        cekUngu("<form target='".$this->jenisTr."'>
        <label> masukan jml produk yang ingin di generate: <input value='$set_qty' placeholder='eg: 100' name='qty'></label>
        <button href='' type='submit'>GENERATE</button></form>");

        if( isset($_GET['qty']) ){
            $jml_produk_random = $set_qty;
            $tmpRand = $this->db->query("SELECT * FROM produk WHERE barcode!='' ORDER BY RAND() LIMIT $jml_produk_random");
            $randProduk = $tmpRand->result();

            foreach($randProduk as $ky => $row){

                $id = $produk_id = $row->id;
                $jml = rand(1,2);
                $stepNum = 1;
                $qty_unit = $jml;

                $barcodesatuan = isset($_GET['barcodesatuan']) ? $_GET['barcodesatuan'] : array();

                if (substr($selectorModel, 0, 1) == "{") {
                    $selectorModel = trim($selectorModel, "{");
                    $selectorModel = trim($selectorModel, "}");
                    $selectorModel = str_replace($selectorModel, $_SESSION[$cCode]['main'][$selectorModel], $selectorModel);
                }
                else {
//                    cekkuning("TIDAK mengandung kurawal @" . __LINE__ . __CLASS__);
                }
                if (substr($selectorSrcModel, 0, 1) == "{") {
                    $selectorSrcModel = trim($selectorSrcModel, "{");
                    $selectorSrcModel = trim($selectorSrcModel, "}");
                    $selectorSrcModel = str_replace($selectorSrcModel, $_SESSION[$cCode]['main'][$selectorSrcModel], $selectorSrcModel);
                }
                else {
//                    cekkuning("TIDAK mengandung kurawal @" . __LINE__ . " " . __METHOD__);
                }

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

                $priceSrcConfig = $this->config->item('hePrices') != null ? $this->config->item('hePrices') : array();
                $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();
                $priceMainConfig = isset($this->configUi[$this->jenisTr]['selectedMainPrice']) ? $this->configUi[$this->jenisTr]['selectedMainPrice'] : 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;
                $connectedDiscountConfig = isset($this->configUi[$this->jenisTr]['connectedDiscount']) ? $this->configUi[$this->jenisTr]['connectedDiscount'] : array();
                $priceFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter']) ? $this->configUi[$this->jenisTr]['selectedPrice']['mdlFilter'] : array();
                $resetFilter = isset($this->configUi[$this->jenisTr]['selectedPrice']) ? $this->configUi[$this->jenisTr]['selectedPrice'] : array();
                $validateMeasurement = isset($this->configUi[$this->jenisTr]['validateMeasurement'][1]) ? $this->configUi[$this->jenisTr]['validateMeasurement'][1] : array();
                $shopingCartItemOptionFields = isset($this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][1]) ? $this->configUi[$this->jenisTr]['shopingCartItemOptionFields'][1] : array();
                $valueGateConfig = isset($this->configValues[$this->jenisTr]['detailInjectedValues']) ? $this->configValues[$this->jenisTr]['detailInjectedValues'] : array();
                $autoCreateOrderId = isset($this->configUi[$this->jenisTr]['autoCreateOrderId']) ? $this->configUi[$this->jenisTr]['autoCreateOrderId'] : false;

                if($autoCreateOrderId){
                    if( !isset($_SESSION[$cCode]['main']['shoppingcart_order_id']) ){
                        $_SESSION[$cCode]['main']['shoppingcart_order_id'] = strtotime(date("Y-m-d H:i:s"));
                    }
                }

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

                if (sizeof($tmpB) > 0) {
                    foreach ($tmpB as $row) {
                        $rows = $row;
                        $valValidate_items = array();
                        if (sizeof($validateMeasurement) > 0) {
                            $iValidate = 0;
                            foreach ($validateMeasurement as $keyVal => $validateKol) {
                                $valValidate = $row->$keyVal;
                                if ($valValidate == 0) {
                                    $msg = "<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr><br><red class='text-red'>$validateKol = $valValidate </red><br>silahkan hubungi bagian entry data untuk melengkapi data produk";
                                    $alerts = array(
                                        "type" => "warning",
                                        "title" => strtoupper("Data ukuran produk belum lengkap "),
                                        "html" => $msg,
                                    );
                                    echo swalAlert($alerts);
                                    die($msg);
                                }
                            }
                        }
                        if (sizeof($valValidate_items) > 0) {
                            $msg = "Data pendukung produk belum lengkap<br><red class='text-red'>" . htmlspecialchars($row->kode) . " " . htmlspecialchars($row->nama) . "</red><hr>$jml_now $satuan stock available";
                            $alerts = array(
                                "type" => "warning",
                                "title" => strtoupper($kode),
                                "html" => $msg,
                            );
                            echo swalAlert($alerts);
                            die($msg);
                        }
                        $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                        $tmpJml = $qty_unit;
                        if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {
                            $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();
                            if (sizeof($tmpC) > 0) {
                                $kode = $row->kode;
                                foreach ($tmpC as $row) {
                                    $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                                    $nama = $row->nama;
                                    $jml_now = $row->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) {
                                        $msg = "Insufficient stock of:<br><red class='text-red'>$kode $nama</red><hr>$jml_now $satuan stock available";
                                        $alerts = array(
                                            "type" => "warning",
                                            "title" => strtoupper($kode),
                                            "html" => $msg,
                                        );
                                        echo swalAlert($alerts);
                                        die($msg);
                                    }
                                    //  endregion validasi stok

                                    $this->db->trans_start();

                                    //  region update locker active
                                    $where = array(
                                        "id" => $row->id,
                                    );
                                    $data_active = array(
                                        "jumlah" => $jml_now - $jml_nambah,
                                        "state" => "active",
                                    );
                                    $c->updateData($where, $data_active);
                                    //  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']);
                                    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);
                                    }
                                    else {
                                        $data_hold = array(
                                            "jenis" => "produk",
                                            "cabang_id" => $this->session->login['cabang_id'],
                                            "produk_id" => $id,
                                            "nama" => $nama,
                                            "satuan" => $row->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'],
                                        );
                                        $c->addData($data_hold);
                                    }
                                    //  endregion locker hold
                                    $this->db->trans_complete() or die("Gagal bro");
                                    $tmpJml = $jml_diperlukan;
                                }
                            }
                            else {
                                mati_disini("tidak ditemukan item " . $row->nama . " di locker stock.");
                            }
                        }
                        if (sizeof($connectedDiscountConfig) > 0) {
                            if ($connectedDiscountConfig['enabled'] == 1) {
                                $mdlNameRelation = $connectedDiscountConfig['mdlNameRelation'];
                                $mdlNameSource = $connectedDiscountConfig['mdlNameSource'];
                                $this->load->model("Mdls/" . $mdlNameRelation);
                                $dr = new $mdlNameRelation();
                                $dr->addFilter("produk_id='$id'");
                                $dr->addFilter("status='1'");
                                $tmpDr = $dr->lookupAll($id)->result();
                                $produkQty = isset($_GET['jml']) ? $_GET['jml'] : $tmpJml;
                                foreach ($tmpDr as $drSpec) {
                                    $this->load->model("Mdls/" . $mdlNameSource);
                                    $sr = new $mdlNameSource();
                                    $sr->addFilter("id='" . $drSpec->diskon_id . "'");
                                    $sr->addFilter("status='1'");
                                    $tmpSr = $sr->lookupAll($id)->result();
                                    foreach ($tmpSr as $srSpec) {
                                        if ($produkQty > $srSpec->max_qty) {
                                            $discountPersen = $srSpec->discount_persen;
                                            $discountQty = $srSpec->discount_qty;
                                        }
                                        elseif (($produkQty >= $srSpec->min_qty) && ($produkQty <= $srSpec->max_qty)) {
                                            $discountPersen = $srSpec->discount_persen;
                                            $discountQty = $srSpec->discount_qty;
                                        }
                                        else {
                                            $discountPersen = 0;
                                            $discountQty = 0;
                                        }
                                        $arrDiscount[$id] = array(
                                            "persen" => $discountPersen,
                                            "qty" => $discountQty,
                                        );
                                    }
                                }
                            }
                        }
                        $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
                        if(!empty($barcodesatuan)){
                            $arrBarcodeSatuan = blobDecode($barcodesatuan);
                            $tmpJml = $arrBarcodeSatuan['satuan_qty']*$qty_unit;
                            $satuan = $arrBarcodeSatuan['satuan_nama'];
                            $satuan_factor_id = $arrBarcodeSatuan['satuan_id'];
                            $satuan_factor_nama = $satuan;
                            $satuan_factor_qty = $arrBarcodeSatuan['satuan_qty'];
                        }

                        /* ----------------------------------------------------------------
                         * inisisasi cCode Items
                         * ----------------------------------------------------------------*/
                        if (!isset($_SESSION[$cCode]['items']) || !array_key_exists($id, $_SESSION[$cCode]['items'])) {
                            $tmp = array(
                                "handler" => $this->modul . "/" . $this->uri->segment(2),
                                "id" => $id,
                                "jml" => $tmpJml,
                                "qty_unit" => $qty_unit,
                                "harga" => 0,
                                "subtotal" => 0,
                                "satuan" => $satuan,
                            );
                            if (sizeof($priceMainConfig) > 0) {
                                if (isset($priceMainConfig[$_SESSION[$cCode]['main']['pihakMainName']])) {
                                    $priceConfig = $priceMainConfig[$_SESSION[$cCode]['main']['pihakMainName']];
                                }
                            }
                            if (sizeof($priceConfig) > 0) {
                                $mdlName = $priceConfig['model'];
                                $this->load->model("Mdls/" . $mdlName);
                                $h = new $mdlName();
                                if (isset($resetFilter['resetFilter']) && $resetFilter['resetFilter'] == true) {
                                    $h->addFilter("produk_id='$id'");
                                }
                                else {
                                    $h->addFilter("produk_id='$id'");
                                    $h->addFilter("status='1'");
                                    $h->addFilter("jenis_value in ('" . implode("','", $priceConfig['label']) . "')");
                                }
                                if (sizeof($priceFilter) > 0) {
                                    foreach ($priceFilter as $f) {
                                        $f_ex = explode("=", $f);
                                        if (!isset($f_ex[1])) {
                                            $f_ey = explode(">", $f_ex[0]);
                                            if (substr($f_ey[1], 0, 1) == ".") {
                                                $h->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                                            }
                                            else {
                                                if (isset($_SESSION[$cCode]['main'][$f_ey[1]])) {
                                                    $h->addFilter($f_ey[0] . ">'" . $_SESSION[$cCode]['main'][$f_ey[1]] . "'");
                                                }
                                                else {
                                                    $h->addFilter($f_ey[0] . ">0");
                                                }
                                            }
                                        }
                                        else {
                                            if (substr($f_ex[1], 0, 1) == ".") {
                                                $h->addFilter($f_ex[0] . "='" . ltrim($f_ex[1], ".") . "'");
                                            }
                                            else {
                                                if (isset($_SESSION[$cCode]['main'][$f_ex[1]])) {
                                                    $h->addFilter($f_ex[0] . "='" . $_SESSION[$cCode]['main'][$f_ex[1]] . "'");
                                                }
                                                else {
                                                    $h->addFilter($f_ex[0] . "=''");
                                                }
                                            }
                                        }
                                    }
                                }
                                $tmpH = $h->lookupAll($id)->result();
                                if (sizeof($tmpH) > 0) {
                                    $rawPrices = array();
                                    foreach ($tmpH as $hSpec) {
                                        foreach ($priceConfig['key_label'] as $key => $val) {
                                            if (isset($resetFilter['resetFilter'])) {
                                                $rawPrices[$key] = isset($hSpec->$key) ? $hSpec->$key : 0;
                                            }
                                            else {
                                                if ($key == $hSpec->jenis_value) {
                                                    $rawPrices[$key] = isset($hSpec->nilai) ? $hSpec->nilai : 0;
                                                }
                                            }
                                        }
                                    }
                                    $prices = normalizePrices("produk", $rawPrices);
                                    if (sizeof($prices) > 0) {
                                        foreach ($prices as $k => $v) {
                                            $tmp[$k] = $v;
                                        }
                                        $tmp['harga'] = isset($tmp[$priceConfig['mainSrc']]) ? $tmp[$priceConfig['mainSrc']] : 0;
                                    }
                                }
                            }
                            //------------------------------------------------------
                            foreach ($fieldSrcs as $key => $src) {
                                if (is_array($src) && sizeof($src) > 0) {
                                    foreach ($src as $srcSpec) {
                                        if (isset($tmp[$srcSpec]) || isset($rows->$srcSpec)) {
                                            $tmp[$key] = makeValue($srcSpec, $tmp, $tmp, isset($rows->$srcSpec) ? $rows->$srcSpec : 0);
                                        }
                                    }
                                }
                                else {
                                    $tmp[$key] = makeValue($src, $tmp, $tmp, isset($rows->$src) ? $rows->$src : 0);
                                }
                            }
                            if(isset($satuan_factor_id)&&isset($satuan_factor_nama)&&isset($satuan_factor_qty)){
                                $tmp['satuan_factor_id'] = $satuan_factor_id;
                                $tmp['satuan_factor_nama'] = $satuan_factor_nama;
                                $tmp['satuan_factor_qty'] = $satuan_factor_qty;
                                $tmp['satuan_id'] = $satuan_factor_id;
                            }
                            if (sizeof($itemNumLabels) > 0) {
                                echo("iterating subNums..");
                                foreach ($itemNumLabels as $key => $label) {
                                    if (isset($_GET[$key]) && $_GET[$key] > 0) {
                                        $newValue = $_GET[$key];
                                        $tmp[$key] = $newValue;
                                        echo "replacing value for $key with " . $newValue . "<br>";
                                    }
                                }
                            }
                            if ($subAmountConfig != null) {
                                $tmp['subtotal'] = makeValue($subAmountConfig, $tmp, $tmp, 0);
                            }
                            else {
                                $tmp['subtotal'] = 0;
                            }
                            /*
                             * bagian option satuan
                             */
                            //region sambungin ke relasi satuan
                            if (sizeof($shopingCartItemOptionFields) > 0) {
                                foreach ($shopingCartItemOptionFields as $keyIndex => $dataExtSatuan) {
                                    $mdl = $dataExtSatuan["mdlName"];
                                    $targetSes = $dataExtSatuan["targetSession"];
                                    $methode = $dataExtSatuan["methode"];
                                    $indexKey = $dataExtSatuan["keySrc"];
                                    $this->load->model("Mdls/" . $mdl);
                                    $mm = new $mdl();
                                    $mm->setTokoId(my_toko_id());
                                    $prevCon = $mm->$methode($id);
                                    if (sizeof($prevCon) > 0) {
                                        foreach ($prevCon[$id] as $prevCon_0) {
                                            foreach ($dataExtSatuan["usedFields"] as $src => $target) {
                                                if (!isset($_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target])) {
                                                    $_SESSION[$cCode][$targetSes][$id][$keyIndex][$prevCon_0[$indexKey]][$target] = $prevCon_0[$src];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            $_SESSION[$cCode]['items'][$produk_id] = $tmp;
                            //endregion
                        }
                        else {

//                            cekBiru("ada id ($id) tapi tidak ada di session items @" . __LINE__);

                            if(!empty($barcodesatuan)){
                                if( $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] != $satuan_factor_qty ){
//                                    cekHitam("satuan before after tidak sama");

                                    if( $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] > $satuan_factor_qty ){
                                        //jika before lebih besar dari pada after
                                        //reset dulu ke satuan terkecil
//                                $_SESSION[$cCode]['items'][$id]['satuan_factor_id'] = $row->satuan_id;
//                                $_SESSION[$cCode]['items'][$id]['satuan_factor_nama'] = $row->satuan;
//                                $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] = 1;
                                        $jml_down = $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'] * $_SESSION[$cCode]['items'][$id]['qty_unit'];
                                        $qty_down = $jml_down;
                                        $qty_tambah = $qty_down + $satuan_factor_qty;
//                                $_SESSION[$cCode]['items'][$id]['jml'] = $qty_tambah;
//                                $_SESSION[$cCode]['items'][$id]['qty_unit'] = $qty_tambah;

//                                        cekKuning("
//                                    satuan_factor_id: ". $row->satuan_id ."  <br>
//                                    satuan_factor_nama: ".$row->satuan ."  <br>
//                                    satuan_factor_qty: 1  <br>
//                                    jml: $qty_tambah <br>
//                                    qty_unit: $qty_tambah
//                                ");
                                    }
                                    else{
                                        //jika before lebih kecil dari pada after
//                                        cekKuning("before lebih kecil dari pada after");
                                    }
                                }
                                else{
//                                    cekHijau("TIDAK BERUBAH SATUAN");
                                }
                            }
                            else{
                                if (isset($_GET['newQty'])) {
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] = $_GET['newQty'];
                                    $_SESSION[$cCode]['items'][$id]['jml'] = $_GET['newQty'] * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];
                                }
                                else {
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] += $qty_unit;
                                    $_SESSION[$cCode]['items'][$id]['qty_unit'] += $qty_unit * $_SESSION[$cCode]['items'][$id]['satuan_factor_qty'];
                                }
                                if (isset($arrDiscount[$id]) && sizeof($arrDiscount[$id]) > 0) {
                                    foreach ($arrDiscount[$id] as $dKey => $dVal) {
                                        if (!isset($_SESSION[$cCode]['items'][$id]['discount_' . $dKey])) {
                                            $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = 0;
                                        }
                                        $_SESSION[$cCode]['items'][$id]['discount_' . $dKey] = $dVal;
                                    }
                                }
                                if (sizeof($itemNumLabels) > 0) {
//                                    echo("iterating subNums..");
                                    foreach ($itemNumLabels as $key => $label) {
                                        if (isset($_GET[$key]) && strlen($_GET[$key]) > 0) {
                                            $newValue = $_GET[$key];
                                            $tmp[$key] = $newValue;
                                            $_SESSION[$cCode]['items'][$id][$key] = $newValue;
//                                            echo "replacing value for $key with " . $newValue . "<br>";
                                        }
                                    }
                                    if ($subAmountConfig != null) {
                                        $tmp['subtotal'] = makeValue($subAmountConfig, $_SESSION[$cCode]['items'][$id], $_SESSION[$cCode]['items'][$id], 0);
                                    }
                                    else {
                                        $tmp['subtotal'] = 0;
                                    }
                                    $_SESSION[$cCode]['items'][$id]['subtotal'] = $tmp['subtotal'];
                                }
                            }
                        }

                        /* ----------------------------------------------------------
                         * diskon-diskonan-grosir
                         * ----------------------------------------------------------*/
                        $tmp = $_SESSION[$cCode]['items'][$id];
                        $pro_premi = $row->premi_jual;
                        $pro_harga = $tmp['harga_list'] + (($pro_premi / 100) * $tmp['harga_list']);
//                        $pro_harga = $tmp['jual'] + (($pro_premi / 100) * $tmp['jual']);

                        $pro_jml = $tmp['jml'];
                        $calc_hasil = $this->selectorDiskon($id, $pro_harga, $pro_jml);

                        $tmp['discPersen']  = $calc_hasil['persen'];
                        $tmp['lastNett']    = $calc_hasil['harga_af'];
                        $tmp['harga']       = $calc_hasil['harga_af'];

                        $tmp['harga_jual']  = $calc_hasil['harga_be']*$tmp['satuan_factor_qty'];
                        $tmp['harga_disc']  = ($calc_hasil['harga_af']*$tmp['satuan_factor_qty'])*$tmp['qty_unit'];

                        $tmp['discNilai']   = $calc_hasil['nilai']*$tmp['satuan_factor_qty'];
                        $tmp['id']          = $id;

                        $tmp['subtotal'] = $calc_hasil['harga_af']*$pro_jml;

                        $_SESSION[$cCode]['items'][$produk_id] = $tmp;
                    }
                }
                else {
//                    cekMerah("tidak ada itemnya! @" . __LINE__ . " " . __METHOD__);
                    die();
                }

                $f_selector = "";
                if (isset($_GET['selector'])) {
                    $f_selector = "selector&";
                }

                $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" => $stepNum,
                    "stepCode" => $this->configUiJenis['steps'][$stepNum]['target'],
                    "dtime" => dtimeNow(),
                    "fulldate" => dtimeNow("Y-m-d"),
                );
                $vg->buildValue($this->jenisTr, $id, $initMasterValues, $this->modul);

            }
        }

    }

    public function validasiHPP($tmp,$cCode,$actual_link){

        $id = $tmp['id'];
        $tHarga = $tmp['harga']*1;
        $tHpp = $tmp['hpp_produk']*1;
        $name = $tmp['nama'];
        $rl = $tmp['laba_jual']*1;
        $cCode_set = $cCode;
        $shoppingcart_order_id = $_SESSION[$cCode]['main']['shoppingcart_order_id'];
        $gate_set = "items";

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

        $emplyeeOption = "";
        if (!empty($arrEmployee)) {

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

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

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

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

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

        }

//        $actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $tmp_target = $tmp;
        $tmp_target['actual_link'] = $actual_link;
        $jml_items = $tmp['qty_unit'];
        $blobDatas = blobEncode($tmp_target);

        echo "<script>
                var showViewOtorisasiProdukHpp = function(){
                    top.swal({
                       title: 'HARGA JUAL < HPP',
                       html: 'Harga Jual (<b>$name</b>) lebih kecil dari HPP.<br>Masukan PIN/OTP dari SPV Anda untuk melanjutkan Transaksi ini.<br><r>Atau hubungi atasan yg berwenang merubah harga.</r><br><br><br><br>' +
                       \"<div class=''>\" +
                       \"$emplyeeOption\" +
                       \"</div>\" +
                       '<div>&nbsp;</div>',
                       type: 'warning',
                       customClass: 'swal-wide',
                       showConfirmButton: false,
                       allowOutsideClick: false,
                       onOpen: function(){
                            top.$('#hppPinOtp').off('keyup');
                            top.$('#hppPinOtp').on('keyup', top.delay_v2( function(){
                                if( this.value.length >= 6){
                                    activeBtnNextHpp()
                                }
                            }, 500) )
                            var activeBtnNextHpp = function(){
                                top.$('#btn-otorisasi').attr('disabled', false);
                                top.$('#btn-otorisasi').off('click');
                                top.$('#btn-otorisasi').on('click', function(){
                                    var pin_otp = top.$('#hppPinOtp').val();
                                    if( pin_otp != '' ){
                                        top.$.ajax({
                                            url: '". base_url() . $this->modul . "/_shoppingCart/hppOtorisator/".$this->jenisTr."',
                                            method: 'post',
                                            data: {
                                                pin_diskon: pin_otp,
                                            },
                                            success: function(a){
                                                jsonData = JSON.parse(a);
                                                if(jsonData.status){
                                                    top.swal('BERHASIL', jsonData.reason, 'warning');
                                                    top.swal.enableLoading();
                                                    if(top.document.getElementById('shopping_cart')){
                                                        top.$('#result').load(jsonData.target_url, function(){
                                                            setTimeout( function(){ top.swal.close() }, 1000);
                                                        });
                                                    }
                                                }
                                                else{
                                                    top.swal('Perbaiki PIN/OTP', jsonData.reason, 'warning');
                                                    top.swal.enableLoading();
                                                    setTimeout(function(){
                                                        showViewOtorisasiProdukHpp()
                                                    },1500)
                                                }
                                            }
                                        })
                                    }
                                    else{
                                        top.swal('masih kosong cookk, masukan pin lok');
                                        top.swal.enableLoading();
                                        setTimeout(function(){
                                            showViewOtorisasiProdukHpp()
                                        },1500)
                                    }
                                })
                            }
                            var pushRequestHpp = function(){
                                top.$('#hppPinOtp').attr('disabled', true)
                                top.$.ajax({
                                    url: '". base_url() . $this->modul . "/_shoppingCart/reqHppSave/".$this->jenisTr."',
                                    method: 'post',
                                    data: {
                                        produk_id: $id,
                                        produk_nama: '$name',
                                        produk_harga: $tHarga,
                                        produk_hpp: $tHpp,
                                        blob_datas: '$blobDatas',
                                        produk_rl: $rl,
                                        jml_items: $jml_items,
                                        cCode_set: '$cCode_set',
                                        gate_set: '$gate_set',
                                        shoppingcart_order_id: $shoppingcart_order_id,
                                        jenisTr: '".$this->jenisTr."',
                                    },
                                    success: function(a){
                                        jsonData = JSON.parse(a);
                                        if(jsonData.status){
                                            top.$('#hppPinOtp').attr('disabled', false)
                                        }
                                        else{

                                        }
                                    }
                                })
                            }
                            pushRequestHpp()
                       }
                    });
                }
                showViewOtorisasiProdukHpp();
            </script>";
        die();
    }
}