<?php

defined('BASEPATH') OR exit('No direct script access allowed');
require_once "Modul_Controller_NL.php";

//error_reporting(E_ALL);
//ini_set('display_errors', 1);

class AndroidSynchronizer extends Modul_Controller_NL
{
    protected $receiptElementTmp;
    protected $settlementTmp;

    public function getReceiptElementTmp()
    {
        return $this->receiptElementTmp;
    }

    public function setReceiptElementTmp($receiptElementTmp)
    {
        $this->receiptElementTmp = $receiptElementTmp;
    }

    public function getSettlementTmp()
    {
        return $this->settlementTmp;
    }

    public function setSettlementTmp($settlementTmp)
    {
        $this->settlementTmp = $settlementTmp;
    }

    public function __construct()
    {
        parent::__construct();
        $this->load->model("MdlTransaksi");
    }

    public function index(){

        die("masuk AndroidSynchronizer index ");

    }

    public function sendPreOrder()
    {

        $this->jenisTr = "581";
        $this->tableInConfig = isset($this->configUi[$this->jenisTr]['tableIn']) ? $this->configUi[$this->jenisTr]['tableIn'] : array();
        $this->tableInConfig_static = isset($this->configUi[$this->jenisTr]['tableIn_static']) ? $this->configUi[$this->jenisTr]['tableIn_static'] : array();

        $this->db->trans_start();

        //region array builder transaction
        $mainTmp = array(
            "olehID" => "olehID",
            "olehName" => "olehName",
            "placeID" => "placeID",
            "placeName" => "placeName",
            "cabangID" => "cabangID",
            "cabangName" => "cabangName",
            "gudangID" => "gudangID",
            "gudangName" => "gudangName",
            "customers_id" => "customers_id",
            "customers_nama" => "customers_nama",
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $this->jenisTr . "r",
            "jenisTrName" => "sales request (apk)",
            "stepNumber" => "1",
            "stepCode" => $this->jenisTr . "r",
            "dtime" => "dtime",
            "fulldate" => "date",
            "gudang2" => "100",
            "gudang2__label" => "default center warehouse",
            "gudang2__nama" => "",
            "harga" => "harga",
            "divID" => "2",
            "divName" => "",
            "subtotal" => "subtotal",
            "reference" => "0",
            "gudang2ID" => "100",
            "gudang2Name" => "default center warehouse",
            "jenis" => $this->jenisTr . "r",
            "transaksi_jenis" => $this->jenisTr . "r",
            "next_step_code" => $this->jenisTr,
            "next_group_code" => "o_seller_entry",
            "step_number" => "1",
            "step_current" => "1",
            "longitude" => "",
            "lattitude" => "",
            "accuracy" => "",
            "nilai_bayar" => "0",
            "new_sisa" => "0",
            "note" => "0",
            "description" => "",
            "pihakID" => $pihakMainID,
            "pihakName" => $pihakMainName,
            "pihakName2" => "cabang utama",
            "pihakDisc" => "",
//            "cabang2ID" => "100",
//            "cabang2Name" => "cabang utama",
//            "place2ID" => "100",
//            "place2Name" => "cabang utama",
            "pihakMainName" => "",
            "pihakMainID" => "",
        );
        $itemsTmp = array(
            "handler" => "Selectors/_processSelectBiaya",
            "id" => "id",
            "jml" => "1",
            "harga" => "harga",
            "subtotal" => "subtotal",
            "nama" => "nama",
            "label" => "",
            "reference" => "",
            "qty" => "1",
            "name" => "extern_nama",
            "sub_harga" => "sub_harga",
            "sub_subtotal" => "sub_total",
            "olehID" => "olehID",
            "olehName" => "olehName",
            "placeID" => "placeID",
            "placeName" => "cabang_nama",
            "cabangID" => "cabangID",
            "cabangName" => "cabangName",
            "gudangID" => "gudangID",
            "gudangName" => "gudangName",
            "gudang2ID" => "100",
            "gudang2Name" => "default center warehouse",
            "jenisTr" => $this->jenisTr,
            "next_substep_code" => $this->jenisTr,
            "next_subgroup_code" => "o_seller_entry",
            "sub_step_number" => "1",
            "sub_step_current" => "1",
            "nilai_bayar" => "",
            "new_sisa" => "0",
            "sub_new_sisa" => "0",
            "note" => "",
            "pihakID" => $pihakMainID,
            "pihakName" => $pihakMainName,
//            "place2ID" => "100",
//            "place2Name" => "cabang utama",
//            "cabang2ID" => "100",
//            "cabang2Name" => "cabang utama",

            "jual_nppn" => "jual_nppn",
            "hpp" => "hpp",
            "disc" => "disc",
            "harga1" => "harga1",
            "harga_nett1" => "harga_nett1",
            "harga2" => "harga2",
            "harga_nett2" => "harga_nett2",

        );
        $items2 = array();
        $items2_sum = array();
        $rsltItems = array();
        $rsltItems2 = array();
        $tableIn_masterTmp = array(
            "trash" => "0",
            "jenis_master" => $this->jenisTr,
            "jenis_top" => $this->jenisTr . "r",
            "jenis" => $this->jenisTr . "r",
            "jenis_label" => "sales request",
            "div_id" => "2",
            "div_nama" => "",
            "oleh_id" => "olehID",
            "oleh_nama" => "olehName",
            "cabang_id" => "cabangID",
            "cabang_nama" => "cabangName",
            "transaksi_nilai" => "sub_total",
            "transaksi_jenis" => $this->jenisTr . "r",
            "gudang_id" => "gudangID",
            "gudang_nama" => "gudangName",
//            "gudang2_id" => "100",
//            "gudang2_nama" => "default center warehouse",
            "keterangan" => "",
//            "cabang2_id" => "100",
//            "cabang2_nama" => "cabang utama",
            "pihakMainName" => "",
            "pihakMainID" => "",
        );
        $tableIn_detailTmp = array(
            "produk_id" => "produk_id",
            "produk_kode" => "",
            "produk_label" => "",
            "produk_nama" => "produk_nama",
            "produk_ord_jml" => "produk_ord_jml",
            "produk_ord_hrg" => "produk_ord_hrg",
            "hpp" => "hpp",
            "satuan" => "",
            "note" => "",
            "reference" => "",
            "trash" => "0",
            "produk_jenis" => "produk_jenis",
            "valid_qty" => "1",
        );
        $tableIn_detail2_sum = array();
        $tableIn_detail_rsltItems = array();
        $tableIn_detail_rsltItems2 = array();
        $tableIn_master_valuesTmp = array(
            "gudang2" => "100",
            "harga" => "harga",
            "divID" => "2",
            "subtotal" => "subtotal",
            "reference" => "0",
            "nilai_bayar" => "0",
            "note" => "0",
        );
        $tableIn_detail_valuesTmp = array(
            "jml" => "jml",
            "harga" => "harga",
            "subtotal" => "subtotal",
            "qty" => "jml",
            "sub_harga" => "sub_harga",
            "sub_subtotal" => "subtotal",
            "sub_new_sisa" => "0",
            "jual_nppn" => "jual_nppn",
            "hpp" => "hpp",
            "disc" => "disc",
            "harga1" => "harga1",
            "harga_nett1" => "harga_nett1",
            "harga2" => "harga2",
            "harga_nett2" => "harga_nett2",
        );
        $tableIn_detail_values_rsltItemsTmp = array();
        $tableIn_detail_values_rsltItems2Tmp = array();
        $tableIn_detail_values2_sumTmp = array();
        $tableIn_detail2 = array();
        $main_add_values = array();
        $main_add_fields = array();
        $main_elements = array();
        $main_inputs = array();
        $main_inputs_orig = array();
        $receiptDetailFieldsTmp = array(
            "produk_nama" => "name",
        );
        $receiptSumFieldsTmp = array(
            "harga" => "total amount",
        );
        $receiptDetailFields2 = array();
        $receiptSumFields2 = array();
        $tableIn_detail_values2_sum = array();
        $items3 = array();
        $items3_sum = array();
        $tableIn_detail_values_rsltItems = array();
        $tableIn_detail_values_rsltItems2 = array();
        //endregion

        $jenisTr = $this->jenisTr;
        $cCode = "_TR_" . $this->jenisTr;

        $title = $this->configUi[$jenisTr]["label"];
        $subTitle = $this->configUi[$jenisTr]["steps"][1]['label'];

        $input = $_REQUEST;

//        $arrProduk = json_decode(base64_decode(" "));
//
//        $response = array(
//            "toko_id" => "20220603",
//            "validGrandTotal" => "1582000",
//            "nomor_referensi" => "INV-2002-1820-1230",
//            "oleh_id" => "1603",
//            "oleh_nama" => "sakura",
//            "datetime" => date("Y-m-d H:i:s"),
//            "seller_id" => "1603",
//            "seller_nama" => "sakura",
//            "customer_id" => "6",
//            "customer_nama" => "Jonathan",
//            "customer_alamat" => "Gedung Prodi Teknik Perminyakan-FTM UPNVY, Lapangan Sepak Bola UPN Kampus I, Condong Catur, Condongcatur, Depok, Sleman Regency, Special Region of Yogyakarta, 55821, Indonesia",
//            "customer_telp" => "08985193131",
//            "produk_blob" => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
//        );
//

        $cabangData = array(
            100 => "cabang utama",
        );

        if(sizeof($input)>0){
            //transaksi main buildder taro sini
            $arrItems = array();
            $subtotal = 0;
            $arrProduk = json_decode(base64_decode($input['produk_blob']), true);
            $toko_id = $input['toko_id'];
            $pihakMainID = $input['oleh_id'];
            $pihakMainName = $input['oleh_nama'];
            $no_reference = $input['nomor_referensi'];
            $cabID = 100;
            $gID = -1000;
            $gudID = -1000;

            foreach($arrProduk as $k => $prodsDetil){
                $produk_id = $prodsDetil['id']*1;
                $valDef = $prodsDetil['harga'];
                $valQty = $prodsDetil['jml'];
                $arrItems[$produk_id] = array(
                    "harga" => $valDef,
                    "produk_ord_hrg" => $valDef*1,
                    "qty" => $valQty*1,
                    "jml" => $valQty*1,
                    "placeID" => $cabID,
                    "subtotal" => $valDef * $valQty,
                    "subTotal" => $valDef * $valQty,
                    "sub_total" => $valDef * $valQty,
                    "sub_subtotal" => $valDef * $valQty,
                    "sub_harga" => $valDef * $valQty,
                    "id" => $produk_id,
                    "produk_id" => $produk_id,
                    "produk_ord_jml" => $valQty*1,
                    "produk_nama" => isset($prodsDetil['nama']) ? $prodsDetil['nama'] : "",
                    "name" => isset($prodsDetil['nama']) ? $prodsDetil['nama'] : "",
                    "nama" => isset($prodsDetil['nama']) ? $prodsDetil['nama'] : "",
                    "kode" => isset($prodsDetil['kode']) ? $prodsDetil['kode'] : "",
                    "merk" => isset($prodsDetil['merk']) ? $prodsDetil['merk'] : "",
                    "serial_no" => isset($prodsDetil['serial_no']) ? $prodsDetil['serial_no'] : "",
                    "produk_jenis" => "produk",
                    "olehID" => $pihakMainID,
                    "olehName" => $pihakMainName,
                    "jual_nppn" => $valDef,
                    "hpp" => $valDef,
                    "disc" => "0",
                    "harga1" => $valDef,
                    "harga_nett1" => $valDef,
                    "harga2" => $valDef,
                    "harga_nett2" => $valDef,
                    "pihakID" => $pihakMainID,
                    "pihakName" => $pihakMainName,
                );

                $subtotal += ($valDef * $valQty);
            }

            //region builder main
            $main = array(
                "olehID" => $pihakMainID,
                "olehName" => $pihakMainName,
                "toko_id" => $toko_id,
                "customerID" => $input['customer_id'],
                "customers_id" => $input['customer_id'],
                "customers_nama" => $input['customer_nama'],
                "placeID" => $cabID,
                "placeName" => "cabang utama",
                "cabangID" => $cabID,
                "cabangName" => "cabang utama",
                "gudangID" => $gID,
                "gudangName" => "gudang utama",
                "jenisTr" => $this->jenisTr,
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $this->jenisTr . "r",
                "jenisTrName" => "sales request (apk)",
                "stepNumber" => "1",
                "stepCode" => $this->jenisTr . "r",
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "harga" => $subtotal,
                "divID" => "2",
                "divName" => "",
                "subtotal" => $subtotal,
                "reference" => "$no_reference",
                "jenis" => $this->jenisTr . "r",
                "transaksi_jenis" => $this->jenisTr . "r",
                "next_step_code" => $this->jenisTr,
                "next_group_code" => "o_seller_entry",
                "step_number" => "1",
                "step_current" => "1",
                "longitude" => "",
                "lattitude" => "",
                "accuracy" => "",
                "nilai_bayar" => "0",
                "new_sisa" => "0",
                "note" => "0",
                "description" => "",
                "pihakDisc" => "",
                "pihakID" => $pihakMainID,
                "pihakName" => $pihakMainName,
            );
            //endregion builder main

            //region builder items
            $items = array();
            foreach ($arrItems as $itsID => $itsData) {
                foreach ($itemsTmp as $col => $selectedRow) {
                    $items[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion builder items

            //region builder tabel in master
            $tableIn_master = array(
                "trash" => "0",
                "jenis_master" => $this->jenisTr,
                "jenis_top" => $this->jenisTr . "r",
                "jenis" => $this->jenisTr . "r",
                "toko_id" => $toko_id,
                "customers_id" => $input['customer_id'],
                "customers_nama" => $input['customer_nama'],
                "jenis_label" => "sales request",
                "div_id" => "2",
                "div_nama" => "",
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "oleh_id" => $pihakMainID,
                "oleh_nama" => $pihakMainName,
                "cabang_id" => $cabID,
                "cabang_nama" => $cabangData[$cabID],
                "transaksi_nilai" => $subtotal,
                "transaksi_jenis" => $this->jenisTr . "r",
                "gudang_id" => $gudID,
                "gudang_nama" => "default warehouse at branch #100",
//                "gudang2_id" => "100",
//                "gudang2_nama" => "default center warehouse",
                "keterangan" => "",
//                "cabang2_id" => "100",
//                "cabang2_nama" => "cabang utama",
                "pihakMainName" => $pihakMainID,
                "pihakMainID" => $pihakMainID,
            );
            //endregion builder tabel in master

            //region builder table in detil
            $tableIn_detail = array();
            foreach ($arrItems as $itsID => $itsData) {
                foreach ($tableIn_detailTmp as $col => $selectedRow) {
                    $tableIn_detail[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }

            //endregion builder table in detil

            //region table in master values
            $tableIn_master_values = array(
                "gudang" => $gID,
                "harga" => $subtotal,
                "divID" => "2",
                "subtotal" => $subtotal,
                "reference" => "0",
                "nilai_bayar" => "0",
                "note" => "0",
            );
            //endregion table in master values

            //region build table in detil values
            $tableIn_detail_values = array();
            foreach ($arrItems as $itsID => $itsData) {
                foreach ($tableIn_detail_valuesTmp as $col => $selectedRow) {
                    $tableIn_detail_values[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion build table in detil values

            arrPrint($tableIn_detail_values);

            //region build table receipDetailFields
            $receiptDetailFields = array();
            foreach ($arrItems as $itsID => $itsData) {
                foreach ($receiptDetailFieldsTmp as $col => $selectedRow) {
                    $receiptDetailFields[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion

            //region receiptSumFields
            $receiptSumFields = array();
            foreach ($arrItems as $itsID => $itsData) {
                foreach ($receiptSumFieldsTmp as $col => $selectedRow) {
                    $receiptSumFields[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion

            if (sizeof($arrItems) > 0) {
                $gate['items'] = $arrItems;
                //region transaksional
                $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][1]['master']) ? $this->configCore[$this->jenisTr]['components'][1]['master'] : array();
                $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][1]['detail']) ? $this->configCore[$this->jenisTr]['components'][1]['detail'] : array();
                $addMasterTables = array(
                    "rugilaba",
                    "laba ditahan",
                    "rugilaba lain lain",
                );
                foreach ($addMasterTables as $trek) {
                    $buildTablesMaster[] = array(
                        "comName" => "RugiLaba",
                        "loop" => array(
                            "$trek" => .0,
                        ),
                    );
                }
                if (sizeof($buildTablesMaster) > 0) {
                    $bCtr = 0;
                    foreach ($buildTablesMaster as $buildTablesMaster_specs) {
                        $bCtr++;
                        $mdlName = $buildTablesMaster_specs['comName'];
                        if (substr($mdlName, 0, 1) == "{") {
                            $mdlName = trim($mdlName, "{");
                            $mdlName = trim($mdlName, "}");
                            $mdlName = str_replace($mdlName, $main[$mdlName], $mdlName);
                        }
                        else {
                            //                        cekkuning("TIDAK mengandung kurawal");
                        }

                        $mdlName = "Com" . $mdlName;
                        $this->load->model("Coms/" . $mdlName);
                        $m = new $mdlName();
                        if (isset($buildTablesMaster_specs['loop']) && sizeof($buildTablesMaster_specs['loop']) > 0) {
                            foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
                                if (substr($key, 0, 1) == "{") {
                                    $oldParam = $buildTablesMaster_specs['loop'][$key];
                                    unset($buildTablesMaster_specs['loop'][$key]);
                                    $key = trim($key, "{");
                                    $key = trim($key, "}");
                                    $key = str_replace($key, $main[$key], $key);
                                    $buildTablesMaster_specs['loop'][$key] = $oldParam;
                                }
                            }
                        }
                        if (method_exists($m, "getTableNameMaster")) {
                            if (sizeof($m->getTableNameMaster())) {
                                $m->buildTables($buildTablesMaster_specs);
                            }
                        }
                    }
                }
                if (sizeof($buildTablesDetail) > 0) {
                    foreach ($buildTablesDetail as $buildTablesDetail_specs) {
                        foreach ($items as $itemSpec) {
                            $mdlName = $buildTablesDetail_specs['comName'];
                            if (substr($mdlName, 0, 1) == "{") {
                                $mdlName = trim($mdlName, "{");
                                $mdlName = trim($mdlName, "}");
                                $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
                            }
                            $mdlName = "Com" . $mdlName;
                            cekbiru("model: $mdlName");
                            $this->load->model("Coms/" . $mdlName);
                            $m = new $mdlName();
                            if (isset($buildTablesDetail_specs['loop']) && sizeof($buildTablesDetail_specs['loop']) > 0) {
                                foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
                                    if (substr($key, 0, 1) == "{") {
                                        $oldParam = $buildTablesDetail_specs['loop'][$key];
                                        unset($buildTablesDetail_specs['loop'][$key]);
                                        $key = trim($key, "{");
                                        $key = trim($key, "}");
                                        $key = str_replace($key, $itemSpec[$key], $key);
                                        $buildTablesDetail_specs['loop'][$key] = $oldParam;
                                    }
                                }
                            }
                            if (method_exists($m, "getTableNameMaster")) {
                                if (sizeof($m->getTableNameMaster())) {
                                    $m->buildTables($buildTablesDetail_specs);
                                }
                            }
                        }
                    }
                }

                //region pre-processors (master)
                if (isset($this->configCore[$this->jenisTr]['preProcessor'][1]['master'])) {
                    $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['master'] : array();
                    $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
                    if (sizeof($iterator) > 0) {
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $comName = $tComSpec['comName'];
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                            $subParams = array();
                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {
                                    $realValue = makeValue($value, $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                    $subParams['static'][$key] = $realValue;
                                }
                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'];
                            }
                            $tmpOutParams[$cCtr] = $subParams;

                            $mdlName = "Pre" . ucfirst($comName);
                            $this->load->model("Preprocs/" . $mdlName);
                            $m = new $mdlName($resultParams);

                            if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                $tobeExecuted = true;
                            }
                            else {
                                $tobeExecuted = false;
                            }

                            if ($tobeExecuted) {
                                $m->pair(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $gotParams = $m->exec();
                                if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                                    foreach ($gotParams as $gateName => $gSpec) {
                                        if (isset($_SESSION[$cCode]['main'])) {
                                            if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                foreach ($gSpec as $key => $val) {
                                                    $_SESSION[$cCode]['main'][$key] = $val;
                                                }
                                            }
                                        }
                                        //==inject gotParams to child gate
                                        if (isset($_SESSION[$cCode]['main'])) {
                                            if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                foreach ($gSpec as $key => $val) {
                                                    $_SESSION[$cCode]['main'][$key] = $val;
                                                }
                                            }
                                        }
                                        if (sizeof($itemNumLabels) > 0) {
                                            foreach ($itemNumLabels as $key => $label) {
                                                if (isset($_SESSION[$cCode]['main'][$key])) {
                                                    $_SESSION[$cCode]['main']['sub_' . $key] = ($_SESSION[$cCode]['main']['jml'] * $_SESSION[$cCode]['main'][$key]);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                            }
                        }
                    }
                    else {
                        //cekKuning("sub-preproc is not set");
                    }
                    $this->load->helper("he_value_builder");
                    fillValues($this->jenisTr, 1, 1);
                }
                else {
                    echo("no processor defined. skipping preprocessor..<br>");
                }
                //endregion

                //region pre-processors (item)
                if (isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail'])) {
                    $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['detail'] : array();
                    $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
                    if (sizeof($iterator) > 0) {
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $comName = $tComSpec['comName'];
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                                $tmpOutParams[$cCtr] = array();
                                $id = $xid;
                                $subParams = array();
                                if (isset($tComSpec['static'])) {
                                    foreach ($tComSpec['static'] as $key => $value) {
                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                        $subParams['static'][$key] = $realValue;
                                    }
                                    $subParams['static']["fulldate"] = date("Y-m-d");
                                    $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                    $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'];
                                }

                                if (sizeof($subParams) > 0) {
                                    $tmpOutParams[$cCtr][] = $subParams;
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                                    $mdlName = "Pre" . ucfirst($comName);
                                    $this->load->model("Preprocs/" . $mdlName);
                                    $m = new $mdlName($resultParams);
                                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                        $tobeExecuted = true;
                                    }
                                    else {
                                        $tobeExecuted = false;
                                    }

                                    if ($tobeExecuted) {
                                        $m->pair(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                        $gotParams = $m->exec();
                                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                                            foreach ($gotParams as $gateName => $paramSpec) {
                                                if (!isset($_SESSION[$cCode][$gateName])) {
                                                    $_SESSION[$cCode][$gateName] = array();
                                                }
                                                else {

                                                }

                                                foreach ($paramSpec as $id => $gSpec) {
                                                    if (!isset($_SESSION[$cCode][$gateName][$id])) {
                                                        $_SESSION[$cCode][$gateName][$id] = array();
                                                    }
                                                    if (isset($_SESSION[$cCode][$gateName][$id])) {
                                                        if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                            foreach ($gSpec as $key => $val) {
                                                                $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                            }
                                                        }
                                                    }
                                                    //==inject gotParams to child gate
                                                    if (isset($_SESSION[$cCode][$srcGateName][$id])) {
                                                        if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                            foreach ($gSpec as $key => $val) {
                                                                $_SESSION[$cCode][$srcGateName][$id][$key] = $val;
                                                            }
                                                        }
                                                    }

                                                    if (sizeof($itemNumLabels) > 0) {
                                                        foreach ($itemNumLabels as $key => $label) {
                                                            if (isset($_SESSION[$cCode][$gateName][$id][$key])) {
                                                                $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else {
                                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                    }
                                }
                            }
                        }
                    }
                    else {
                        //cekKuning("sub-preproc is not set");
                    }

                    $this->load->helper("he_value_builder");
                    fillValues($this->jenisTr, 1, 1);

                }
                else {
                    echo("no processor defined. skipping preprocessor..<br>");
                }
                //endregion

//                $this->midValidate();
//                $this->unionValidate();
                //===finalisasi sebelum masuk tabel beneran

                //===isinya ada pembentukan nomor nota dll
                //region penomoran receipt
                $this->load->model("CustomCounter");
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");

                $counterForNumber = array($this->configCore[$this->jenisTr]['formatNota']);
                if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['counters'])) {
                    die("Used number should be registered in 'counters' config as well");
                }
                echo "<div style='background:#ff7766;'>";
                foreach ($counterForNumber as $i => $cRawParams) {
                    $cParams = explode("|", $cRawParams);
                    $cValues = array();
                    foreach ($cParams as $param) {
                        $cValues[$i][$param] = $main[$param];
                    }
                    $cRawValues = implode("|", $cValues[$i]);
                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                }
                echo "</div style='background:#ff7766;'>";

                $stepNumber = 1;
                $tmpNomorNota = $paramSpec['paramString'];

                if (isset($this->configUi[$this->jenisTr]['steps'][2])) {
                    $nextProp = array(
                        "num" => 2,
                        "code" => $this->configUi[$this->jenisTr]['steps'][2]['target'],
                        "label" => $this->configUi[$this->jenisTr]['steps'][2]['label'],
                        "groupID" => $this->configUi[$this->jenisTr]['steps'][2]['userGroup'],
                    );
                }
                else {
                    $nextProp = array(
                        "num" => 0,
                        "code" => "",
                        "label" => "",
                        "groupID" => "",
                    );
                }
                //endregion

                //region dynamic counters
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $configCustomParams = $this->configCore[$this->jenisTr]['counters'];
                $configCustomParams[] = "stepCode";

                if (sizeof($configCustomParams) > 0) {
                    $cContent = array();
                    foreach ($configCustomParams as $i => $cRawParams) {
                        $cParams = explode("|", $cRawParams);
                        $cValues = array();
                        foreach ($cParams as $param) {
                            $cValues[$i][$param] = $main[$param];
                        }
                        $cRawValues = implode("|", $cValues[$i]);
                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                        $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                        switch ($paramSpec['id']) {
                            case 0: //===counter type is new
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                break;
                            default: //===counter to be updated
                                $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                break;
                        }
                    }
                }
                $appliedCounters = base64_encode(serialize($cContent));
                $appliedCounters_inText = print_r($cContent, true);

                //region addition on master
                $addValues = array(
                    'counters' => $appliedCounters,
                    'counters_intext' => $appliedCounters_inText,
                    'nomer' => $tmpNomorNota,
                    'dtime' => date("Y-m-d H:i:s"),
                    'fulldate' => date("Y-m-d"),
                    "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                    "step_number" => 1,
                    "step_current" => 1,
                    "next_step_num" => $nextProp['num'],
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],
                    "tail_number" => 1,
                    "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],
                );
                foreach ($addValues as $key => $val) {
                    $tableIn_master[$key] = $val;
                }
                //endregion

                //region addition on detail
                $addSubValues = array(
                    "sub_step_number" => 1,
                    "sub_step_current" => 1,
                    "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                    "next_substep_num" => $nextProp['num'],
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "sub_tail_number" => 1,
                    "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],
                );
                foreach ($tableIn_detail as $id => $dSpec) {
                    foreach ($addSubValues as $key => $val) {
                        $tableIn_detail[$id][$key] = $val;
                    }
                }
                //endregion

                //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                if (sizeof($tableIn_master) > 0) {
                    $tableIn_master['status_4'] = 11;
                    $tableIn_master['trash_4'] = 0;

                    $tr = new MdlTransaksi();
                    $tr->addFilter("transaksi.cabang_id='" . $tableIn_master['cabang_id'] . "'");
                    $insertID = $tr->writeMainEntries($tableIn_master);
                    $queryInsertID = $this->db->last_query();
                    $mongoList['main'][] = $insertID;
                    $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $tableIn_master);
                    $mongoList['main'][] = $epID;

                    $insertNum = $tableIn_master['nomer'];
                    $main['nomer'] = $insertNum;
                    if ($insertID < 1) {
                        cekmerah($queryInsertID);
                        die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                    }

                    //==transaksi_id dan nomor nota diinject kan ke gate utama
                    $injectors = array(
                        "transaksi_id" => $insertID,
                        "nomer" => $tmpNomorNota,
                    );
                    $arrInjectorsTarget = array(
                        "items",
                    );
                    foreach ($injectors as $key => $val) {
                        $main[$key] = $val;
                        foreach ($arrInjectorsTarget as $target) {
                            foreach ($items as $xis => $iSpec) {
                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xis;
                                if (isset($items[$id])) {
                                    $items[$id][$key] = $val;
                                }
                            }
                            foreach ($gate[$target] as $xis => $iSpec) {
                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xis;
                                $gate[$target][$id][$key] = $val;
                            }
                        }
                    }

                    //===signature
                    $dwsign = $tr->writeSignature($insertID, array(
                        "nomer" => $main['nomer'],
                        "step_number" => 1,
                        "step_code" => $this->jenisTr,
                        "step_name" => $this->configUi[$this->jenisTr]['steps'][1]['label'],
                        "group_code" => $this->configUi[$this->jenisTr]['steps'][1]['userGroup'],
                        "oleh_id" => $pihakMainID,
                        "oleh_nama" => $pihakMainName,
                        "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh sys",
                        "transaksi_id" => $insertID,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    $idHis = array(
                        $stepNumber => array(
                            "step" => $stepNumber,
                            "trID" => $insertID,
                            "nomer" => $tmpNomorNota,
                            "counters" => $appliedCounters,
                            "counters_intext" => $appliedCounters_inText,
                        ),
                    );
                    $idHis_blob = blobEncode($idHis);
                    $idHis_intext = print_r($idHis, true);
                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array("id" => $insertID), array(
                        "next_step_num" => $nextProp['num'],
                        "next_step_code" => $nextProp['code'],
                        "next_step_label" => $nextProp['label'],
                        "next_group_code" => $nextProp['groupID'],

                        //===references
                        "id_master" => $insertID,
                        "id_top" => $insertID,
                        "ids_prev" => "",
                        "ids_prev_intext" => "",
                        "nomer_top" => $main['nomer'],
                        "nomers_prev" => "",
                        "nomers_prev_intext" => "",
                        "jenises_prev" => "",
                        "jenises_prev_intext" => "",
                        "ids_his" => $idHis_blob,
                        "ids_his_intext" => $idHis_intext,
                    )) or die("Failed to update tr next-state!");

                    $addValues = array(
                        //===references
                        "id_master" => $insertID,
                        "id_top" => $insertID,
                        "ids_prev" => "",
                        "ids_prev_intext" => "",
                        "nomer_top" => $main['nomer'],
                        "nomers_prev" => "",
                        "nomers_prev_intext" => "",
                        "jenises_prev" => "",
                        "jenises_prev_intext" => "",
                        "ids_his" => $idHis_blob,
                        "ids_his_intext" => $idHis_intext,
                    );
                    foreach ($addValues as $key => $val) {
                        $tableIn_master[$key] = $val;
                    }
                }
                if (sizeof($tableIn_master_values) > 0) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                        $inserMainValues = array();
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                            if (isset($tableIn_master_values[$key])) {
                                $dd = $tr->writeMainValues($insertID, array(
                                    "key" => $key,
                                    "value" => $tableIn_master_values[$key],
                                ));
                                $inserMainValues[] = $dd;
                                $mongoList['mainValues'][] = $dd;
                            }
                        }
                        if (sizeof($inserMainValues) > 0) {
                            $arrBlob = blobEncode($inserMainValues);
                            $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                        }
                    }
                }
                if (sizeof($main_add_values) > 0) {
                    $inserMainValues = array();
                    foreach ($main_add_values as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoList['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }
                }
                if (sizeof($main_inputs) > 0) {
                    foreach ($main_inputs as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoList['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }
                }
                if (sizeof($main_add_fields) > 0) {
                    foreach ($main_add_fields as $key => $val) {
                        $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                    }
                }
                if (sizeof($main_elements) > 0) {
                    foreach ($main_elements as $elName => $aSpec) {
                        $tr->writeMainElements($insertID, array(
                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                            "name" => $aSpec['name'],
                            "label" => isset($aSpec['label']) ? $aSpec['label'] : "",
                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",
                        ));

                        //==nebeng bikin inputLabels
                        $currentValue = "";
                        switch ($aSpec['elementType']) {
                            case "dataModel":
                                $currentValue = $aSpec['key'];
                                break;
                            case "dataField":
                                $currentValue = $aSpec['value'];
                                break;
                        }
                        if (array_key_exists($elName, $relOptionConfigs)) {
                            if (isset($relOptionConfigs[$elName][$currentValue])) {
                                if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
                                    foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
                                        $inputLabels[$oValueName] = $oValSpec['label'];
                                        if (isset($oValSpec['auth'])) {
                                            if (isset($oValSpec['auth']['groupID'])) {
                                                $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                            }
                        }
                    }
                }
                if (sizeof($tableIn_detail) > 0) {
                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($tableIn_detail as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        $insertIDs[] = $insertDetailID;
                        $insertDeIDs[$insertID][] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                            $insertIDs[] = $insertEpID;
                            $insertDeIDs[$epID][] = $insertEpID;
                            $mongoList['detail'][] = $insertEpID;
                        }
//                                cekUngu("LINE: " . __LINE__ . " <br> " . $this->db->last_query());
                    }
                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }
                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                            cekOrange($this->db->last_query());
                        }
                    }
                }
                if (sizeof($tableIn_detail2) > 0) {
                    $insertIDs = array();
                    foreach ($tableIn_detail2 as $dSpec) {
                        $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                        $mongoList['detail'] = $insertIDs;
                        if ($epID != 999) {
                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                            $mongoList['detail'] = $insertIDs;
                        }
//                                cekUngu($this->db->last_query());
                    }
                }
                if (sizeof($tableIn_detail2_sum) > 0) {
                    $insertIDs = array();
                    foreach ($tableIn_detail2_sum as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        $insertIDs[] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;

                        if ($epID != 999) {
                            $insertDetailID = $tr->writeDetailEntries($epID, $dSpec);
                            $insertIDs[] = $insertDetailID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                    }
                cekOrange($this->db->last_query());
                }
                if (sizeof($tableIn_detail_rsltItems) > 0) {
                    $insertIDs = array();
                    foreach ($tableIn_detail_rsltItems as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        $insertIDs[] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;
                        if ($epID != 999) {
                            $insertDetailID = $tr->writeDetailEntries($epID, $dSpec);
                            $insertIDs[] = $insertDetailID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                    cekUngu($this->db->last_query());
                    }
                }
                if (sizeof($tableIn_detail_values) > 0) {
                    foreach ($tableIn_detail_values as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                            $insertIDs = array();
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                if (isset($tableIn_detail[$pID])) {
                                    $dd = $tr->writeDetailValues($insertID, array(
                                        "produk_jenis" => $tableIn_detail[$pID]['produk_jenis'],
                                        "produk_id" => $pID,
                                        "key" => $key,
                                        "value" => $dSpec[$src],
                                    ));
                                    $insertIDs[$pID][] = $dd;
                                    $mongoList['detailValues'][] = $dd;
                                }
                            cekLime($this->db->last_query());
                            }
                            if (sizeof($insertIDs) > 0) {
                                $arrBlob = blobEncode($insertIDs);
                                $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                            }
                        }
                    }
                }
                if (sizeof($tableIn_detail_values2_sum) > 0) {
                    foreach ($tableIn_detail_values2_sum as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $tableIn_detail2_sum[$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => $dSpec[$src],
                                ));
                                $insertIDs[] = $dd;
                                $mongoList['detailValues'][] = $dd;
                            }
                        }
                    }
                }
                //endregion

                //===components akan langsung dieksekusi jika steps-nya tidak pakai approval
                $steps = $this->configUi[$this->jenisTr]['steps'];

                $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
                $filterNeeded = false;

                //====registri value-gate
                $baseRegistries = array(
                    'main' => sizeof($main) > 0 ? $main : array(),
                    'items' => sizeof($items) > 0 ? $items : array(),
                    'items2' => sizeof($items2) > 0 ? $items2 : array(),
                    'items2_sum' => sizeof($items2_sum) > 0 ? $items2_sum : array(),
                    'items3' => sizeof($items3) > 0 ? $items3 : array(),
                    'items3_sum' => sizeof($items3_sum) > 0 ? $items3_sum : array(),
                    'rsltItems' => sizeof($rsltItems) > 0 ? $rsltItems : array(),
                    'rsltItems2' => sizeof($rsltItems2) > 0 ? $rsltItems2 : array(),
                    'tableIn_master' => sizeof($tableIn_master) > 0 ? $tableIn_master : array(),
                    'tableIn_detail' => sizeof($tableIn_detail) > 0 ? $tableIn_detail : array(),
                    'tableIn_detail2_sum' => sizeof($tableIn_detail2_sum) > 0 ? $tableIn_detail2_sum : array(),
                    'tableIn_detail_rsltItems' => sizeof($tableIn_detail_rsltItems) > 0 ? $tableIn_detail_rsltItems : array(),
                    'tableIn_detail_rsltItems2' => sizeof($tableIn_detail_rsltItems2) > 0 ? $tableIn_detail_rsltItems2 : array(),
                    'tableIn_master_values' => sizeof($tableIn_master_values) > 0 ? $tableIn_master_values : array(),
                    'tableIn_detail_values' => sizeof($tableIn_detail_values) > 0 ? $tableIn_detail_values : array(),
                    'tableIn_detail_values_rsltItems' => sizeof($tableIn_detail_values_rsltItems) > 0 ? $tableIn_detail_values_rsltItems : array(),
                    'tableIn_detail_values_rsltItems2' => sizeof($tableIn_detail_values_rsltItems2) > 0 ? $tableIn_detail_values_rsltItems2 : array(),
                    'tableIn_detail_values2_sum' => sizeof($tableIn_detail_values2_sum) > 0 ? $tableIn_detail_values2_sum : array(),
                    'main_add_values' => sizeof($main_add_values) > 0 ? $main_add_values : array(),
                    'main_add_fields' => sizeof($main_add_fields) > 0 ? $main_add_fields : array(),
                    'main_elements' => sizeof($main_elements) > 0 ? $main_elements : array(),
                    'main_inputs' => sizeof($main_inputs) > 0 ? $main_inputs : array(),
                    'main_inputs_orig' => sizeof($main_inputs) > 0 ? $main_inputs : array(),
                    "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                    "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                    "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                    "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                );

                $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));

                $mongRegID[] = $doWriteReg;

                //region processing sub-post-processors, always items
                $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][1]['detail'] : array();
                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $tmpOutParams[$cCtr] = array();
                        foreach ($gate[$srcGateName] as $cnt => $dSpec) {
                            $subParams = array();
                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {
                                    $realValue = makeValue($value, $gate[$srcGateName][$cnt], $gate[$srcGateName][$cnt], 0);
                                    $subParams['loop'][$key] = $realValue;
                                }
                            }
                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {
                                    $realValue = makeValue($value, $gate[$srcGateName][$cnt], $gate[$srcGateName][$cnt], 0);
                                    $subParams['static'][$key] = $realValue;
                                }
                                if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                                    foreach ($paramPatchers[$comName] as $k => $v) {
                                        if (!isset($subParams['static'][$k])) {
                                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                        }
                                    }
                                }
                                if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                                    $jenis = $gate['main']['jenis'];
                                    foreach ($paramForceFillers[$comName] as $k => $v) {
                                        $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    }
                                }
                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                            }
                            if (sizeof($subParams) > 0) {
                                $tmpOutParams[$cCtr][] = $subParams;
                            }
                        }
                    }

                    foreach ($iterator as $cCtr => $tComSpec) {
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $mdlName = "Com" . ucfirst($comName);
                        $this->load->model("Coms/" . $mdlName);
                        $m = new $mdlName();
                        $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $m->exec() or die("Gagal saat berusaha exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                    }
                }

                // endregion
                //region writelog
                $this->load->model("Mdls/" . "MdlActivityLog");
                $hTmp = new MdlActivityLog();
                $tmpHData = array(
                    "title" => $main['jenisTrName'],
                    "sub_title" => "New Pre Order From APK",
                    "uid" => $pihakMainID,
                    "uname" => $pihakMainName,
                    "dtime" => date("Y-m-d H:i:s"),
                    "transaksi_id" => $insertID,
                    "deskripsi_old" => "",
                    "deskripsi_new" => "",
                    "jenis" => $this->jenisTr,
                    "ipadd" => $_SERVER['REMOTE_ADDR'],
                    "devices" => $_SERVER['HTTP_USER_AGENT'],
                    "category" => "apk_transaksi",
                    "controller" => $this->uri->segment(1),
                    "method" => $this->uri->segment(2),
                    "url" => "",
                );
                $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));

            }
        }

//        mati_disini("============= BELUM COMMIT ===============");
//         or die("Gagal saat berusaha  commit transaction!");

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

            $result=array(
                "status" => 1,
                "mainID" => $insertID,
            );

            echo json_encode($result);
        }
        else{
            $result=array(
                "status" => 0,
                "reason" => "gagal commit",
            );
            echo json_encode($result);
        }
//        mati_disini("============= BERHASIL COMMIT ===============");
    }

    public function randomCollector(){
        $this->load->library("Curl");
        $curl = New Curl();
        $writer = $curl->collectorSendToApk();
        print_r($writer);
        echo "masuk toooo COLLECTOR";
    }
    public function randomLogistik(){
        $this->load->library("Curl");
        $curl = New Curl();
        $writer = $curl->logistikSendToApk();
        print_r($writer);
        echo "masuk toooo LOGISTIK";
    }

    public function syncCustomer(){
        $this->load->library("Curl");
        $curl = New Curl();

        $url = ADM_DOMAIN . "run_sakura_apk/eusvc/Entries/syncCustomerToApk";
        $toko_id = "1001";

        $this->load->model("Mdls/MdlCustomer");
        $pr = new MdlCustomer();
        $pr->addFilter("toko_id=$toko_id");
        $prdTmp = $pr->lookupAll()->result();

        $arrCustomer=array();
        foreach($prdTmp as $k => $dCustomer){
            $arrCustomer[$dCustomer->id] = $dCustomer;
        }

        $writer = $curl->syncCustomerToApk($url, $arrCustomer);
    }
    public function syncProduk(){
        $this->load->library("Curl");
        $curl = New Curl();

        $url = ADM_DOMAIN . "/eusvc/Entries/syncProdukToApk";
        $toko_id = "1001";

        //region inisiasi produk
        $this->load->model("Mdls/MdlProduk");
        $pr = new MdlProduk();
        $pr->addFilter("toko_id=$toko_id");
        $prdTmp = $pr->lookupAll()->result();

        $arrProduk=array();
        foreach($prdTmp as $k => $dProduk){
            $arrProduk[$dProduk->id] = $dProduk;
        }

        $arrPrice=array();
        $this->load->model("Mdls/MdlHargaProduk");
        $hr = new MdlHargaProduk();
        $hr->addFilter("jenis_value='jual'");
        $hr->addFilter("status=1");
        $hr->addFilter("trash=0");
        $hr->addFilter("toko_id=$toko_id");
        $prdHrg = $hr->lookupAll()->result();

        if(!empty($prdHrg)){
            foreach($prdHrg as $pid => $listH ){
                $arrPrice[$listH->produk_id] = $listH;
            }
        }

        $produkPrice = array();
        if(!empty($arrProduk)){
            foreach($arrProduk as $ids => $datas){
                $produkPrice[$ids] = (array)$datas;
                if(isset($arrPrice[$ids])){
                    if(!isset($produkPrice[$ids]["harga_jual"])){
                        $produkPrice[$ids]["harga_jual"] = 0;
                    }
                    $produkPrice[$ids]["harga_jual"] = $arrPrice[$ids]->nilai*1;
                }
            }
        }

        $writer = $curl->syncProdukToApk($url, $produkPrice);

    }
    public function syncEmployee(){
        $this->load->library("Curl");
        $curl = New Curl();

        $url = ADM_DOMAIN . "/eusvc/Entries/syncEmployeeToApk";
        $toko_id = "1001";

        $this->load->model("Mdls/MdlEmployeeCabang");
        $pr = new MdlEmployeeCabang();
        $pr->addFilter("toko_id=$toko_id");
        $prdTmp = $pr->lookupAll()->result();

        $arrEmployee=array();
        foreach($prdTmp as $k => $dEmployee){
            $arrEmployee[$dEmployee->id] = $dEmployee;
        }

        $this->load->model("Mdls/MdlEmployeeGudang");
        $prG = new MdlEmployeeGudang();
        $prG->addFilter("toko_id=$toko_id");
        $prdTmpG = $prG->lookupAll()->result();

//        $arrEmployee=array();
        foreach($prdTmpG as $k => $dEmployee){
            $arrEmployee[$dEmployee->id] = $dEmployee;
        }

        $writer = $curl->syncEmployeeToApk($url, $arrEmployee);
    }
    public function syncCompany(){
        $this->load->library("Curl");
        $curl = New Curl();

        $url = ADM_DOMAIN."/eusvc/Entries/syncCompanyToApk";
        $toko_id = "1001";

        $this->load->model("Mdls/MdlCompany");
        $pr = new MdlCompany();
        $pr->addFilter("toko_id=$toko_id");
        $prdTmp = $pr->lookupAll()->result();

        $arrCompany=array();
        foreach($prdTmp as $k => $dCompany){
            $arrCompany[$dCompany->id] = $dCompany;
        }

        $writer = $curl->syncCompanyToApk($url, $arrCompany);
    }

    public function doCreateTransaksi(){

        $arr = $_REQUEST;

        $cabang_id      = $arr['cabang_id'];
        $toko_id        = $arr['toko_id'];
        $penagih_id     = $arr['oleh_id'];
        $externID       = $arr['customer_id']; // customer
        $selectedTrID   = $arr['transaksi_id'];
        $targetJenis    = $arr['targetJenis'];
        $nilai_entry    = $arr['nilai_entry'];
        $payment_gate   = $arr['payment_gate'];

        $apkLogin = json_decode($arr['login'],true);

        //get data login
        $arrLogin = $this->authCheck($penagih_id);

        $this->jenisTr = $targetJenis;

        $selectorProcess=array();

        $id = $selectedTrID;

        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("transaksi_payment_source.cabang_id='" . $arrLogin['cabang_id'] . "'");
        $tr->addFilter("transaksi_payment_source.toko_id='" . $toko_id . "'");
//        if ($targetJenis == "749") {
//            $tr->addFilter("transaksi_payment_source.penagih_id='" . $penagih_id . "'");
//        }
        $tr->addFilter("extern_id='$externID'");
        $tr->addFilter("sisa>0");

        if($selectedTrID>0){
            $tr->addFilter("transaksi_id='$selectedTrID'");
        }

        $tmpSrc = $tr->lookupPaymentSrcByJenis_joined($targetJenis)->result();
        $queris = $this->db->last_query();
//        echo json_encode($queris) . "\n";
//        echo json_encode($arrLogin);

        $tmpSelectedNota = array(
            "transaksi_id",
            "nomer",
            "extern_id",
            "tagihan",
            "terbayar",
            "sisa",
            "diskon",
            "extern_nama",
            "tagihan_valas",
            "terbayar_valas",
            "sisa_valas",
            "diskon_valas",
            "valas_id",
            "valas_nama",
            "valas_nilai",
            "id_master",
            "extern_label2",
            "extern_nilai2",
            "extern_nilai3",
            "extern_nilai4",
            "pph_23",
            "ppn_sisa",
            "ppn",
            "extern2_id",
            "extern2_nama",
            "extern_jenis",
            "jenis_master",
            "state",
        );

        $selectedNota = array();

        foreach($tmpSrc as $kk => $arr){
            foreach($tmpSelectedNota as $key => $vVal){
                $selectedNota[$vVal] = $arr->$vVal;
            }
        }

        $selectedNota["state"] = "true";

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

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

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

            $selectorProcess['main']['refIDs'] = array();

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

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

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

            //tambahan baru
            "bank_asal_nama"       => $selectedNota['bank_asal_nama'],
            "bank_tujuan_nama"     => $selectedNota['bank_tujuan_nama'],
            "bank_asal_no"         => $selectedNota['bank_asal_no'],
            "bank_tujuan_no"       => $selectedNota['bank_tujuan_no'],
            "bank_asal_alias"      => $selectedNota['bank_asal_alias'],
            "bank_tujuan_alias"    => $selectedNota['bank_tujuan_alias'],
            "cdn_img_url"          => $selectedNota['cdn_img_url'],
            "giro_jatuh_tempo"     => $selectedNota['giro_jatuh_tempo'],
            "trf_effective_date"   => $selectedNota['trf_effective_date'],
            "apk_produk_blob"      => $selectedNota['produk_blob'],
        );

        foreach ($initMain as $key => $src) {
            $selectorProcess['main'][$key] = $src;
        }
        $row = $selectedNota;

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

        if (!array_key_exists($id, $selectorProcess['items'])) {
            $tmp = array(
                "handler" => $this->uri->segment(1),
                "id" => $id,
                "refID" => $id,
                "jml" => 1,
                "harga" => 0,
                "satuan" => "-",
                "subtotal" => 0,
            );

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

                }
                if (sizeof($relativeComNameDetails) > 0) {
                    $key = isset($selectorProcess['main']['pihakMainName']) ? $selectorProcess['main']['pihakMainName'] : "";
                    $tmp['relativeCom'] = isset($relativeComNameDetails[$key]) ? $relativeComNameDetails[$key] : "";
                    $tmp['rekName'] = isset($selectorProcess['main']['pihakMainName']) ? $selectorProcess['main']['pihakMainName'] : "";
                }
            }
        }
        else {
//            cekMerah("TIDAK akan memasukkan ITEMS");
        }

        $selectorProcess['main']['refIDs'][$id] = $id;

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

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

                }
                else {

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

                            unset($selectorProcess['main'][$val]);

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

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

                    $selectorProcess['items2_sum'][$eSpec['id']]['jml'] += $eSpec['jml'];
                    $selectorProcess['items2_sum'][$eSpec['id']]['harga'] += $eSpec['harga'];
                    $selectorProcess['items2_sum'][$eSpec['id']]['produk_ids'][$pID] = $pID;
                    if (sizeof($relativeComNameDetails) > 0) {
                        $key = isset($selectorProcess['main']['pihakMainName']) ? $selectorProcess['main']['pihakMainName'] : "";
                        cekHere($key);
                        cekHere("$relativeComNameDetails[$key] " . $relativeComNameDetails[$key]);
                        $selectorProcess['items2_sum'][$eSpec['id']]['relativeCom'] = isset($relativeComNameDetails[$key]) ? $relativeComNameDetails[$key] : "";
                        $selectorProcess['items2_sum'][$eSpec['id']]['rekName'] = isset($selectorProcess['main']['pihakMainName']) ? $selectorProcess['main']['pihakMainName'] : "";
                    }
                }
            }
        }
        if (sizeof($selectorProcess['items2_sum']) > 0) {
            foreach ($selectorProcess['items2_sum'] as $bID => $pSpec) {
                $selectorProcess['items2_sum'][$bID]['produk_ids'] = serialize(base64_encode($pSpec['produk_ids']));
            }
        }

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

        $selectorProcess['tableIn_master']['lat'] = htmlspecialchars($apkLogin['Latitude']);
        $selectorProcess['tableIn_master']['lng'] = htmlspecialchars($apkLogin['Longitude']);
        $selectorProcess['tableIn_master']['accuracy'] = htmlspecialchars($apkLogin['Accuracy']);

        //handle receipt element
//        $selectorProcess['main_elements']['cash_account'] = $payment_gate;
//        arrPrintWebs($selectedNota);

        $selectorProcess['add_rows'] = array(
            "amount" => $selectedNota['sisa'], //ambil sisa dari payment source
            "credit_amount" => 0,
            "harus_bayar" => $selectedNota['sisa'], //ambil sisa dari payment source
            "nilai_entry" => $nilai_entry,
            "new_sisa" => ($selectedNota['sisa']*1) - ($nilai_entry*1),
            "total_disc" => 0,
        );

        $this->setReceiptElementTmp(array());
        $this->setReceiptElementTmp($selectorProcess);

        $receiptElement = array();
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                $elementConfigs[$eName]['autoSelect'] = false;
                if (!isset($this->receiptElementTmp['main_elements'][$eName])) {
                    //==cek apakah ada seting defaultValue
                    if (isset($eSpec['defaultValue'])) {
                        $defValueSrc = $eSpec['defaultValue'];
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                $this->heFetchElement_he_element($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $this->configUiJenis, $this->receiptElementTmp);
                                break;
                            case "dataField":
                                $this->heRecordElement_he_element($this->jenisTr, $eName, $defValueSrc, $this->configUiJenis, $this->receiptElementTmp);
                                break;
                        }
                        $elementConfigs[$eName]['autoSelect'] = true;
                    }
                    else {
                        //==cek apakah pilihannya cuma satu
                        if (isset($eSpec['noPrefetch']) && $eSpec['noPrefetch'] == true) {

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

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

        //manual select pembayaran
        $this->heFetchElement_he_element($this->jenisTr, "cash_account", "MdlBankAccount_cash_and_in", $payment_gate, $this->configUiJenis, $this->receiptElementTmp);


        $this->load->library("ValueGate");

        $vg = new ValueGate();

        $vg->setConfigUiJenis($this->configUi[$this->jenisTr]);
        $vg->setConfigCoreJenis($this->configCore[$this->jenisTr]);
        $vg->setConfigValuesJenis($this->configValues[$this->jenisTr]);
        $vg->setPpnFactor($ppnFactor);

        $initMasterValues = array(
            "olehID"        => $arrLogin["id"],
            "olehName"      => $arrLogin["nama_login"],
            "placeID"       => $arrLogin["cabang_id"],
            "placeName"     => $arrLogin["cabang_nama"],
            "divID"         => isset($arrLogin["div_id"]) ? $arrLogin["div_id"] : 0,
            "divName"       => isset($arrLogin["div_nama"]) ? $arrLogin["div_nama"] : "-",
            "cabangID"      => $arrLogin["cabang_id"],
            "cabangName"    => $arrLogin["cabang_nama"],
            "gudangID"      => $arrLogin["gudang_id"],
            "gudangName"    => $arrLogin["gudang_nama"],
            "jenis_usaha"   => $arrLogin["jenis_usaha"],
            "tokoID"        => $arrLogin["toko_id"],
            "tokoNama"      => isset($arrLogin["toko_nama"]) ? $arrLogin["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"),
        );

        $resultBuildValue = $vg->buildValueNS($this->jenisTr, $id, $initMasterValues, $this->modul, $this->receiptElementTmp);

//        $resultBuildValue["bla_bla"]  = $arr;
//        $resultBuildValue["queris"]  = $queris;

//        echo json_encode($resultBuildValue);

//        arrPrint($this->receiptElementTmp);
        arrPrintWebs($resultBuildValue);
//        matiHere();
//        $this->save( $resultBuildValue );

    }

    public function doCreateReturnTransaksi(){


        $arr = $_REQUEST;

        $cabang_id      = $arr['cabang_id'];
        $toko_id        = $arr['toko_id'];
        $oleh_id        = $arr['oleh_id'];
        $externID       = $arr['customer_id']; // customer
        $description    = $arr['description']; // customer

        $arrProduk      = json_decode(base64_decode($arr['produk']),true);
        $apkLogin = json_decode($arr['login'],true);

        //get data login
        $arrLogin = $this->authCheck($oleh_id);
        $selectorProcess=array();
        $selectorProcess['items'] = array();

        $pihakMainValueSrc  = isset($this->configUi[$this->jenisTr]['pihakMainValueSrc']) ? $this->configUi[$this->jenisTr]['pihakMainValueSrc'] : array();
        $pihakValidate      = isset($this->configUi[$this->jenisTr]['pihakValidate']) ? $this->configUi[$this->jenisTr]['pihakValidate'] : array();
        $pihakAddValidate   = isset($this->configUi[$this->jenisTr]['pihakAddValidate']) ? $this->configUi[$this->jenisTr]['pihakAddValidate'] : array();

        //select customer
        $this->load->model("Mdls/MdlCustomer");
        $b = new MdlCustomer();
        $tmpB = $b->lookupByID($externID)->result();

        //---------------------------------------------------
        if (sizeof($pihakValidate) > 0) {
            foreach ($pihakValidate as $kolom => $spec) {
                if (isset($tmpB[0]->$kolom) && ($tmpB[0]->$kolom != NULL)) {
                    $result = $tmpB[0]->$kolom;
                    $tb_kolom = $spec['result'][$result]['kolom'];
                    $tb_label = $spec['result'][$result]['label'];
                    if (isset($tmpB[0]->$tb_kolom) && ($tmpB[0]->$tb_kolom != NULL)) {
                        cekHijau("LANJUT...");
                    }
                    else {
                        $label = $tmpB[0]->nama . ", " . $tb_label;
                        die(lgShowAlertBiru($label));
                    }
                }
                else {
                    $label = $tmpB[0]->nama . ", " . $spec['result']['none']['label'];
                    die(lgShowAlertBiru($label));
                }
            }
        }
        if (sizeof($pihakAddValidate) > 0) {
            $addMode = isset($pihakAddValidate['mode']) ? $pihakAddValidate['mode'] : NULL;
            $addFilter = isset($pihakAddValidate['filter']) ? $pihakAddValidate['filter'] : array();
            if (sizeof($addFilter) > 0) {
                foreach ($addFilter as $kf => $vf) {
                    cekHere(":: $kf => $vf :: $addMode ::");
                    switch ($addMode) {
                        case "!=":
                            if ($tmpB[0]->$kf != $vf) {
                                $label = $pihakAddValidate['label'][$kf];
                                die(lgShowAlertBiru($label));
                            }
                            break;
                        case "==":
                            if ($tmpB[0]->$kf == $vf) {
                                $label = $pihakAddValidate['label'][$kf];
                                die(lgShowAlertBiru($label));
                            }
                            break;
                        default:
                            cekHitam(":: masuk sini, default ::");
                            break;
                    }
                }
            }
        }

        //---------------------------------------------------

        if (isset($this->configUi[$this->jenisTr]["pihakMainNota"]) && $this->configUi[$this->jenisTr]["pihakMainNota"] == true) {
            $selectColumn = "nomer";
        }
        else {
            $selectColumn = "nama";
        }

        if (sizeof($tmpB) > 0) {
            $phakSpeks = $tmpB[0];
            $pihakLevel = isset($phakSpeks->level_id) ? $phakSpeks->level_id : 0;
            $selectorProcess['main']['pihakLevel']     = $pihakLevel;
            $selectorProcess['main']['pihakLevelNama'] = isset($phakSpeks->level_nama) ? $phakSpeks->level_nama : '';
            $selectorProcess['main']['pihakDisc']      = isset($tmpB[0]->diskon) ? $tmpB[0]->diskon : "";
            $selectorProcess['main']['pihakID']        = $externID;
            $selectorProcess['main']['pihakName']      = isset($tmpB[0]->$selectColumn) ? $tmpB[0]->$selectColumn : "";
            $selectorProcess['main']['pihakName2']     = isset($tmpB[0]->$selectColumn) ? formatNota($selectColumn, $tmpB[0]->$selectColumn) : "";
            $tmpPihakName = isset($tmpB[0]->$selectColumn) ? formatNota($selectColumn, $tmpB[0]->$selectColumn) : "";
            if (isset($tmpB[0]->name)) {
                $tmpPihakName = $tmpB[0]->name;
            }
            if (sizeof($pihakMainValueSrc) > 0) {
                foreach ($pihakMainValueSrc as $key => $src) {
                    $selectorProcess['main'][$key] = $tmpB[0]->$src;
                }
            }
        }
        //select customer

        $selectorProcess['main']['description'] = htmlspecialchars($description);

        $selectorProcess['tableIn_master']['lat'] = htmlspecialchars($apkLogin['Latitude']);
        $selectorProcess['tableIn_master']['lng'] = htmlspecialchars($apkLogin['Longitude']);
        $selectorProcess['tableIn_master']['accuracy'] = htmlspecialchars($apkLogin['Accuracy']);
//        $selectorProcess['tableIn_master']['gudang_id'] = -99;
//        $selectorProcess['tableIn_master']['gudang_nama'] = "gudang return";

        //region select produk
        $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();

        $checkProdukValid =array();

        foreach($arrProduk as $pid => $pdata){
            $id = $produk_id = $pid;
            $pihakID = $externID;
            $satuan_factor_qty = $pdata['satuan_factor_qty'];
            $jml = $pdata['produk_qty'];
            $qty_unit = $pdata['qty_unit']; //total unit
            $gudang_source_id = $pdata['gudang_id']; //saat beli terakhir dari gudang mana?

            $this->load->model("Mdls/MdlProduk");
            $b = new MdlProduk();
            $tmpB = $b->lookupByID($id)->result();

            if (sizeof($tmpB) > 0) {
                foreach ($tmpB as $row) {
                    $rows = $row;
                    $fieldSrcs = isset($this->configUi[$this->jenisTr]['shoppingCartFieldSrc']) ? $this->configUi[$this->jenisTr]['shoppingCartFieldSrc'] : array("nama" => "nama");
                    $tmp = array(
                        "handler" => $this->modul . "/" . $this->uri->segment(2),
                        "id" => $id,
                        "jml" => $jml,
                        "nama" => $row->nama,
                        "name" => $jml->name,
                        "qty_unit" => $qty_unit,
                        "gudang_id" => $gudang_source_id,
                        "harga" => 0,
                        "subtotal" => 0,
                        "satuan" => strlen($rows->satuan) > 0 ? $rows->satuan : "n/a",
                        "satuan_factor_nama" => $pdata['satuan_factor_nama'],
                        "satuan_factor_qty" => $satuan_factor_qty,
                    );

                    if (sizeof($priceMainConfig) > 0) {
                        if (isset($priceMainConfig[$selectorProcess['main']['pihakMainName']])) {
                            $priceConfig = $priceMainConfig[$selectorProcess['main']['pihakMainName']];
                            cekUngu("masuk disini...");
                        }
                    }
                    $this->load->model("Mdls/MdlLockerStockPenjualanCache");
                    $pr = new MdlLockerStockPenjualanCache();
                    $pr->addFilter("extern_id='$id'");
                    $pr->addFilter("extern2_id='$pihakID'");
                    $pr->addFilter("saldo_qty>0");
                    $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;
                            }
                        }
                    }
                    else{
                        $checkProdukValid[$produk_id] = array(
                            "p_nama" => $rows->nama,
                            "reason" => "STOK RETURN KOSONG",
                        );
                    }
//                    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 (sizeof($itemNumLabels) > 0) {
                        foreach ($itemNumLabels as $key => $label) {
                            if (isset($_GET[$key]) && $_GET[$key] > 0) {
                                $newValue = $_GET[$key];
                                $tmp[$key] = $newValue;
                            }
                        }
                    }
                    if ($subAmountConfig != null) {
                        $tmp['subtotal'] = makeValue($subAmountConfig, $tmp, $tmp, 0);
                    }
                    else {
                        $tmp['subtotal'] = 0;
                    }
                    $selectorProcess['items'][$produk_id] = $tmp;
                }
            }
            else {
                cekMerah("tidak ada itemnya! @" . __LINE__ . " " . __METHOD__);
                die();
            }
        }

        if(!empty($checkProdukValid)){
            $txtError = "";
            foreach($checkProdukValid as $pi => $res){
                $txtError .= "<div>".$res['p_nama']." => ".$res['reason']."</div>";
            }
            $result = array(
                "status" => 0,
                "reason" => $txtError,
            );
            echo json_encode($result);
            die();
        }

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

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

        $this->setReceiptElementTmp(array());
        $this->setReceiptElementTmp($selectorProcess);

        cekMerah("selectorProcess");
        arrPrint($selectorProcess);

        $receiptElement = array();
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                $elementConfigs[$eName]['autoSelect'] = false;
                if (!isset($this->receiptElementTmp['main_elements'][$eName])) {
                    //==cek apakah ada seting defaultValue
                    if (isset($eSpec['defaultValue'])) {
                        $defValueSrc = $eSpec['defaultValue'];
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                $this->heFetchElement_he_element($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $this->configUiJenis, $this->receiptElementTmp);
                                break;
                            case "dataField":
                                $this->heRecordElement_he_element($this->jenisTr, $eName, $defValueSrc, $this->configUiJenis, $this->receiptElementTmp);
                                break;
                        }
                        $elementConfigs[$eName]['autoSelect'] = true;
                    }
                    else {
                        //==cek apakah pilihannya cuma satu
                        if (isset($eSpec['noPrefetch']) && $eSpec['noPrefetch'] == true) {

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

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

        //manual select pembayaran
//        $this->heFetchElement_he_element($this->jenisTr, "cash_account", "MdlBankAccount_cash_and_in", $payment_gate, $this->configUiJenis, $this->receiptElementTmp);
        $this->heFetchElement_he_element($this->jenisTr, "gudangReturn", "MdlGudangNG", -99, $this->configUiJenis, $this->receiptElementTmp);

        $this->load->library("ValueGate");

        $vg = new ValueGate();

        $vg->setConfigUiJenis($this->configUi[$this->jenisTr]);
        $vg->setConfigCoreJenis($this->configCore[$this->jenisTr]);
        $vg->setConfigValuesJenis($this->configValues[$this->jenisTr]);
        $vg->setPpnFactor($ppnFactor);

        $initMasterValues = array(
            "olehID"        => $arrLogin["id"],
            "olehName"      => $arrLogin["nama_login"],
            "placeID"       => $arrLogin["cabang_id"],
            "placeName"     => $arrLogin["cabang_nama"],
            "divID"         => isset($arrLogin["div_id"]) ? $arrLogin["div_id"] : 0,
            "divName"       => isset($arrLogin["div_nama"]) ? $arrLogin["div_nama"] : "-",
            "cabangID"      => $arrLogin["cabang_id"],
            "cabangName"    => $arrLogin["cabang_nama"],
            "gudangID"      => $this->receiptElementTmp['main']['gudangReturn'],
            "gudang_id"     => $this->receiptElementTmp['main']['gudangReturn'],
            "gudangName"    => $this->receiptElementTmp['main']['gudangReturn__nama'],
            "gudang_nama"   => $this->receiptElementTmp['main']['gudangReturn__nama'],
            "jenis_usaha"   => $arrLogin["jenis_usaha"],
            "tokoID"        => $arrLogin["toko_id"],
            "tokoNama"      => isset($arrLogin["toko_nama"]) ? $arrLogin["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"),
        );

        $resultBuildValue = $vg->buildValueNS($this->jenisTr, $id, $initMasterValues, $this->modul, $this->receiptElementTmp);
        cekMerah("LINE: " . __LINE__ );
//        $resultBuildValue["bla_bla"]  = $arr;
//        $resultBuildValue["queris"]  = $queris;
//        echo json_encode($resultBuildValue);
//        arrPrint($this->receiptElementTmp);
//        arrPrintWebs($resultBuildValue);
//        echo json_encode($resultBuildValue);
//        matiHere();
        $this->save( $resultBuildValue );

    }

    public function authCheck($dpost)
    {

        $nama_login = $this->input->post('nama');
        $post_password = $this->input->post('password');

        $bypass = "on";

        $authProps = array(
            "MdlUser",
            "MdlPos",
            "MdlEmployee",
            "MdlEmployee__shadow",
            "MdlEmployeeCabang",
            "MdlEmployeeCabang__shadow",
            "MdlEmployeeGudang",
        );

        //==pairers
        //company profile grap jenis usaha
        $this->load->Model("Mdls/MdlCompany");
        $comPro = new MdlCompany();
        $tmpCompanyProfile = $comPro->lookupAll()->result();
        $companyProfil = array();
        $jn_usaha = $tmpCompanyProfile[0]->jenis_usaha;
        foreach ($tmpCompanyProfile as $rows) {
            $companyProfil["jenis_usaha"] = $rows->jenis_usaha;
        }

        $this->ci = $CI =& get_instance();
        //load dari config item pair pajak
        $masterPpnData = $CI->config->item("pairPajak");
        $masterPPN = $masterPpnData[$jn_usaha]["value"]["default"];

        $cabangs = array();
        $this->load->model("Mdls/MdlCabang");
        $cab = new MdlCabang();
        $tmpc = $cab->lookupAll()->result();
        if (sizeof($tmpc) > 0) {
            foreach ($tmpc as $row) {
                $_id = $row->id;
                $cabangs[$_id] = $row->nama;
            }
        }
        $divs = array();
        $this->load->model("Mdls/MdlDiv");
        $cab = new MdlDiv();
        $tmpc = $cab->lookupAll()->result();
        if (sizeof($tmpc) > 0) {
            foreach ($tmpc as $row) {
                $divs[$row->id] = $row->nama;
            }
        }
        $gudangs = array();
        $this->load->model("Mdls/MdlGudang");
        $cab = new MdlGudang();
        $tmpc = $cab->lookupAll()->result();
        if (sizeof($tmpc) > 0) {
            foreach ($tmpc as $row) {
                $_id = $row->id;
                $gudangs[$_id] = $row->nama;
            }
        }
        $loginProp = array();
        $nameField = "id";
        foreach ($authProps as $mdlName) {
            $this->load->model("Mdls/" . $mdlName);
            $u = new $mdlName();
            if ($bypass == 'on') {
                $tmpUser = $u->lookupByCondition(array(
                    $nameField => $dpost,
                ))->result();
            }
            else {
                $tmpUser = $u->lookupByCondition(array(
                    $nameField => $nama_login,
                    "password" => md5($post_password),
                    "status" => "1",
                ))->result();
            }

            if (sizeof($tmpUser) > 0) {
                $userProp   = $tmpUser[0];
                $login_fail = $userProp->login_fail;
                $email      = $userProp->email;

                if ($login_fail == 10) {
                    $arrAlert = array(
                        "type"  => "warning",
                        "title" => "Passsword Reseted",
                        "html"  => "please check your email and follow the link have been  sent to <b class='text-info'>$email</b> for confirm your account",
                    );
                    echo swalAlert($arrAlert);
                    die();
                }

                $arrAlert = array(
                    "html"              => "<img src='" . base_url() . "public/images/sys/loader-100.gif'> <br>Authenticating.<br>Please wait...<br>",
                    "showConfirmButton" => false,
                    "allowOutsideClick" => false,
                );

                foreach ($userProp as $field => $item) {
                    $$field = $item;
                }

                $sessionSwappers = array(
                    "id",
                    "nama_login",
                    "nama",
                    "phpsess_dtime",
                    "phpsessid",
                    "phpsessid",
                    "status",
                    "jenis",
                    "debuger",
                    "cabang_id",
                    "gudang_id",
                    "div_id",
                    "ghost",
                    "employee_type",
                    "jenis_usaha",
                    "toko_id",
                    "toko_nama",
                );
                $sessionUpdaters = array(
                    'phpsess_dtime' => dtimeNow(),
                    'phpsessid'     => $_COOKIE['ci_session'],
                    'ipadd'         => $_SERVER['REMOTE_ADDR'],
                    'devices'       => $_SERVER['HTTP_USER_AGENT'],
                    'membership'    => unserialize(base64_decode($userProp->membership)),
                    'longitude'     => "",
                    'lattitude'     => "",
                    'accuracy'      => "",
                    'status_login' => "1",
                );
                $tableUpdaters   = array(
                    "phpsessid" => "phpsessid",
                    "phpsess_dtime" => "phpsess_dtime",
                    "php_session"   => "php_session",
                    "ipadd"         => "ipadd",
                    "devices"       => "devices",
                    "last_dtime_active" => "phpsess_dtime",
                    'status_login' => "status_login",
                );

                $gudSpec_pusat  = getDefaultWarehouseID(-1000);
                $gudSpec_cabang = getDefaultWarehouseID($userProp->cabang_id);
                $gudSpec_POS    = getPOSWarehouseID($userProp->id, $userProp->cabang_id, $userProp->id);

                $sessionUniqUpdaters = array(
                    "MdlUser"                   => array(
                        'gudang_id'   => -1000,
                        'gudang_nama' => 'no warehouse',
                        'cabang_id'   => $userProp->cabang_id,
                        'cabang_nama' => $userProp->cabang_nama,
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlEmployee"               => array(
                        'gudang_id'   => $gudSpec_pusat['gudang_id'],
                        'gudang_nama' => $gudSpec_pusat['gudang_nama'],
                        'cabang_id'   => $userProp->cabang_id,
                        'cabang_nama' => $userProp->cabang_nama,
                        'div_nama'    => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlEmployee__shadow"       => array(
                        'gudang_id'   => $gudSpec_pusat['gudang_id'],
                        'gudang_nama' => $gudSpec_pusat['gudang_nama'],
                        'cabang_id'   => $userProp->cabang_id,
                        'cabang_nama' => $userProp->cabang_nama,
                        'div_nama'    => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlEmployeeCabang"         => array(
                        'gudang_id'   => $gudSpec_cabang['gudang_id'],
                        'gudang_nama' => $gudSpec_cabang['gudang_nama'],
                        'cabang_nama' => isset($cabangs[$userProp->cabang_id]) ? $cabangs[$userProp->cabang_id] : "branch " . $userProp->cabang_id,
                        'div_nama'    => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlEmployeeCabang__shadow" => array(
                        'gudang_id'   => $gudSpec_cabang['gudang_id'],
                        'gudang_nama' => $gudSpec_cabang['gudang_nama'],
                        'cabang_nama' => isset($cabangs[$userProp->cabang_id]) ? $cabangs[$userProp->cabang_id] : "branch " . $userProp->cabang_id,
                        'div_nama'    => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlPos"                    => array(
                        'gudang_id'   => $gudSpec_POS['gudang_id'],
                        'gudang_nama' => $gudSpec_POS['gudang_nama'],
                        'cabang_nama' => isset($cabangs[$userProp->cabang_id]) ? $cabangs[$userProp->cabang_id] : "branch " . $userProp->cabang_id,
                        'div_nama'    => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlEmployeeGudang"         => array(
                        'gudang_id'   => $userProp->gudang_id,
                        'gudang_nama' => isset($gudangs[$userProp->gudang_id]) ? $gudangs[$userProp->gudang_id] : "warehouse " . $userProp->gudang_id,
                        'cabang_nama' => isset($cabangs[$userProp->cabang_id]) ? $cabangs[$userProp->cabang_id] : "branch " . $userProp->cabang_id,
                        'div_nama'    => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                    "MdlEmployeeFreelanceCabang"=> array(
                        'gudang_id' => $gudSpec_cabang['gudang_id'],
                        'gudang_nama' => $gudSpec_cabang['gudang_nama'],
                        'cabang_nama' => isset($cabangs[$userProp->cabang_id]) ? $cabangs[$userProp->cabang_id] : "branch " . $userProp->cabang_id,
                        'div_nama' => $divs[$userProp->div_id],
                        'employee_type' => $userProp->employee_type,
                    ),
                );
                foreach ($sessionSwappers as $key) {
                    $loginProp[$key] = isset($userProp->$key) ? $userProp->$key : "";
                }
                foreach ($sessionUpdaters as $key => $val) {
                    $loginProp[$key] = $val;
                }
                if (isset($sessionUniqUpdaters[$mdlName]) && sizeof($sessionUniqUpdaters[$mdlName]) > 0) {
                    foreach ($sessionUniqUpdaters[$mdlName] as $key => $val) {
                        $loginProp[$key] = $val;
                    }
                }
                foreach ($companyProfil as $keys => $vals) {
                    $loginProp[$keys] = $vals;
                }
                foreach ($masterPPN as $keyPpn => $value_ppn) {
                    $loginProp[$keyPpn] = $value_ppn;
                }
                //==force membership
                if (!is_array($loginProp['membership'])) {
                    $loginProp['membership'] = array();
                }
                //tambahan jenis usaha pkp/nonpkp
                $this->load->model("Mdls/MdlCompany");
                $c = new MdlCompany();
                $c->addFilter("toko_id='$toko_id'");
                $company = $c->lookUpAll()->result();
                if(sizeof($company)>0){
                    $loginProp['jenis_usaha']= $company[0]->jenis_usaha;
                    $loginProp['profil_usaha'] = array(
                        "id"=>$company[0]->id,
                        "jenis_usaha"=>$company[0]->jenis_usaha,
                        "alamat"=>$company[0]->alamat_1,
                        "telp"=>$company[0]->tlp,
                        "kelurahan"=>$company[0]->kelurahan,
                        "kecamatan"=>$company[0]->kecamatan,
                        "kabupatem"=>$company[0]->kabupaten,
                        "provinsi"=>$company[0]->propinsi,
                        "kode_pos"=>$company[0]->kode_pos,
                        "lat"=>$company[0]->lat,
                        "lng"=>$company[0]->lng,
                    );
                }
                return $loginProp;
            }
        }
    }

    public function save($dReturn=array())
    {

        $doSave = $dReturn;
        $timeStart = date('Y-m-d H:i:s');

        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $this->load->model("MdlTransaksi");

        $cCode = $this->cCode;
        $configUi = $this->configUi;
        $configCore = $this->configCore;
        $configLayout = $this->configLayout;
        $configValues = $this->configValues;

        $tokoID = $doSave['main']['tokoID'];
        $tokoNama = $doSave['main']['tokoNama'];

        $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][1]["target"]) ? $this->configUi[$this->jenisTr]["steps"][1]["target"] : NULL;
        $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
        $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][1]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][1]["runCoreAkunting"] : false;
        $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();
        $corePreProcParam = isset($this->config->item('heTransaksi_core')[$this->modul]['requiredParam'][$this->jenisTr]['preProcessor']) ? $this->config->item('heTransaksi_core')[$this->modul]['requiredParam'][$this->jenisTr]['preProcessor'] : false;
        $coreRequiredParam = isset($this->config->item('heTransaksi_core')[$this->modul]['requiredParam']) ? $this->config->item('heTransaksi_core')[$this->modul]['requiredParam'] : array();
        $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][1]["target"]) ? $this->configUi[$this->jenisTr]["steps"][1]["target"] : NULL;
        $relOptionConfigs = isset($this->configUi[$this->jenisTr]['relativeOptions']) ? $this->configUi[$this->jenisTr]['relativeOptions'] : array();

        $relOptionConfigs = isset($configUi[$this->jenisTr]['relativeOptions']) ? $configUi[$this->jenisTr]['relativeOptions'] : array();
        $validationTableInMaster = isset($configUi[$this->jenisTr]['validationTableInMaster']) ? $configUi[$this->jenisTr]['validationTableInMaster'] : false;
        $inputLabels = array();
        $inputAuthConfigs = array();

        $rawPrevURL = isset($_GET['rawPrev']) ? $_GET['rawPrev'] : "";
        $prevUrl = blobDecode($rawPrevURL);

        /* ------------------------------
         * TRANSAKSIONAL TERJADI DI DALAM SINI
         * $dieForDebug = false; --------> kondisi normal transaksi bisa lanjot
         * untuk mematikan transksi di jadikan true
         * ------------------------*/

        $dieForDebug = false;
//        $dieForDebug = true;

        if (isset($doSave)) {

            $this->load->library("Transaksional");
            $lt = New Transaksional();

            //-------
            $sessionData[$this->cCode] = $doSave;

            cekHijau($this->cCode);
            cekHijau($this->modul);
            cekHijau($this->jenisTr);
            //-------
            $lt->setCCode($this->cCode);
            $lt->setModul($this->modul);
            $lt->setJenisTr($this->jenisTr);
            $lt->setCCodeData($sessionData);
            $lt->setStepNum(1);
            $lt->setStepNumCurrent(1);
            $lt->setTransaksiNumber(0);
            $lt->setConfigUiModul($this->configUi);
            $lt->setConfigLayoutModul($this->configLayout);
            $lt->setConfigCoreModul($this->configCore);
            $lt->setConfigValuesModul($this->configValues);
            $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));

            //-------
            //region build table rekening
            if ($runCoreAkunting == true) {
                $lt->buildTableRekeningNS();
            }
            //endregion

            $this->db->trans_start();

            // menjalankan save
            $libResult = $lt->save();
            $tmpNomorNota = $libResult["tmpNomerNota"];
            $tmpTransaksiID = $libResult["transaksiId"];

            //ini untuk mekanisme setelah customer bayar,
            //jika customer masih memiliki sisa tagihan,
            //maka buat kan transaksi tagihan baru untuk di apk
            //senilai sisa tagihan, dan mencantumkan history pembayaran yang lalu
            $arrProduk = $libResult['sessionData']['items'];
            $response = array(
                "status"            => 999,
                "toko_id"           => $libResult['sessionData']['main']['tokoID'],
                "validGrandTotal"   => $libResult['sessionData']['main']['piutang_dagang'],
                "nomor_referensi"   => $libResult['sessionData']['main']['nomer'],
                "referensi_id"      => $tmpTransaksiID,
                "oleh_id"           => $libResult['sessionData']['main']['olehID'],
                "oleh_nama"         => $libResult['sessionData']['main']['olehName'],
                "produk_blob"       => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
                "jenisTr"           => $this->jenisTr,
            );

            $matiDulu = 0;
            if($matiDulu){
                if(!empty($this->session->login)){
                    cekMerah("BROWSER MEMILIKI SESSION, HARAP MEMATIKAN SESSION LOGIN (LOGOUT) PADA BROWSER");
                    mati_disini("LINE: " . __LINE__ . " under maintenance, tunggu beberapa saat lagi yaa ..");
                }
                else{
                    $callBack = array(
                        "status" => 0,
                        "reason" => "LINE: " . __LINE__ . " under maintenance, tunggu beberapa saat lagi yaa ..",
                        "data" => $libResult,
                        "response" => $response,
                    );
                    echo json_encode($callBack);
                }
            }
            else{
                if(!empty($this->session->login)){
                    $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");
                }
                else{
                    if($this->db->trans_complete()){
//                    if(1){

//                        $arrProduk = $libResult['sessionData']['items'];
//                        $response = array(
//                            "status"            => 999,
//                            "toko_id"           => $libResult['sessionData']['main']['tokoID'],
//                            "validGrandTotal"   => $libResult['sessionData']['main']['piutang_dagang'],
//                            "nomor_referensi"   => $libResult['sessionData']['main']['nomer'],
//                            "referensi_id"      => $tmpTransaksiID,
//                            "oleh_id"           => $libResult['sessionData']['main']['olehID'],
//                            "oleh_nama"         => $libResult['sessionData']['main']['olehName'],
//                            "datetime"          => date("Y-m-d H:i:s"),
//                            "customer_id"       => $libResult['sessionData']['main']['customerDetails'],
//                            "customer_nama"     => $libResult['sessionData']['main']['customerDetails__nama'],
//                            "customer_alamat"   => $libResult['sessionData']["main"]['customerDetails__alamat_1'],
//                            "customer_telp"     => $libResult['sessionData']['customerDetails__tlp_1'],
//                            "produk_blob"       => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
//                        );

                        //$sendToApk = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/writeDataCollector", $response);

                        $callBack = array(
                            "status" => 1,
                            "data" => $libResult,
                            "doSave" => $doSave,
                        );
                        echo json_encode($callBack);
                    }
                    else{
                        $callBack = array(
                            "status" => 0,
                            "reason" => "Gagal saat berusaha  commit transaction!",
                        );
                        echo json_encode($callBack);
                    }
                }
            }
        }
        else {
            die("the gate index you want to debug has not been formed yet!");
        }

    }

    public function heFetchElement_he_element($jenisTr, $elName, $mdlName, $key, $configUiJenis, $dResult=array())
    {

        $result = $dResult;

        $ci =& get_instance();
        $ci->load->helper("he_element");
        $cCode = cCodeBuilderMisc($jenisTr);

        $elementConfigs = isset($configUiJenis['receiptElements']) ? $configUiJenis['receiptElements'] : array();
        $relElementConfigs = isset($configUiJenis['relativeElements']) ? $configUiJenis['relativeElements'] : array();
        $relOptionConfigs = isset($configUiJenis['relativeOptions']) ? $configUiJenis['relativeOptions'] : array();
        $configRecomData = isset($configUiJenis['pairRecomDataElement']) ? $configUiJenis['pairRecomDataElement'] : array();
        $pairedRelative = array();

        if (sizeof($relElementConfigs) > 0) {
            foreach ($relElementConfigs as $eSrc => $esSpec) {
                foreach ($esSpec as $esName => $psubSpec) {
                    if (sizeof($psubSpec) > 0) {
                        foreach ($psubSpec as $rcID => $subSpec) {
                            $elementConfigs[$rcID] = $subSpec;
                        }
                    }
                }
            }
            //cekHere(":: $elName");
            if (array_key_exists($elName, $relElementConfigs)) {
                //reset semua nilai anakan relatif yang mungkin saja terlanjur terbentuk
                if (isset($result['main_elements']) && sizeof($result['main_elements']) > 0) {
                    foreach ($result['main_elements'] as $eeName => $jasghhagsghaj) {
                        if (strpos($eeName, $elName . "_") !== false) {
                            $result['main_elements'][$eeName] = array();
                        }
                        else {
                            //							cekkuning("$eeName tidak perlu direset");
                        }
                    }
                }
            }
            if (array_key_exists($elName, $relOptionConfigs)) {
                //reset semua inputan relatif yang mungkin saja terlanjur terbentuk
                foreach ($relOptionConfigs[$elName] as $trigVal => $options) {
                    foreach ($options as $iVarName => $jasghahgsghasha) {
                        if (isset($result['main_elements'][$elName]['key']) && $result['main_elements'][$elName]['key'] == $trigVal) {
//                            cekbiru("NO NEED to remove value: $iVarName");
                        }
                        else {
                            // hapus semua main_input dp/cia/diskon bila sudah diisi maka diisi ulang...
                            if (isset($result['main_inputs'])) {
                                foreach ($result['main_inputs'] as $k_input => $v_input) {
                                    $result['main_inputs'][$k_input] = 0;
                                    $result['main'][$k_input] = 0;
                                }
                            }
                        }
                    }
                }
            }
            else {
                //            cekhijau("$elName TIDAK terdaftar pada relInputs");
            }
        }

        $keySrc = $elementConfigs[$elName]['key'];
        $aFilter = isset($elementConfigs[$elName]['mdlFilter']) ? $elementConfigs[$elName]['mdlFilter'] : array();

        $prTemp = array();
        $paired = array();
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $subConfig) {
                if (isset($subConfig['pairedModel']) && sizeof($subConfig['pairedModel']) > 0) {
                    $ci->load->model("Coms/" . $subConfig['pairedModel']['mdlName']);
                    $pr = new $subConfig['pairedModel']['mdlName']();
                    if (sizeof($subConfig['pairedModel']['mdlFilter']) > 0) {
                        foreach ($subConfig['pairedModel']['mdlFilter'] as $prKey => $prVal) {
                            $prVal = makeValue($prVal, $result['main'], $result['main'], $static = 0);
                            $pr->addFilter("$prKey='$prVal'");
                        }
                    }
                    $pairedRek = $subConfig['pairedModel']['rekening'];
                    $pairedMethod = $subConfig['pairedModel']['mdlMethod'];
                    $prTemp = $pr->$pairedMethod($pairedRek);
                    if (sizeof($prTemp) > 0) {
                        $fieldID = $subConfig['pairedModel']['fieldID'];
                        $fieldLabel = $subConfig['pairedModel']['fieldLabel'];
                        foreach ($prTemp as $prSpec) {
                            $colName = $subConfig['pairedModel']['key'];
                            if ($prSpec->$colName == $key) {
                                $paired[$fieldLabel] = $prSpec->$fieldID;
                            }
                        }
                    }
                }
            }
        }
        else {
            //        cekUngu("TIDAK ada elementConfig");
        }

        $ci->load->model("Mdls/" . $mdlName);
        $oo = new $mdlName();

        if (sizeof($aFilter) > 0) {
            $oo = makeFilter($aFilter, $result['main'], $oo);
        }
        else {
            //        cekHitam(":: tidak ada filterya ::");
        }

        $oo->init();
        $oo->setFilters(array());
        if ($oo->getTableName() == "static") {
            $oo->addFilter("$keySrc='$key'");
        }
        else {
            $oo->addFilter($oo->getTableName() . "." . "$keySrc='$key'");
        }

        $tmp = $oo->lookupAll()->result();

        $contents = array();
        $labelValue = "";
        if (sizeof($tmp) > 0) {
            foreach ($tmp as $row) {
                if (sizeof($paired) > 0) {
                    foreach ($paired as $prKey => $prVal) {
                        $row->$prKey = $prVal;
                    }
                }
                if (sizeof($pairedRelative) > 0) {
                    foreach ($pairedRelative as $prKeyRel => $prValRel) {
                        $row->$prKeyRel = $prValRel;
                    }
                }
                if (isset($elementConfigs[$elName]['usedFields']) && sizeof($elementConfigs[$elName]['usedFields']) > 0) {
                    if ($row->$keySrc == $key) {
                        foreach ($elementConfigs[$elName]['usedFields'] as $src => $label) {
                            $contents[$src] = isset($row->$src) ? $row->$src : "";
                        }
                        if (isset($elementConfigs[$elName]['labelSrc'])) {
                            $ex = explode("/", $elementConfigs[$elName]['labelSrc']);
                            if (sizeof($ex) > 1) {
                                $labelValue = "";
                                foreach ($ex as $col) {
                                    $labelValue .= $row->$col . " / ";
                                }
                                $labelValue = rtrim($labelValue, " / ");
                            }
                            else {
                                $kolomName = $elementConfigs[$elName]['labelSrc'];
                                $labelValue = $row->$kolomName;
                            }
                        }
                    }
                }
            }
        }
        else {

        }

        //  method diskon....
        if (isset($elementConfigs[$elName]['targetMethod']) && sizeof($elementConfigs[$elName]['targetMethod']) > 0) {
            foreach ($elementConfigs[$elName]['targetMethod'] as $tKey => $tVal) {
                if ($key == $tKey) {
                    $model = $tVal;
                    $ci->load->model("ReComs/" . $model);
                    $tt = New $model();
                    $tt->pair();
                    $tt->exec();
                }
            }
        }

        //kalkulasi relemet ke main jika ada perhitungan logic
        if (isset($elementConfigs[$elName]['pairMethod']) && sizeof($elementConfigs[$elName]['pairMethod']) > 0) {
            $model = $elementConfigs[$elName]['pairMethod']["recom"];
            $ci->load->model("ReComs/" . $model);
            $gateVal = $elementConfigs[$elName]['pairMethod']["calculate"];
            $tc = new $model();
            $tc->pair($gateVal, $key);
            $tc->exec();
        }
        if (isset($relElementConfigs[$elName]) && $elementConfigs[$elName] > 0) {
            if (isset($relElementConfigs[$elName][$key])) {
                foreach ($relElementConfigs[$elName][$key] as $tKey => $tVal) {
                    if (isset($tVal['targetMethod2'])) {
                        foreach ($tVal['targetMethod2'] as $sKey => $sVal) {
                            if ($key == $sKey) {
                                $model = $sVal;
                                $ci->load->model("ReComs/" . $model);
                                $tt = New $model();
                                $tt->pair();
                                $tt->exec();
                            }
                        }
                    }
                }
            }
        }
        if (!isset($result['main_elements'])) {
            $result['main_elements'] = array();
        }

        //==daftarkan ke gerbang yang sesuai
        if (sizeof($tmp) > 0) {
            $result['main_elements'][$elName] = array(
                "elementType" => $elementConfigs[$elName]['elementType'],
                "name" => $elName,
                "label" => $elementConfigs[$elName]['label'],
                "key" => $key,
                "labelSrc" => isset($elementConfigs[$elName]['labelSrc']) ? $elementConfigs[$elName]['labelSrc'] : "--",
                "labelValue" => $labelValue,
                "mdl_name" => $mdlName,
                "contents" => base64_encode(serialize($contents)),
                "contents_intext" => print_r($contents, true),
            );
            //==masukkan ke gerbang utama
            $result["main"][$elName] = $key;
            $result["main"][$elName . "__label"] = $labelValue;
            if (sizeof($contents)) {
                foreach ($contents as $key => $val) {
                    $result["main"][$elName . "__" . $key] = $val;
                }
            }
        }
        else {
            $result['main_elements'][$elName] = array();
            $result["main"][$elName] = array();
        }

        $this->setReceiptElementTmp($result);
    }

    public function heRecordElement_he_element($jenisTr, $elName, $val, $configUiJenis, $dResult=array())
    {

        $result = $dResult;

        $ci =& get_instance();
        $ci->load->helper("he_element");
        $cCode = cCodeBuilderMisc($jenisTr);
        $elementConfigs = isset($configUiJenis['receiptElements']) ? $configUiJenis['receiptElements'] : array();
        $relElementConfigs = isset($configUiJenis['relativeElements']) ? $configUiJenis['relativeElements'] : array();
        $relOptionConfigs = isset($configUiJenis['relativeOptions']) ? $configUiJenis['relativeOptions'] : array();

        if (sizeof($relElementConfigs) > 0) {
            foreach ($relElementConfigs as $eSrc => $esSpec) {
                foreach ($esSpec as $esName => $psubSpec) {
                    if (sizeof($psubSpec) > 0) {
                        foreach ($psubSpec as $rcID => $subSpec) {
                            $elementConfigs[$rcID] = $subSpec;
                        }
                    }
                }
            }
            if (array_key_exists($elName, $relElementConfigs)) {
                //reset semua nilai anakan relatif yang mungkin saja terlanjur terbentuk
                if (isset($result['main_elements']) && sizeof($result['main_elements']) > 0) {
                    foreach ($result['main_elements'] as $eeName => $jasghhagsghaj) {
                        if (strpos($eeName, $elName . "_") !== false) {
                            $result['main_elements'][$eeName] = array();
                        }
                        else {

                        }
                    }
                }
            }
            if (array_key_exists($elName, $relOptionConfigs)) {
                //reset semua inputan relatif yang mungkin saja terlanjur terbentuk
                foreach ($relOptionConfigs[$elName] as $trigVal => $options) {
                    foreach ($options as $iVarName => $jasghahgsghasha) {
                        if (isset($result['main_elements'][$elName]['value']) && $result['main_elements'][$elName]['value'] == $trigVal) {

                        }
                        else {
                            if (isset($result['main_inputs'][$iVarName])) {
                                $result['main_inputs'][$iVarName] = array();
                            }
                        }
                    }
                }
            }
            else {

            }
        }

        if (!isset($result['main_elements'])) {
            $result['main_elements'] = array();
        }
        $result['main_elements'][$elName] = array(
            "elementType" => $elementConfigs[$elName]['elementType'],
            "name" => $elName,
            "label" => $elementConfigs[$elName]['label'],
            "labelSrc" => isset($elementConfigs[$elName]['labelSrc']) ? $elementConfigs[$elName]['labelSrc'] : "--",
            "mdl_name" => "",
            "value" => $val,
        );

        //==masukkan ke gerbang utama
        $result["main"][$elName] = $val;
        if (isset($result['items']) && sizeof($result['items']) > 0) {
            foreach ($result['items'] as $iID => $iSpec) {
                if (isset($result['items'][$iID][$elName])) {
                    $result['items'][$iID][$elName] = null;
                    $result['items'][$iID][$elName] = array();
                }
            }
        }

        $this->setReceiptElementTmp($result);

    }


}