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

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

        /* ----------------------------------------------------------------------------------
          * loader cunstruk yg wajib ada
          * variabel-variabel bisa langsung dipangil, apa saja yang ada bisa dilihat didalamnya
          * ----------------------------------------------------------------------------------*/
        // require_once "_construct_file.php";
        $this->load->config("heApi");
        $this->api = $this->config->item("heApi");
        $this->apiApk = $this->api["apk"];

    }

    public function index()
    {
        // arrPrint($_SESSION);
        $cCode = $this->cCode;
        // cekKuning($cCode);
        if (isset($_SESSION[$cCode])) {
            // cekKuning("shopping-cart (creator)");
            //            arrprint($_SESSION[$cCode]);
        }
        else {
            die("the gate index you want to debug has not been formed yet!");
        }
    }

    public function validate()
    {

        $previewCtr = isset($this->configUi[$this->jenisTr]["previewCtr"]) ? $this->configUi[$this->jenisTr]["previewCtr"] : matiHere('controller preview belum diset');
        $createReturnOTP = isset($this->configUi[$this->jenisTr]["returnOTP"]) ? $this->configUi[$this->jenisTr]["returnOTP"] : "false";
        $previewValidate = isset($this->configUi[$this->jenisTr]["previewValidate"]) ? $this->configUi[$this->jenisTr]["previewValidate"] : "true";

        $modalCloseable = "true";

        $cCode = $this->cCode;
        $rawPrevURL = isset($_GET['rawPrev']) ? $_GET['rawPrev'] : "";

        if (isset($_SESSION[$cCode]['mode']['edit']) && sizeof($_SESSION[$cCode]['mode']['edit']) > 0) {
            $prevAction = $previewCtr . "/editPreview";
            $main_id = "/" . $_SESSION[$cCode]['mode']['edit'];
        }
        else {
            if (isset($_SESSION[$cCode]['mode']['cancel']) && sizeof($_SESSION[$cCode]['mode']['cancel']) > 0) {
                $prevAction = "Transaksi/preCancelPackingPreview";
                $main_id = "/" . $_SESSION[$cCode]['mode']['cancel'];
            }
            else {
                $prevAction = $previewCtr . "/preview";
                $main_id = "";
            }
        }

        $apiRequestReturnOTP = "";

        if($createReturnOTP=="true"){
            $modalCloseable = "false";
//            if(!isset($_SESSION[$cCode]['main']['view_oto_return'])){
                $_SESSION[$cCode]['main']['view_oto_return'] = 1;
                $nomer_main = $_SESSION[$cCode]['main']['referenceNomer'];
                $apiRequestReturnOTP .= "
                    top.$.ajax({
                        url: '". base_url() . $this->modul ."/_shoppingCart/reqReturnOTP/".$this->jenisTr."',
                        method: 'post',
                        data: {
                            'shoppingcart_order_id': '$nomer_main',
                        },
                        success: function(a){
                            jsonData = JSON.parse(a);
                            if(jsonData.status){

                            }
                        }
                    })
                ";

//            }
//            unset($_SESSION[$cCode]['main']['view_oto_return']);
        }
        else{

            if( isset($_SESSION[$cCode]['main']['view_oto_return']) ){
                unset($_SESSION[$cCode]['main']['view_oto_return']);
            }
        }

//        matiHere($createReturnOTP." | LINE: " . __LINE__ . "<br>view_oto_return: " . $_SESSION[$cCode]['main']['view_oto_return'] . "<br>cCode: $cCode");

        //-----------------
        $this->load->library("Validator");
        $vd = new Validator();
        $vd->setCCode($this->cCode);
        $vd->setSessionData($_SESSION[$cCode]);
        $vd->setConfigUiJenis($this->configUiJenis);
        $vd->validateSessionData();
        //-----------------

        //check items digital,
//        $unpaid=0;
//        $pending=0;
//        if(isset($_SESSION[$cCode]['items'])){
//            $exeDigiTrx=array();
//            $exeDigiPending=array();
//            foreach($_SESSION[$cCode]['items'] as $k => $digi){
//                if( isset($digi['tipe_produk']) && $digi['tipe_produk']=="digital" ){
//                    if(!isset($digi['digipay'])){
//                        $unpaid += 1;
//                        $exeDigiTrx[] = $digi;
//                    }
//                    else{
//                        if(!isset($digi['digipay']['paid']) && $digi['digipay']['status'] == 0){
//                            $pending += 1;
//                            $exeDigiPending[] = $digi;
//                        }
//                    }
//                }
//            }
//        }

        $actionTarget = "";

//        if($unpaid>0 || $pending>0){
//
//            if( $pending>0 ){
//                $actionTarget .= "
//                top.swal.close();\n
//                top.BootstrapDialog.show({
//                    title: 'MEMPROSES PENDING TRANSAKSI DIGITAL',
//                    message: ".'top.$'."('<div></div>').html('---------'),
//                    draggable: false,
//                    animate: false,
//                    size: top.BootstrapDialog.SIZE_WIDE,
//                    type: top.BootstrapDialog.TYPE_DEFAULT,
//                    closable: false,
//                    onshow: function(dialogRef){
//                        console.log('onshow');
//                    },
//                    onshown: function(dialogRef){
//                        console.log('onshown');
//                    },
//                    onhide: function(dialogRef){
//                        console.log('onhide');
//                    },
//                    onhidden: function(dialogRef){
//                        console.log('onhidden');
//                    }
//                });";
//            }
//            else if($unpaid>0){
//                $proses = json_encode($exeDigiTrx[0]);
//                $targetID = strtotime(date('Y-m-d H:i:s'));
//                $actionTarget .= "
//                top.swal.close();\n
//                top.BootstrapDialog.show({
//                    title:'MEMPROSES TRANSAKSI DIGITAL',
//                    message: " . 'top.$' . "('<div id=digi_$targetID></div>').html('---------'),
//                    draggable:false,
//                    animate: false,
//                    size:top.BootstrapDialog.SIZE_WIDE,
//                    type:top.BootstrapDialog.TYPE_DEFAULT,
//                    closable: false,
//                    onshow: function(dialogRef){
//
//                    },
//                    onshown: function(dialogRef){
//                        top.exePayment.pay($proses,'',$targetID);
//                    },
//                    onhide: function(dialogRef){
//                        console.log('onhide');
//                    },
//                    onhidden: function(dialogRef){
//                        console.log('onhidden');
//                    }
//                });";
//            }
//            else{
//
//                matiHere();
//            }
//
//
//        }
//        else{
            $actionTarget .= "
                top.BootstrapDialog.show({
                    title:'preview',
                    message: " . 'top.$' . "('<div></div>').load('" . base_url() . $this->modul . "/" . $prevAction . "/" . $this->jenisTr . "?rawPrev=$rawPrevURL'),
                    draggable:false,
                    animate: false,
                    size:top.BootstrapDialog.SIZE_WIDE,
                    type:top.BootstrapDialog.TYPE_DEFAULT,
                    closable: $modalCloseable,
                    onshow: function(dialogRef){

                    },
                    onshown: function(dialogRef){

                    },
                    onhide: function(dialogRef){

                    },
                    onhidden: function(dialogRef){

                    }
                });";
//        }



        echo "<script>

        $apiRequestReturnOTP

        top.close_holdon();
        $actionTarget
        </script>";

    }

    // public function validate2()
    // {
    //     $cCode = $this->cCode;
    //
    //     $validationRules = isset($this->configUi[$this->jenisTr]['validationRules']) ? $this->configUi[$this->jenisTr]['validationRules'] : array();
    //
    //
    //     $msgWarning = array();
    //     if (isset($validationRules)) {
    //         foreach ($validationRules as $gateName => $gSpec) {
    //             if (isset($_SESSION[$cCode][$gateName])) {
    //                 foreach ($_SESSION[$cCode][$gateName] as $eKey => $eSpec) {
    //                     if (isset($gSpec['target']) && isset($eSpec[$gSpec['target']]) && $eSpec[$gSpec['target']] > 0) {
    //                         if ($eSpec[$gSpec['source']] > $eSpec[$gSpec['target']]) {
    //
    //                             $msg = $gSpec['target'] . " " . $eSpec['nama'] . " tidak cukup.";
    //                             $msgWarning[$eSpec['id']] = array(
    //                                 "id" => "trItems_" . $eSpec['id'],
    //                                 "label" => $msg,
    //                             );
    //                         }
    //                     }
    //                     else {
    //                         $msg = $gSpec['target'] . " " . $eSpec['nama'] . " tidak cukup.";
    //                         $msgWarning[$eSpec['id']] = array(
    //                             "id" => "trItems_" . $eSpec['id'],
    //                             "label" => $msg,
    //                         );
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //
    //     return $msgWarning;
    // }

    public function viewUndoneItems_modul()
    {
        // cekOrange($this->uri->segment_array());
        // cekBiru($this->jenisTr);
        // matiHere();
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $historyFields = $this->configUi[$jenisTr]['shortHistoryFields'];
        $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
        $dueDateAllow = isset($this->configUi[$jenisTr]['updateDueDate']) ? $this->configUi[$jenisTr]['updateDueDate'] : array();
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }
        $glanceHistoryFields = isset($this->configUi[$jenisTr]['glanceHistoryFields']) ? $this->configUi[$jenisTr]['glanceHistoryFields'] : array("nomer" => "receipt no");
        $glanceHistoryFields2 = array("nomer" => "receipt no"); //init;
        $selectorProcessor = base_url() . $this->configUi[$jenisTr]['selectorProcessor'] . "/$jenisTr";

        //region lookup on-going transactions
        $arrayOnprogress = array();
        $progressFields = $historyFields;

        $progressFields['jenis_label'] = "activity";
        //        $progressFields['nomer'] = "receipt number";
        $progressFields['oleh_nama'] = "started by";
        $progressFields['state'] = "status";
        $progressFields['action'] = "action";

        $steps = $this->configUi[$jenisTr]['steps'];

        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $registryFields = $tr->getRegistryFields();
        if (sizeof($steps) > 1) {

            // cekMerah($this->accessList);
            $stepCodes = array();
            $jmlStep = count($steps);
            if (isset($this->accessList[$jenisTr]) && sizeof($this->accessList) > 0) {
                $arrFilters = array();
                $indsteps = "(";
                foreach ($this->accessList[$jenisTr] as $stepNumber => $stepSpec) {
                    if ($stepNumber <= $jmlStep) {
                        foreach ($stepSpec as $targetCode => $filters) {
                            $indsteps .= "'$targetCode',";
                            $stepCodes[] = $targetCode;
                            if ($filters['allowFollowUp'] == "true") {
                                $arrFilters["allowFollowUp"][] = $targetCode;
                            }

                        }
                    }
                }
                $indsteps = rtrim($indsteps, ",");
                $indsteps .= ")";
                if (sizeof($arrFilters) > 0) {
                    $tr->addFilter("next_step_code in $indsteps");
                }
                else {
                    $tr->addFilter("transaksi.oleh_id='" . $this->session->login['id'] . "'");
                }
            }
            else {
                foreach ($steps as $stepNumber => $stepSpec) {
                    if ($stepNumber < $jmlStep) {
                        $stepCodes[] = $stepSpec['target'];
                    }

                }
            }

        }


        // $tr->addFilter("div_id='" . (isset($this->session->login['div_id']) ? $this->session->login['div_id'] : '') . "'");
        $tr->addFilter("jenis_top='" . $steps[1]['target'] . "'");
        $tr->addFilter("next_substep_code<>''");
        $tr->addFilter("sub_step_number>0");
        if (isset($this->accessList[$jenisTr]) && sizeof($this->accessList) > 0) {
        }
        else {
            if (sizeof($this->session->login['membership']) > 0) {
                $this->db->group_start();
                $mCtr = 0;
                foreach ($this->session->login['membership'] as $gID) {
                    if ($mCtr == 0) {
                        $this->db->where(array("next_subgroup_code" => $gID));

                    }
                    else {
                        $this->db->or_where(array("next_subgroup_code" => $gID));
                    }
                    $mCtr++;
                }
                $this->db->group_end();
            }
        }
        $tmpHist = $tr->lookupUndoneEntries_joined(replaceSession())->result();
        // cekLime($this->db->last_query());
        // cekMerah($tmpHist);
        //region due date
        $tr->setFilters(array());
        $listedDue = $tr->lookupAllDueDate()->result();
        $arrDue = array();
        $overDue = array();
        foreach ($listedDue as $dueData) {

            $due_date = strtotime($dueData->due_date);
            $date_now = strtotime(date("Y-m-d"));
            if ($due_date < $date_now) {
                $arrDue[$dueData->transaksi_id] = array(
                    "due_date" => $dueData->due_date,
                    "aging"    => umurDay($dueData->due_date),
                );
            }

        }
        //arrPrint($arrDue);
        //arrPrint($tmpHist);
        //endregion
        $arrOver_due = array();


        if (sizeof($tmpHist) > 0) {
            $arrTransID = array();
            $arrTransTopID = array();
            $arrIdsHist = array();
            $arrTransHist = array();
            $tmpReg_result = array();
            foreach ($tmpHist as $row) {
                $arrTransID[] = $row->transaksi_id;
                $arrTransTopID[] = $row->id_top;

                if ($row->ids_his != "") {
                    $hist = blobDecode($row->ids_his);
                    foreach ($hist as $hisSpec) {
                        $arrIdsHist[$row->id][$hisSpec['step']] = array(
                            "step"  => $hisSpec['step'],
                            "trID"  => $hisSpec['trID'],
                            "nomer" => $hisSpec['nomer'],
                        );
                        $arrTransHist[] = $hisSpec['trID'];
                    }
                }

                $filterField = array("main");
                if (sizeof($registryFields) > 0) {
                    foreach ($registryFields as $param) {
                        if (in_array($param, $filterField)) {
                            $tmpReg_result[$row->transaksi_id][$param] = blobDecode($row->$param);
                        }
                    }
                }
            }

            //            $trReg = new MdlTransaksi();
            //            $trReg->setFilters(array());
            //            $trReg->addFilter("param='main'");
            //            $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
            //            $tmpReg = $trReg->lookupRegistries()->result();
            //            if (sizeof($tmpReg) > 0) {
            //                foreach ($tmpReg as $regRow) {
            //                    $param = $regRow->param;
            //                    $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
            //                }
            //            }

            if (sizeof($arrIdsHist) > 0) {
                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("id in ('" . implode("','", $arrTransHist) . "')");
                $tmpTransHist = $tr->lookupAll()->result();


                if (sizeof($tmpTransHist) > 0) {
                    foreach ($tmpTransHist as $histSpec) {
                        $tmpTransHist_result[$histSpec->id] = array(
                            "oleh_id"   => $histSpec->oleh_id,
                            "oleh_nama" => $histSpec->oleh_nama,
                        );
                    }
                }

                foreach ($arrIdsHist as $trID => $histSpec) {
                    foreach ($histSpec as $step => $detailSpec) {
                        if (array_key_exists($detailSpec['trID'], $tmpTransHist_result)) {
                            $detailSpec['main'] = $tmpTransHist_result[$detailSpec['trID']];
                        }
                        $arrTransMainHist[$trID][$step] = $detailSpec;
                    }
                }
            }
            $configUiJenis = $this->configUi[$jenisTr];
            $numb = 0;
            foreach ($tmpHist as $row) {
                $step_current = $row->step_current;

                if (sizeof($pairRegistries) > 0) {
                    if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->transaksi_id]))) {
                        foreach ($tmpReg_result[$row->transaksi_id] as $param => $eReg) {
                            foreach ($eReg as $k => $v) {
                                if (!isset($row->$k)) {
                                    $row->$k = $v;
                                }
                            }
                        }
                    }
                }

                $tmp = array();
                $numb++;

                foreach ($historyFields as $fName => $fLabel) {

                    if (isset($row->$fName)) {
                        if (is_numeric($row->$fName)) {
                            if (!isset($sumFooter[$fName])) {
                                $sumFooter[$fName] = 0;
                            }
                            $sumFooter[$fName] += $row->$fName;
                        }
                    }

                    if (is_array($fLabel)) {
                        $hisStep = $fLabel['step'];
                        $hisKey = $fLabel['key'];
                        //                                $tNomer = $id_hist[$hisStep][$hisKey];

                        if (isset($row->ids_his)) {
                            $returnVal = showHistoriGlobalNumbers($row->ids_his, $hisStep, true);
                            if ($returnVal == "") {
                                $tmp[$fName] = "-";
                            }
                            else {
                                $tmp[$fName] = $returnVal;
                            }
                        }
                        else {
                            $tmp[$fName] = "-";
                        }
                    }
                    else {
                        $tmp[$fName] = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : formatField_he_format($fName, 0);
                    }

                    if ($fName == "no") {
                        $tmp[$fName] = formatField_he_format($fName, $numb);
                    }
                }

                if ($row->sub_step_number > 0) {
                    // $tmp['state'] = "<span style='color:" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateColor'] . "'>" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateLabel'] . "</span>";
                    // $tmp['state'] .= "<br>" . createStateSign($row->sub_step_number, $row->step_avail, $jenisTr);

                    $tmp['state'] = createStateHorizontal($row->sub_step_number, $row->step_avail, $jenisTr);
                }
                else {
                    $tmp['state'] = "<span style='color:#777777'>canceled</span>";
                }

                // matiHere();
                $tmp['action'] = "";
                $nextStepNum = ($row->next_substep_num);
                $currentStepNum = ($row->sub_step_number);
                $nextStepCode = ($row->next_step_code);
                $allowJoin = isset($this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin']) && $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] == true ? $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] : false;

                /*button followUp*/
                $allowFollowup = false;
                if ($row->sub_step_number > 0) {
                    //                    if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum)) {
                    //                        //                        if (in_array($this->configUi[$jenisTr]['steps'][$currentStepNum]['userGroup'], $this->session->login['membership'])) {
                    //                        $allowFollowup = true;
                    //                        $actionLabel = "review " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                    //                    }
                    $allowFollowup = true;
                    $actionLabel = "review " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                }

                if (isset($this->configUi[$jenisTr]['steps'][$nextStepNum])) {
                    if (isset($this->accessList[$jenisTr])) {
                        if (isset($this->accessList[$jenisTr][$nextStepNum][$nextStepCode]["allowFollowUp"])) {
                            $allowFollowup = $this->accessList[$jenisTr][$nextStepNum][$nextStepCode]["allowFollowUp"];
                            $actionLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['actionLabel'];
                        }


                    }
                    else {

                        if (placeCanFollowupTrans(my_memberships(), my_cabang_id(), my_gudang_id(), $this->jenisTr, $nextStepNum, "", $configUiJenis)) {
                            //                        if (in_array($this->configUi[$jenisTr]['steps'][$nextStepNum]['userGroup'], $this->session->login['membership'])) {
                            $allowFollowup = true;
                            $actionLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['actionLabel'];

                        }
                    }

                }

                if ($allowFollowup) {
                    $stepLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['label'];
                    $isCancelPacking = isset($this->configUi[$jenisTr]['steps'][$nextStepNum]['isCancelPacking']) ? $this->configUi[$jenisTr]['steps'][$nextStepNum]['isCancelPacking'] : false;
                    $allowCancel = isset($this->configUi[$jenisTr]['steps'][$nextStepNum]['allowCancel']) ? $this->configUi[$jenisTr]['steps'][$nextStepNum]['allowCancel'] : false;

                    $targetFollowupLink = $isCancelPacking == true ? "followupCancelPackingPrePreview" : "followupPrePreview";
                    //                    $followupLink = "top.$('#result').load('" . base_url() . "Transaksi/followupPrePreview/" . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
                    // $followupLink = "disableShopCart();top.$('#result').load('" . base_url() . $this->modul . "/Transaksi/$targetFollowupLink/" . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
                    $followupLink = "disableShopCart();top.$('#result').load('" . base_url() . $this->modul . "/FollowUp/$targetFollowupLink/" . $this->jenisTr . DIRECTORY_SEPARATOR . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
                    //                        $tmp['action'] = "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' href='JavaScript:void(0)' onClick =\"$followupLink\">" . $actionLabel . "</a>";
                    $tmp['action'] = "<div class='input-group'>";
                    $tmp['action'] .= "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' data-toggle='tooltip' href='JavaScript:void(0)' onClick =\"top.open_holdon();$followupLink\"><span class='glyphicon glyphicon-ok'></span> " . $actionLabel . "</a>";
                    if ($allowJoin) {
                        $tmp['action'] .= "<span class='input-group-addon'>";
                        $tmp['action'] .= "<a title='process many items at once' href='" . base_url() . "Transaksi/viewIncomplete/" . $this->jenisTr . "/$currentStepNum'><span class='fa fa-dedent'></span></a>";
                        $tmp['action'] .= "</span class='input-group-addon'>";
                    }
                }
                //                $arrayOnprogress[] = $tmp;
                //                if (isset($arrDue[$row->transaksi_id]) && $arrDue[$row->transaksi_id]['aging'] > 0) {
                //                    cekhere($row->transaksi_id);
                //                    $arrOver_due[] = $tmp;
                //                } else {
                $arrayOnprogress[] = $tmp;
                //                }
            }
        }


        //endregion

        //region lookup on-going from connected requests

        if (!isset($_SESSION['undoneQty'])) {
            $_SESSION['undoneQty'] = array();
        }
        if (!isset($_SESSION['undoneQty'][$this->jenisTr])) {
            $_SESSION['undoneQty'][$this->jenisTr] = 0;
        }
        $progress2Fields = array();
        $arrayOnprogress2 = array();
        $reqFormTarget = "";
        $needToClear = false;
        $allowMultiSelect = false;
        if (isset($this->configUi[$jenisTr]['requestCode'])) {
            $masterRefCode = $this->configUi[$jenisTr]['requestCode']['masterCode'];
            $stateRefCode = $this->configUi[$jenisTr]['requestCode']['stateCode'];
            $stateRefNum = $this->configUi[$jenisTr]['requestCode']['stepNumber'];
            $progress2Fields = isset($this->configUi[$masterRefCode]['shortHistoryFields']) ? $this->configUi[$masterRefCode]['shortHistoryFields'] : "";
            //            $glanceHistoryFields2 = isset($this->configUi[$masterRefCode]['glanceHistoryFields']) ? $this->configUi[$masterRefCode]['glanceHistoryFields'] + array("select" => "select") : array("nomer" => "receipt no");
            $glanceHistoryFields2 = isset($this->configUi[$masterRefCode]['glanceHistoryFields']) ? $this->configUi[$masterRefCode]['glanceHistoryFields'] : array("nomer" => "receipt no");
            $reqFormTarget = base_url() . get_class($this) . "/swapFrom/$jenisTr";


            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
            $tr->addFilter("transaksi.jenis_master='" . $masterRefCode . "'");
            $tr->addFilter("transaksi.jenis='" . $stateRefCode . "'");
            //            $tr->addFilter("transaksi.step_number='" . $stateRefNum . "'");
            $tr->addFilter("transaksi.step_current='" . $stateRefNum . "'");
            $tmpByReq = $tr->lookupRecentHistories()->result();

            $needToClear = false;
            if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                $needToClear = true;
            }
            $_SESSION['undoneQty'][$this->jenisTr] = sizeof($tmpByReq);

            if (sizeof($tmpByReq) > 0) {

                $allowMultiSelect = isset($this->configUi[$jenisTr]['requestCode']['allowMultiSelect']) ? $this->configUi[$jenisTr]['requestCode']['allowMultiSelect'] : false;

                $reqCtr = 0;
                foreach ($tmpByReq as $row) {
                    $reqCtr++;
                    $tmp = array();
                    $inputType = $allowMultiSelect == true ? "checkbox" : "radio";
                    //                    $clickEvent = "onclick=\"return false;\"";
                    $clickEvent = "";
                    if ($inputType == "radio" && !$needToClear) {
                        //                        $clickEvent="onclick=\"document.getElementById('btnConnect').innerHTML='Clear the list to process one of entries above';document.getElementById('btnConnect').disabled=true;document.getElementById('fAsNew').submit()\"";
                        $clickEvent = "onclick=\"document.getElementById('fAsNew').submit()\"";
                    }
                    $tmp['select'] = "<input type=$inputType name='trID[]' value='" . $row->id . "' id='select_" . $reqCtr . "' $clickEvent>";
                    foreach ($historyFields as $fName => $fLabel) {
                        //                        $tmp[$fName] = formatField_he_format($fName, $row->$fName);
                        $tmp[$fName] = isset($row->$fName) ? $row->$fName : "";
                    }


                    $arrayOnprogress2[] = $tmp;
                }
            }
            if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                $needToClear = true;
            }

        }


        //endregion

        $sumFooterResult = array();
        if (isset($sumFooter) && sizeof($sumFooter) > 0) {
            foreach ($sumFooter as $key => $val) {

                $sumFooterResult[$key] = formatField_he_format($key, $val);
            }
        }
        // cekOrange($progressFields);
        $data = array(
            "mode"                 => $this->uri->segment(3),
            "isMobile"             => $isMob,
            //            "arrayProgressLabels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progressFields : $glanceHistoryFields,
            //            "arrayProgress2Labels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progress2Fields : $glanceHistoryFields2,
            "arrayProgressLabels"  => $progressFields,
            "arrayProgress2Labels" => $glanceHistoryFields2,
            "arrayOnProgress"      => $arrayOnprogress,
            "arrayOnProgress2"     => $arrayOnprogress2,
            "needToClear"          => $needToClear,
            "reqFormTarget"        => $reqFormTarget,
            "allowMultiSelect"     => $allowMultiSelect,
            "overDue"              => $arrOver_due,
            "clearCartTarget"      => base_url() . "_shoppingCart/reset/" . $this->jenisTr,
            "sumFooter"            => $sumFooterResult,
        );

        $this->load->view("transaksi", $data);

    }

    public function viewUndoneItems()
    {
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        // arrPrintHijau(url_segment());
        /*--pembaca takein order dari apk ----*/
//        $this->load->library('curl');

//        $urlApi = $this->apiApk["order_request"] . my_toko_id();
        //        cekBiru("$urlApi");

//        $src_preOrderRequest = array();
//        $preOrderRequest = json_decode($this->curl->simple_get($urlApi));
        //        arrPrintKuning($preOrderRequest);
//        if (isset($preOrderRequest) && ($preOrderRequest->status)) {
//            $src_preOrderRequest = $preOrderRequest->data;
//        }


        //        arrPrint($src_preOrderRequest);

//        $kolom_conversi = array(
//            "id"           => "id",
//            "id_cust"      => "customers_id",
//            "nm_cust"      => "customers_nama",
//            "datetime"     => "dtime",
//            "nomor"        => "nomer",
//            "grand_total"  => "grand_total",
//            "apk_version"  => "apk_version",
//            "oleh_nama"    => "oleh_nama",
//            "diskon_total" => "disc",
//        );
        // $apkTmp[0] = array();
//        $apk_datas = array();
//        $apkTmp = array();
        //        if(!empty($src_preOrderRequest)){
//        foreach ($src_preOrderRequest as $item) {
//            foreach ($kolom_conversi as $apk_kolom => $web_kolom) {
//                // cekHere($apk_kolom);
//                $val_apk = $item->$apk_kolom;
//                $apk_datas[$web_kolom] = $apk_kolom == "id" ? $val_apk . "_apk" : $val_apk;
        //        }
//            // $apk_datas["id"] = "8";
//            $apkTmp[] = (object)$apk_datas;
//        }
        //        }
        //-------------------------------------
        // cekHere(sizeof($src_preOrderRequest));
        //         arrPrintWebs($apkTmp);

        $historyFields = $this->configUi[$jenisTr]['shortHistoryFields'];
        $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
        $dueDateAllow = isset($this->configUi[$jenisTr]['updateDueDate']) ? $this->configUi[$jenisTr]['updateDueDate'] : array();
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }
        $glanceHistoryFields = isset($this->configUi[$jenisTr]['glanceHistoryFields']) ? $this->configUi[$jenisTr]['glanceHistoryFields'] : array("nomer" => "receipt no");
        $glanceHistoryFields2 = array("nomer" => "receipt no"); //init;
        $selectorProcessor = base_url() . $this->configUi[$jenisTr]['selectorProcessor'] . "/$jenisTr";

        //region lookup on-going transactions
        $arrayOnprogress = array();
        $progressFields = $historyFields;

        $progressFields['jenis_label'] = "activity";
        $progressFields['oleh_nama'] = "started by";
        $progressFields['state'] = "status";
        $progressFields['action'] = "action";

        $steps = $this->configUi[$jenisTr]['steps'];

        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();

        if (sizeof($steps) > 1) {
            $stepCodes = array();
            $jmlStep = count($steps);
            if (isset($this->accessList[$jenisTr]) && sizeof($this->accessList) > 0) {
                $arrFilters = array();
                $indsteps = "(";
                foreach ($this->accessList[$jenisTr] as $stepNumber => $stepSpec) {
                    if ($stepNumber <= $jmlStep) {
                        foreach ($stepSpec as $targetCode => $filters) {
                            $indsteps .= "'$targetCode',";
                            $stepCodes[] = $targetCode;
                            if ($filters['allowFollowUp'] == "true") {
                                $arrFilters["allowFollowUp"][] = $targetCode;
                            }
                        }
                    }
                }
                $indsteps = rtrim($indsteps, ",");
                $indsteps .= ")";
                if (sizeof($arrFilters) > 0) {
                    $tr->addFilter("next_step_code in $indsteps");
                }
                else {
                    $tr->addFilter("transaksi.oleh_id='" . $this->session->login['id'] . "'");
                }
            }
            else {
                foreach ($steps as $stepNumber => $stepSpec) {
                    if ($stepNumber < $jmlStep) {
                        $stepCodes[] = $stepSpec['target'];
                    }
                }
            }
        }

        //        $tr->addFilter("div_id='" . $this->session->login['div_id'] . "'");
        $tr->addFilter("jenis_top='" . $steps[1]['target'] . "'");
        $tr->addFilter("next_substep_code<>''");
        $tr->addFilter("sub_step_number>0");
        if (isset($this->accessList[$jenisTr]) && sizeof($this->accessList) > 0) {
        }
        else {
            // arrPrintWebs($this->session->login['membership']);
            if (in_array("o_holding", ($this->session->login['membership']))) {

            }
            elseif (in_array("w_gudang", ($this->session->login['membership']))) {
                $this->db->where(array("gudang2_id" => $this->session->login['gudang_id']));
            }
            else {
                if (sizeof($this->session->login['membership']) > 0) {
                    $this->db->group_start();
                    $mCtr = 0;
                    foreach ($this->session->login['membership'] as $gID) {
                        if ($mCtr == 0) {
                            $this->db->where(array("next_subgroup_code" => $gID));
                        }
                        else {
                            $this->db->or_where(array("next_subgroup_code" => $gID));
                        }
                        $mCtr++;
                    }
                    $this->db->group_end();
                }
            }

            // matiHere();

        }

        $tmpHist = $tr->lookupUndoneEntries_joined(replaceSession())->result();
        //         cekHitam($this->db->last_query());
        //         matiHere();

        //region due date
        $tr->setFilters(array());
        $listedDue = $tr->lookupAllDueDate()->result();
        $arrDue = array();
        $overDue = array();
        foreach ($listedDue as $dueData) {
            $due_date = strtotime($dueData->due_date);
            $date_now = strtotime(date("Y-m-d"));
            if ($due_date < $date_now) {
                $arrDue[$dueData->transaksi_id] = array(
                    "due_date" => $dueData->due_date,
                    "aging"    => umurDay($dueData->due_date),
                );
            }
        }
        //endregion
        $arrOver_due = array();

        if (sizeof($tmpHist) > 0) {
            $arrTransID = array();
            $arrTransTopID = array();
            $arrIdsHist = array();
            $arrTransHist = array();
            foreach ($tmpHist as $row) {
                $arrTransID[] = $row->transaksi_id;
                $arrTransTopID[] = $row->id_top;
                if ($row->ids_his != "") {
                    $hist = blobDecode($row->ids_his);
                    foreach ($hist as $hisSpec) {
                        $arrIdsHist[$row->id][$hisSpec['step']] = array(
                            "step"  => $hisSpec['step'],
                            "trID"  => $hisSpec['trID'],
                            "nomer" => $hisSpec['nomer'],
                        );
                        $arrTransHist[] = $hisSpec['trID'];
                    }
                }
            }
            $tmpReg_result = array();
            $trReg = new MdlTransaksi();
            $trReg->setFilters(array());
            $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
            $tmpReg = $trReg->lookupDataRegistries()->result();
            //            showLast_query("biru");

            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $regRow) {
                    //                    arrPrintKuning($regRow);
                    $transID = $regRow->transaksi_id;
                    //                    $param = $regRow->param;
                    //                    $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
                    foreach ($regRow as $key => $val) {
                        if ($key != "transaksi_id") {
                            $tmpReg_result[$transID][$key] = blobDecode($val);
                        }
                    }
                }
            }
            if (sizeof($arrIdsHist) > 0) {
                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("id in ('" . implode("','", $arrTransHist) . "')");
                $tmpTransHist = $tr->lookupAll()->result();


                if (sizeof($tmpTransHist) > 0) {
                    foreach ($tmpTransHist as $histSpec) {
                        $tmpTransHist_result[$histSpec->id] = array(
                            "oleh_id"   => $histSpec->oleh_id,
                            "oleh_nama" => $histSpec->oleh_nama,
                        );
                    }
                }

                foreach ($arrIdsHist as $trID => $histSpec) {
                    foreach ($histSpec as $step => $detailSpec) {
                        if (array_key_exists($detailSpec['trID'], $tmpTransHist_result)) {
                            $detailSpec['main'] = $tmpTransHist_result[$detailSpec['trID']];
                        }
                        $arrTransMainHist[$trID][$step] = $detailSpec;
                    }
                }
            }
            $numb = 0;
            foreach ($tmpHist as $row) {
//                arrPrint($row);
                $step_current = $row->step_current;
                if (sizeof($pairRegistries) > 0) {
                    if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->transaksi_id]))) {
                        foreach ($tmpReg_result[$row->transaksi_id]["main"] as $k => $v) {
                            //                            foreach ($eReg as $k => $v) {
                            if (!isset($row->$k)) {
                                $row->$k = $v;
                            }
                            //                            }
                        }
                    }
                }

                $tmp = array();
                $numb++;

                foreach ($historyFields as $fName => $fLabel) {

                    if (isset($row->$fName)) {
                        if (is_numeric($row->$fName)) {
                            if (!isset($sumFooter[$fName])) {
                                $sumFooter[$fName] = 0;
                            }
                            $sumFooter[$fName] += $row->$fName;
                        }
                    }

                    if (is_array($fLabel)) {
                        $hisStep = $fLabel['step'];
                        $hisKey = $fLabel['key'];
                        //                                $tNomer = $id_hist[$hisStep][$hisKey];

                        if (isset($row->ids_his)) {
                            $returnVal = showHistoriGlobalNumbers($row->ids_his, $hisStep, true);
                            if ($returnVal == "") {
                                $tmp[$fName] = "-";
                            }
                            else {
                                $tmp[$fName] = $returnVal;
                            }
                        }
                        else {
                            $tmp[$fName] = "-";
                        }
                    }
                    else {
                        $tmp[$fName] = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : formatField_he_format($fName, 0);
                    }

                    if ($fName == "no") {
                        $tmp[$fName] = formatField_he_format($fName, $numb);
                    }
                }

                if ($row->sub_step_number > 0) {
                    // $tmp['state'] = "<span style='color:" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateColor'] . "'>" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateLabel'] . "</span>";
                    // $tmp['state'] .= "<br>" . createStateSign($row->sub_step_number, $row->step_avail, $jenisTr);
                    $tmp['state'] = createStateHorizontal($row->sub_step_number, $row->step_avail, $jenisTr);
                }
                else {
                    $tmp['state'] = "<span style='color:#777777'>canceled</span>";
                }


                $tmp['action'] = "";
                $nextStepNum = ($row->next_substep_num);
                $currentStepNum = ($row->sub_step_number);
                $nextStepCode = ($row->next_step_code);
                $allowJoin = isset($this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin']) && $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] == true ? $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] : false;


                $allowFollowup = false;
                if ($row->sub_step_number > 0) {
                    //                    if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum)) {
                    //                        //                        if (in_array($this->configUi[$jenisTr]['steps'][$currentStepNum]['userGroup'], $this->session->login['membership'])) {
                    //                        $allowFollowup = true;
                    //                        $actionLabel = "review " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                    //                    }
                    $allowFollowup = true;
                    $actionLabel = "review " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                }

                if (isset($this->configUi[$jenisTr]['steps'][$nextStepNum])) {
                    // cekHitam("ada");
                    // if (isset($this->accessList[$jenisTr])) {
                    //     if (isset($this->accessList[$jenisTr][$nextStepNum][$nextStepCode]["allowFollowUp"])) {
                    //         // $allowFollowup = $this->accessList[$jenisTr][$nextStepNum][$nextStepCode]["allowFollowUp"];
                    //         // $actionLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['actionLabel'];
                    //     }
                    //
                    //
                    // }
                    // else {
                    if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $nextStepNum)) {
                        if (in_array($this->configUi[$jenisTr]['steps'][$nextStepNum]['userGroup'], $this->session->login['membership'])) {
                            // cekBiru("bolehhh");
                            $allowFollowup = true;
                            $actionLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['actionLabel'];

                        }
                        else {
                            // cekMErah("gak bolehhh");
                        }
                    }
                    else {
                        // cekKuning("nano nano");
                    }

                }

                if ($allowFollowup) {
                    $stepLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['label'];
                    $isCancelPacking = isset($this->configUi[$jenisTr]['steps'][$nextStepNum]['isCancelPacking']) ? $this->configUi[$jenisTr]['steps'][$nextStepNum]['isCancelPacking'] : false;
                    $allowCancel = isset($this->configUi[$jenisTr]['steps'][$nextStepNum]['allowCancel']) ? $this->configUi[$jenisTr]['steps'][$nextStepNum]['allowCancel'] : false;

                    $targetFollowupLink = $isCancelPacking == true ? "followupCancelPackingPrePreview" : "followupPrePreview";
                    //                    $followupLink = "top.$('#result').load('" . base_url() . "Transaksi/followupPrePreview/" . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
                    $followupLink = "disableShopCart();top.$('#result').load('" . base_url() . $this->modul . "/FollowUp/$targetFollowupLink/$jenisTr/" . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
                    //                        $tmp['action'] = "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' href='JavaScript:void(0)' onClick =\"$followupLink\">" . $actionLabel . "</a>";
                    $tmp['action'] = "<div class='input-group'>";
                    $tmp['action'] .= "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' data-toggle='tooltip' href='JavaScript:void(0)' onClick =\"top.open_holdon();$followupLink\"><span class='glyphicon glyphicon-ok'></span> " . $actionLabel . "</a>";
                    if ($allowJoin) {
                        $tmp['action'] .= "<span class='input-group-addon'>";
                        $tmp['action'] .= "<a title='process many items at once' href='" . base_url() . "Transaksi/viewIncomplete/" . $this->jenisTr . "/$currentStepNum'><span class='fa fa-dedent'></span></a>";
                        $tmp['action'] .= "</span class='input-group-addon'>";
                    }
                }
                //                $arrayOnprogress[] = $tmp;
                //                if (isset($arrDue[$row->transaksi_id]) && $arrDue[$row->transaksi_id]['aging'] > 0) {
                //                    cekhere($row->transaksi_id);
                //                    $arrOver_due[] = $tmp;
                //                } else {
                $arrayOnprogress[] = $tmp;
                //                }
            }
        }
        //endregion
//arrPrint($arrayOnprogress);
        /*---dari apk-----*/
        $selectedApkId = "";
        $session_main = isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array();
        if (isset($session_main['apk_trid'])) {
            // if(isset($_SESSION[$cCode]['main'])){
            $selectedApkId = $session_main['apk_trid'];
            $http_referer = $_SERVER['HTTP_REFERER'];

            $modul_ini = url_segment(1);
            // arrPrintPink(uri_string($http_referer));
            $expl_url = explode('/', $http_referer);
            $controler_ky = array_flip($expl_url)[$modul_ini] + 1;
            $referer_controler = $expl_url[$controler_ky];
            if ($referer_controler != "Create") {
                $url_tujuan = str_replace($referer_controler, "Create", $http_referer);

                echo "<script>top.location.href='$url_tujuan';</script>";
            }
            // arrPrint();
            // cekMerah("jj -- " . APPPATH . MODUL_PATH);
            $apk_trid = $session_main["apk_trid"];
        }
        //region lookup on-going from connected requests
        if (!isset($_SESSION['undoneQty'])) {
            $_SESSION['undoneQty'] = array();
        }
        if (!isset($_SESSION['undoneQty'][$this->jenisTr])) {
            $_SESSION['undoneQty'][$this->jenisTr] = 0;
        }
        $progress2Fields = array();
        $arrayOnprogress2 = array();
        $reqFormTarget = "";
        $needToClear = false;
        $allowMultiSelect = false;
        if (isset($this->configUi[$jenisTr]['requestCode'])) {
            $masterRefCode = $this->configUi[$jenisTr]['requestCode']['masterCode'];
            $stateRefCode = $this->configUi[$jenisTr]['requestCode']['stateCode'];
            $stateRefNum = $this->configUi[$jenisTr]['requestCode']['stepNumber'];
            $progress2Fields = isset($this->configUi[$masterRefCode]['shortHistoryFields']) ? $this->configUi[$masterRefCode]['shortHistoryFields'] : "";
            //            $glanceHistoryFields2 = isset($this->configUi[$masterRefCode]['glanceHistoryFields']) ? $this->configUi[$masterRefCode]['glanceHistoryFields'] + array("select" => "select") : array("nomer" => "receipt no");
            /*--ambil confignya 581-*/
            $glanceHistoryFields2 = isset($this->configUi[$masterRefCode]['glanceHistoryFields']) ? $this->configUi[$masterRefCode]['glanceHistoryFields'] : array("nomer" => "receipt no");
            $reqFormTarget = base_url() . $this->modul . "/" . get_class($this) . "/swapFrom/$jenisTr";

            // arrPrintPink($glanceHistoryFields2);
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
            $tr->addFilter("transaksi.jenis_master='" . $masterRefCode . "'");
            $tr->addFilter("transaksi.jenis='" . $stateRefCode . "'");
            //            $tr->addFilter("transaksi.step_number='" . $stateRefNum . "'");
            $tr->addFilter("transaksi.step_current='" . $stateRefNum . "'");
            $tmpByReq = $tr->lookupRecentHistories()->result();
            /*pengabungan data reguler dan data dari apk*/
            $gabungan = array_merge($tmpByReq, $apkTmp);

            $needToClear = false;
            if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                $needToClear = true;
            }
            $_SESSION['undoneQty'][$this->jenisTr] = sizeof($tmpByReq);

            if (sizeof($gabungan) > 0) {

                $allowMultiSelect = isset($this->configUi[$jenisTr]['requestCode']['allowMultiSelect']) ? $this->configUi[$jenisTr]['requestCode']['allowMultiSelect'] : false;
                $historyFields["apk_version"] = "apk_version";
                $reqCtr = 0;
                // foreach ($tmpByReq as $row) {
                foreach ($gabungan as $row) {
                    $reqCtr++;

                    $apk_version = isset($row->apk_version) ? $row->apk_version : "0";
                    $tmp = array();
                    $inputType = $allowMultiSelect == true ? "checkbox" : "radio";
                    //                    $clickEvent = "onclick=\"return false;\"";
                    // arrPrintHijau($session_main["apk_trid"]);
                    // arrPrint($row);
                    $checked_req = $row->id == $selectedApkId . "_apk" ? "checked" : "";
                    $clickEvent = "";
                    if ($inputType == "radio" && !$needToClear) {
                        //                        $clickEvent="onclick=\"document.getElementById('btnConnect').innerHTML='Clear the list to process one of entries above';document.getElementById('btnConnect').disabled=true;document.getElementById('fAsNew').submit()\"";
                        $clickEvent = "onclick=\"document.getElementById('fAsNew').submit()\"";
                    }
                    $tmp['select'] = "<input $checked_req class='order_request' type=$inputType name='trID[]' value='" . $row->id . "' id='select_" . $reqCtr . "' $clickEvent>";
                    $tmp['id'] = $row->id;
                    foreach ($historyFields as $fName => $fLabel) {
                        //                        $tmp[$fName] = formatField_he_format($fName, $row->$fName);
                        $tmp[$fName] = isset($row->$fName) ? $row->$fName : "";
                    }


                    $arrayOnprogress2[] = $tmp;
                }
            }
            if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                $needToClear = true;
            }

        }
        //endregion
        $sumFooterResult = array();
        if (isset($sumFooter) && sizeof($sumFooter) > 0) {
            foreach ($sumFooter as $key => $val) {
                $sumFooterResult[$key] = formatField_he_format($key, $val);
            }
        }

        $data = array(
            "mode"                 => "viewUndoneItems",
            // "mode" => $this->uri->segment(3),
            "isMobile"             => $isMob,
            //            "arrayProgressLabels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progressFields : $glanceHistoryFields,
            //            "arrayProgress2Labels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progress2Fields : $glanceHistoryFields2,
            "arrayProgressLabels"  => $progressFields,
            "arrayProgress2Labels" => $glanceHistoryFields2,
            "arrayOnProgress"      => $arrayOnprogress,
            "arrayOnProgress2"     => $arrayOnprogress2,
            "needToClear"          => $needToClear,
            "selectedApkId"        => $selectedApkId,
            "reqFormTarget"        => $reqFormTarget,
            "allowMultiSelect"     => $allowMultiSelect,
            "overDue"              => $arrOver_due,
            "clearCartTarget"      => base_url() . $this->modul . "/_shoppingCart/reset/" . $this->jenisTr,

            "sumFooter" => $sumFooterResult,
        );

        $this->load->view("transaksi", $data);

    }

    public function viewUndonePacking()
    {
        if (!isset($this->session->login['id'])) {
            gotoLogin();
        }
        $starttime = microtime(true);
        $limit = 20;
        $maxPageNum = 20;
        $jenisTr = $this->jenisTr;
        $jenisTrsub = $this->uri->segment(5);
        $cCode = $this->cCode;
        $allStep = $this->configUi[$jenisTr]['steps'];
        $availSteps = array();
        foreach ($allStep as $step => $tempStep) {
            $availSteps[$tempStep['target']] = $step;
        }
        $selectedSTep = isset($availSteps[$jenisTrsub]) ? $availSteps[$jenisTrsub] : 1;
        $historyFields = isset($this->configUi[$jenisTr]['historyFields'][$selectedSTep]) ? $this->configUi[$jenisTr]['historyFields'][$selectedSTep] : $this->configUi[$jenisTr]['shortHistoryFields'];
        $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
        //        $historyFieldsExt = isset($this->configUi[$jenisTr]["extHistoryFields"][$selectedSTep]) ? $this->configUi[$jenisTr]["extHistoryFields"][$selectedSTep] : array();
        $extHistoryFields2 = isset($this->configUi[$jenisTr]["extHistoryFields2"][$selectedSTep]) ? $this->configUi[$jenisTr]["extHistoryFields2"][$selectedSTep] : array();
        $customButton = isset($this->configLayout[$jenisTr]["customButton"][$selectedSTep]) ? $this->configLayout[$jenisTr]["customButton"][$selectedSTep] : array();
        $printValas = isset($this->configLayout[$jenisTr]["print_nvalas"]) ? $this->configLayout[$jenisTr]["print_nvalas"] : array();
        $pairTransaksi = isset($this->configUi[$jenisTr]['pairTransaksi']) ? $this->configUi[$jenisTr]['pairTransaksi'] : array();
        $extHistoryKeterangan = isset($this->configUi[$jenisTr]['extHistoryKeterangan'][$selectedSTep]) ? $this->configUi[$jenisTr]['extHistoryKeterangan'][$selectedSTep] : array();

        $historyFields = array(
            0 => array(
                "dtime_inv"     => "tgl invoice",
                "nomer_top"     => "NO SO",
                "nomer_pl"      => "NO PL",
                "transaksi_no"  => "NO INV",
                "customer_nama" => "konsumen",
                "oleh_nama"     => "PIC Gudang",
                "kurir_nama"    => "PIC Kurir",
                "dtime_kirim"   => "Tgl Kirim",
            ),
            1 => array(
                "dtime_inv"     => "tgl invoice",
                "nomer_top"     => "NO SO",
                "nomer_pl"      => "NO PL",
                "transaksi_no"  => "NO INV",
                "customer_nama" => "konsumen",
                "oleh_nama"     => "PIC Gudang",
                "kurir_nama"    => "PIC Kurir",
                "dtime_kirim"   => "Tgl Kirim",
                "dtime_sampai"  => "Tgl Sampai",
            ),
        );

        $historyFieldsExt = array(
            0 => array(
                "customer_nama" => "customer_nama",
                "transaksi_no"  => "transaksi_no",
                "master_nomer"  => "master_nomer",
                "dtime_inv"     => "dtime_inv",
                "data_produk"   => "data_produk",
                "status"        => "status",
                "oleh_nama"     => "oleh_nama",
                "dtime_kirim"   => "dtime_kirim",
                "dtime_sampai"  => "dtime_sampai",
                "data_kirim"    => "data_kirim",
            ),
            1 => array(
                "customer_nama" => "customer_nama",
                "transaksi_no"  => "transaksi_no",
                "master_nomer"  => "master_nomer",
                "dtime_inv"     => "dtime_inv",
                "data_produk"   => "data_produk",
                "status"        => "status",
                "oleh_nama"     => "oleh_nama",
                "dtime_kirim"   => "dtime_kirim",
                "dtime_sampai"  => "dtime_sampai",
                "data_kirim"    => "data_kirim",
            ),
        );

        //        $modul_path = base_url() . $modul . "/";
        //arrPrint($extHistoryKeterangan);

        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }

        $backdate_f = formatTanggal(backDate(30), 'Y-m-d');

        $date1 = isset($_GET['date1']) ? $_GET['date1'] : $backdate_f;
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");

        // cekHere($date1." ******* ".$date2);

        //region preparing ERP step labels for top link
        $steps = $this->configUi[$jenisTr]['steps'];
        $steps = array(
            0 => array(
                "target" => 0,
                "label"  => "Belum Dikirim"
            ),
            1 => array(
                "target" => 1,
                "label"  => "Sampai Tujuan"
            )
        );
        $stepLabels = array();
        $stepLinks = array();
        if (sizeof($steps) > 1) {
            $subCodes = array();
            $stepCodes = array();
            $jmlStep = count($steps);
            foreach ($steps as $stepNumber => $stepSpec) {
                if ($stepNumber <= $jmlStep) {
                    $subCodes[$stepSpec['target']] = $stepSpec['label'];
                    $stepCodes[] = $stepSpec['target'];
                    $stepLabels[$stepNumber] = $stepSpec['label'];
                    $stepLinks[$stepNumber] = MODUL_PATH . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $stepSpec['target'] . "";
                }
            }
            if (isset($_GET['stID'])) {
                $currentState = $_GET['stID'];
            }
            else {
                $currentState = strlen($this->uri->segment(5)) > 0 ? $this->uri->segment(5) : 0;
            }
        }
        //endregion

        //region lookup histories
        $this->load->model("Mdls/MdlTransaksiStatus");
        $tr = new MdlTransaksiStatus();

        $searchStr = isset($_GET['search']) ? $_GET['search'] : "";
        if (my_cabang_id() == "-1") {
            $filters = array(
                // "cabang_id" => $this->placeId,
                //                "jenis_master" => $this->jenisTr,
                //                "link_id" => "0",
                //                "div_id" => $this->session->login['div_id'],
            );
        }
        else {
            if ($this->session->login['employee_type'] == "employee_freelance") {
                $filters = array(
                    //                    "cabang_id" => $this->placeId,
                    //                    "jenis_master" => $this->jenisTr,
                    //                    "link_id" => "0",
                    //                    "div_id" => $this->session->login['div_id'],
                    //                    "seller_id" => $this->session->login['id']
                );
            }
            else {
                $filters = array(
                    //                    "cabang_id" => $this->placeId,
                    //                    "jenis_master" => $this->jenisTr,
                    //                    "link_id" => "0",
                    //                    "div_id" => $this->session->login['div_id'],
                );
            }
        }

        if (isset($filters) && (sizeof($filters) > 0)) {
            foreach ($filters as $key_f => $val_f) {
                $tr->addFilter("$key_f='" . $val_f . "'");
            }
        }
        if (isset($currentState)) {
            $tr->addFilter("status='" . $currentState . "'");
        }

        $tmpHist = $tr->lookupAll()->result();

        $arrayHistory = array();
        $arrayHistory_ids = array();
        $arrayHistory_canceled = array();
        $sumValue = array();
        if (sizeof($tmpHist) > 0) {
            $numb = 0;
            foreach ($tmpHist as $ii => $row) {
                $toko_id = $row->toko_id;

                if (sizeof($historyFieldsExt) > 0) {
                    foreach ($historyFieldsExt[$currentState] as $alias => $colom) {
                        $row->$alias = $row->$colom;
                    }
                }
                $tmp = array();
                $tmp1 = array();
                $numb++;
                foreach ($historyFields[$currentState] as $fName => $fLabel) {
                    if ($fName == "data_produk") {
                        $tmp[$fName] = "array produk";
                    }
                    else {
                        //                        $tmp[$fName] = $row->$fName;
                        $tmp[$fName] = formatField_he_format($fName, $row->$fName, "", "");
                    }
                }

                $arrayHistory[$ii] = $tmp;
                $arrayHistory_ids[$ii] = $tmp1;
            }
        }

        //region link to add new transaction
        if (placeCanMakeTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $this->configUiJenis)) {
            //        if (in_array($this->configUi[$jenisTr]["steps"][1]['userGroup'], $this->session->login['membership'])) {
            $createIndexes = (null != $this->config->item("transaksi_createIndex")) ? $this->config->item("transaksi_createIndex") : array();
            if (array_key_exists($this->jenisTr, $createIndexes)) {
                $targetUrl = MODUL_PATH . $createIndexes[$this->jenisTr] . "/" . $this->jenisTr;
            }
            else {
                $targetUrl = MODUL_PATH . "Create/index/" . $this->jenisTr;
            }
            $addLink = array(
                "link"  => $targetUrl,
                "label" => "<span class='glyphicon glyphicon-plus'></span> create new " . $this->configUi[$jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion

        //region prepare params for viewer
        $data = array(
            "mode"                 => "viewUndonePacking",
            "isMobile"             => $isMob,
            "jenisTr"              => $jenisTr,
            "trName"               => $this->configUi[$jenisTr]["label"],
            "errMsg"               => $this->session->errMsg,
            "title"                => isset($subCodes) && isset($currentState) ? $subCodes[$currentState] : $this->jenisTrName,
            "subTitle"             => "histories",
            "customButton"         => $customButton,
            "customButtonTarget"   => isset($currentState) ? "$currentState?date1=$date1&date2=$date2" : "",
            "arrayHistoryLabels"   => $historyFields[$currentState],
            "arrayHistory"         => $arrayHistory,
            "arrayHistorySumField" => $sumValue,
            "arrayHistoryId"       => $arrayHistory_ids,
            //            "action" => $action,
            "steps"                => $steps,
            "stepLabels"           => $stepLabels,
            "stepLinks"            => $stepLinks,
            "addParams"            => isset($_GET['addParams']) ? $_GET['addParams'] : null,
            "currentState"         => isset($currentState) ? $currentState : "all states",
            "alternateLink"        => "",
            "alternateLinkCaption" => "",
            "addLink"              => $addLink,
            "filters"              => array(
                "dates" => $this->dates,
                "date1" => $date1,
                "date2" => $date2,
            ),
            "thisPage"             => MODUL_PATH . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6),
            "history_canceled"     => isset($arrayHistory_canceled) ? $arrayHistory_canceled : array(),
            "history_keterangan"   => isset($arrayHistory_keterangan) ? $arrayHistory_keterangan : array(),
        );
        //endregion

        $endtime = microtime(true); // Bottom of page
        $valTimeEnd = $endtime - $starttime;
        $this->load->view("history", $data);
    }

    public function viewResume()
    {
        $globalVars = array();
        $no = $this->uri->segment(5);
        // $this->jenisTr = explode(".", $no)[0];
        $cCode = $this->cCode;
        $this->load->config("heAccounting");
        $accountChildsLinks = $this->config->item("accountChildsLinks");

        $this->load->model("MdlTransaksi");
        // $this->load->model("Mdls/MdlMongoMother");
        $tr = new MdlTransaksi();
        $tr->addFilter("nomer='$no'");
        $tmp1 = $tr->lookupAll()->result();
        //        showLast_query("biru");
        if (sizeof($tmp1[0]) > 0) {
            foreach ($tmp1[0] as $tmpKey => $tmpVal) {
                $rkey_field = $tmpKey;
                if ($rkey_field == "nomer") {
                    $rkey_field = "nomer_nolink";
                }
                //                $globalDatas[$rkey] = formatField_he_format($rkey_field, $rval, "", "");
                $globalVars[$tmpKey] = formatField_he_format($rkey_field, $tmpVal, "", "");
            }
        }

        $jenisMasterTrans = $tmp1[0]->jenis_master;
        $transaksiID = $tmp1[0]->id;
        $transaksiTopID = $tmp1[0]->id_top;
        $step_number = $tmp1[0]->step_number < 1 ? 1 : $tmp1[0]->step_number;
        $configUiJenis = loadConfigModulJenis_he_misc($jenisMasterTrans, "coTransaksiUi");
        $globalVars['transaksi_nama'] = $configUiJenis['label'];
        $globalVars["transaksi_nama_" . $step_number] = $configUiJenis['steps'][$step_number]["label"];
        $globalVars["transaksi_actionLabel"] = $configUiJenis['steps'][$step_number]["actionLabel"];
        $pairRegistry = isset($configUiJenis["pairRegistries"]) ? $configUiJenis["pairRegistries"] : array("main", "items");
        $configNotes = isset($configUiJenis["canceledLabel"][$step_number]) ? $configUiJenis["canceledLabel"][$step_number] : NULL;

        // membaca status edit di TOPID
        $tr = new MdlTransaksi();
        $tr->addFilter("id='$transaksiTopID'");
        $tmpTop = $tr->lookupAll()->result();
        $arrTopEdit = array();
        if (sizeof($tmpTop) > 0) {
            if ((isset($tmpTop[0]->status_edit)) && ($tmpTop[0]->status_edit == 1)) {
                $arrTopEdit[$transaksiTopID] = array(
                    "status_edit" => $tmpTop[0]->status_edit,
                    "edit_dtime"  => $tmpTop[0]->edit_dtime,
                    "edit_id"     => $tmpTop[0]->edit_id,
                    "edit_name"   => $tmpTop[0]->edit_name,
                );
            }
        }

        //region swap from registry

        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->setJointSelectFields($pairRegistry);//select fields jika ada, atau biarkana array untuk reset
        $tr->addFilter("transaksi_id='$transaksiID'");
        $tmpReg = $tr->lookupDataRegistries()->result();

        if (sizeof($tmpReg) > 0) {
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $eParams) {
                    foreach ($pairRegistry as $param) {
                        $$param = blobDecode($eParams->$param);
                    }
                }
            }
        }
        //endregion

        //region signatures
        $signNumbers = array();
        $signValues = array();
        $signExtValues = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $masterID = isset($tmp1[0]->id_master) ? $tmp1[0]->id_master : 0;
        $tmpSign = $trs->lookupSignaturesByMasterID($masterID)->result();
        //         cekLime($this->db->last_query());
        // arrPrint($tmpSign);
        $arrCounters = blobDecode($tmp1[0]->counters);
        //        arrPrintKuning($arrCounters);
        $urutCounters = NULL;
        if (sizeof($arrCounters) > 0) {
            $key2 = $tmp1[0]->jenis . "|" . $tmp1[0]->toko_id;
            $urutCounters = digit_5($arrCounters["stepCode|tokoID"][$key2]);
        }
        if ($urutCounters != NULL) {
            $urutCounters = "-$urutCounters";
        }

        if (isset($this->configUi[$tmp1[0]->jenis_master]['resumeFieldNames'])) {
            $resumeFields = $this->configUi[$tmp1[0]->jenis_master]['resumeFieldNames']['selectFields'];
            $resumeTitle = $this->configUi[$tmp1[0]->jenis_master]['resumeFieldNames']['title'];
            $resumeName = isset($tmp1[0]->$resumeFields) ? $tmp1[0]->$resumeFields : "";
        }
        else {
            $resumeTitle = "";
            $resumeName = "";
        }

        $arrSignName = array();
        if (sizeof($tmpSign) > 0) {
            foreach ($tmpSign as $ii => $row) {
                $signValues['sign_' . $row->id . '_' . $row->step_number] = array(
                    "title" => isset($this->configUi[$tmp1[0]->jenis_master]['steps'][$row->step_number]['label']) ? $this->configUi[$tmp1[0]->jenis_master]['steps'][$row->step_number]['label'] : "",
                    "label" => isset($this->configUi[$tmp1[0]->jenis_master]['steps'][$row->step_number]['stateCaption']) ? $this->configUi[$tmp1[0]->jenis_master]['steps'][$row->step_number]['stateCaption'] : "",
                    "dtime" => $row->dtime,

                    "nomer"      => formatField_he_format("nomer_nolink", $row->nomer),
                    "nomer_orig" => $row->nomer,

                    "oleh"               => isset($row->oleh_nama) ? $row->oleh_nama : "",
                    "caption_department" => isset($this->config->item("userGroup")[$row->group_code]) ? $this->config->item("userGroup")[$row->group_code] : "",
                    "prev_id"            => isset($row->prev_id) ? $row->prev_id : 0,
                    "link_id"            => isset($row->transaksi_id) ? $row->transaksi_id : 0,
                );
                $arrSignName[$ii] = array(
                    "nama"  => $row->oleh_nama,
                    "dtime" => $row->dtime,
                );
            }
        }
        $signStr = "";
        //endregion

        //entry points
        $trep = new MdlTransaksi();
        //        $tmpEP = $trep->lookupEntryPoints_joined($masterID)->result();
        $tmpEP = $trep->lookupEntryPoints($masterID)->result();
        //        showLast_query("biru");
        //arrPrintHijau($tmpEP);
        $epValues = array();
        if (sizeof($tmpEP) > 0) {
            foreach ($tmpEP as $ii => $row) {
                $jenisEx = explode("_", $row->jenis);
                $jenis = $jenisEx[0];
                $counterDecode = blobDecode($row->counters);
                $counterjenis = $jenis . "|" . $row->toko_id;

//                arrPrint($counterDecode);
                $counterGlobal = $counterDecode['stepCode|tokoID'][$counterjenis];
//                cekMerah("counterGlobal: $counterGlobal");
                $cGlobals = digit_5($counterGlobal);


                $epValues['sign_' . $row->transaksi_id . '_' . $row->step_number] = array(
                    //                $epValues['sign_' . $row->id . '_' . $row->step_number] = array(
                    "title"              => isset($this->configUi[$row->jenis_master]['steps'][$row->step_number]['label']) ? $this->configUi[$row->jenis_master]['steps'][$row->step_number]['label'] : "",
                    "cabang_nama"        => $row->cabang_nama,
                    "label"              => $row->jenis_label,
                    "dtime"              => $row->dtime,
                    "nomer"              => formatField_he_format("nomer_nolink", $row->nomer),
                    "nomer_orig"         => $row->nomer,
                    "oleh"               => $row->oleh_nama,
                    "caption_department" => "text",
                    "deskripsi"          => $row->deskripsi,
                    "link_id"            => $row->link_id,
                    "global_counter"     => $cGlobals,
                );
            }
        }
        //        arrPrintHijau($tmpEP);
        //arrPrintPink($signValues);
        //        cekHitam(sizeof($tmpEP) . " --- $masterID ---");
        //        $signArray = sizeof($epValues) > 0 ? $epValues : $signValues;
        $signArray = $epValues;
        //        arrPrint($signArray);

        if (sizeof($signArray) > 0) {
            $signStr .= "<div class='panel'>";
            $signStr .= "<h4 class='text-blue'><span class='fa fa-sign-in'></span> entry points </h4>";
            $signStr .= "<h5 class='text-blue'><span class='fa fa-tasks'></span> $resumeTitle  $resumeName</h5>";
            $signStr .= "<table class='table table-condensed'>";
            $signStr .= "<tr bgcolor='#f0f0f0'>";
            $signStr .= "<td class='text-muted'>date</td>";
            $signStr .= "<td class='text-muted'>title</td>";
            $signStr .= "<td class='text-muted'>branch</td>";
            $signStr .= "<td class='text-muted'>transaction number</td>";
            $signStr .= "<td class='text-muted'>person</td>";
            $signStr .= "<td class='text-muted'>tool</td>";
            foreach ($signArray as $k => $sSpec) {

                $signDeskripsi = isset($sSpec['deskripsi']) ? " (" . $sSpec['deskripsi'] . ")" : "";
                $nomerOrig = $sSpec['nomer_orig'];
                $nomerOrigEx = explode("_", $nomerOrig);
                $nomerOrigNota = $nomerOrigEx[0];
                $nomerView = $nomerOrigNota . "-" . $sSpec['global_counter'];
                $oleh_nama = isset($arrSignName[$k]) ? $arrSignName[$k] : $sSpec['oleh'];

                $edit_description = "";
                if (isset($arrTopEdit[$sSpec['link_id']])) {
                    $edit_dtime = formatField_he_format("date_time", $arrTopEdit[$sSpec['link_id']]['edit_dtime']);
                    $edit_nama = $arrTopEdit[$sSpec['link_id']]['edit_name'];
                    $edit_description = "<span style='color:red;'>Edited by $edit_nama, $edit_dtime</span>";
                }

                $signStr .= "<tr>";
                $signStr .= "<td>" . formatField_he_format("date_time", $sSpec['dtime']);
                $signStr .= "</td>";
                //                $signStr .= "<td>" . ($sSpec['title']);
                $signStr .= "<td>" . ($sSpec['label']);
                $signStr .= "</td>";
                $signStr .= "<td>" . (isset($sSpec['cabang_nama']) ? $sSpec['cabang_nama'] : "-");
                $signStr .= "</td>";
                $signStr .= "<td>" . (formatField_he_format("nomer_nolink", $nomerView)) . $signDeskripsi . "<br>$edit_description";
                $signStr .= "</td>";
                $signStr .= "<td>";
                $signStr .= ("<span class='fa fa-user'></span> " . $oleh_nama . "");
                $signStr .= "</td>";

                $signStr .= "<td>";
                $signStr .= formatField_he_format("print_label", $nomerOrigNota, $this->jenisTr, MODUL_PATH);
                $signStr .= "</td>";
                $signStr .= "</tr>";
            }
            $signStr .= "</table class='table table-condensed'>";
            $signStr .= "</div class='panel'>";
        }

        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $allowedView = $this->config->item('userGroup_jurnal') != null ? $this->config->item('userGroup_jurnal') : array();

        //        $rekeningAlias = $this->config->item('accountAlias') != null ? $this->config->item('accountAlias') : array();

        $rekeningAlias = fetchAccountStructureAlias();

        $lItems = array();
        $headers = array();
        $arrCabang = array();
        if (array_intersect($allowedView, $mems)) {
            $this->load->model("Coms/ComJurnal");
            $this->load->model("Mdls/MdlCabang");

            $cb = New MdlCabang();
            $tmpCb = $cb->lookupAll()->result();
            $arrCabang = array();
            if (sizeof($tmpCb) > 0) {
                foreach ($tmpCb as $spec) {
                    $arrCabang[$spec->id] = $spec->nama;
                }
            }

            $j = new ComJurnal();
            $j->addFilter("transaksi_no='$no'");
            if ($this->session->login['cabang_id'] == CB_ID_PUSAT) {

            }
            else {
                // dimatikan dulu untuk checking jurnal lengkapnya...........
                //                $j->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
            }
            //            $j->setSortBy(array("kolom" => "urut", "mode" => "ASC"));
            $tmp = $j->lookupAll()->result();
            $headers = array(
                "dtime"    => "date",
                "rekening" => "account",
                "debet"    => "debet",
                "kredit"   => "kredit",
            );
            $lItems = array();
            if (sizeof($tmp) > 0) {
                /* ---------------------------------------
                 * array link untuk mengarahkan ke halaman mutasi yg dikendaki
                 * -----------------------------------*/

                //region Description
                $mutasiLinks = array();
                foreach ($accountChildsLinks as $rekNama => $rekLink) {
                    $mutasiLinks[$rekNama] = $rekLink . "/" . $main['pihakID'] . "?o=" . $main['cabangID'] . "&trID=$transaksiID";
                }
                //endregion

                foreach ($tmp as $row) {
                    $d_start = backCustomDate("30", $row->dtime);
                    $d_stop = $row->dtime;
                    if ($row->j_jenis == "items") {
                        $blob_ext = blobEncode($row->rekening);
                        //                        Ledger/viewMoveDetails/RekeningPembantuProduk/persediaan%20produk/1076?o=-1&ext2_id=&main_ext2_id=
                        $defLink = "Ledger/viewMoveDetails/RekeningPembantuProduk/" . $row->rekening_main . "/" . $row->extern_id . "?o=" . $row->cabang_id . "&trID=$transaksiID&date1=$d_start&date2=$d_stop&blob_ext=$blob_ext";
                    }
                    else {
                        $defLink = "Ledger/viewMoveDetails_1/Rekening/" . $row->rekening . "?o=" . $row->cabang_id . "&trID=$transaksiID&date1=$d_start&date2=$d_stop";
                        //                    $defLink = "Ledger/viewMoves_l1/Rekening/" . $row->rekening . "?o=" . $row->cabang_id . "&trID=$transaksiID&date1=$d_start&date2=$d_stop";
                    }

                    //                    $rekening_alias = isset($rekeningAlias[$row->rekening]) ? $rekeningAlias[$row->rekening] : $row->rekening;
                    $rekening_alias = isset(fetchAccountStructureAlias()[$row->rekening]) ? fetchAccountStructureAlias()[$row->rekening] : $row->rekening;
                    if ($row->debet > 0 || $row->kredit > 0) {
                        //$strLink = key_exists($row->rekening, $mutasiLinks) ? $mutasiLinks[$row->rekening] : $defLink;
                        $strLink = $defLink;
                        $lItems[$row->cabang_id][$row->urut][] = array(
                            "dtime"    => $row->dtime,
                            "rekening" => $row->debet > 0 ? $rekening_alias : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $rekening_alias,
                            "debet"    => $row->debet > 0 ? $row->debet : "",
                            "kredit"   => $row->kredit > 0 ? $row->kredit : "",
                            "link"     => base_url() . $strLink,
                        );
                    }
                }
                //                arrPrint($lItems);
                ksort($lItems);
            }


        }

        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        $mobMode = $isMob == true ? "1" : "0";

        $printSettings = isset($this->configLayout[$jenisMasterTrans]['allowPrint']['1']) ? $this->configLayout[$jenisMasterTrans]['allowPrint']['1'] : array();
        $printLocation = isset($this->configLayout[$jenisMasterTrans]['printLocation']) ? $this->configLayout[$jenisMasterTrans]['printLocation'] : "Transaksi/viewReceipt/";

        $valasType = (isset($main['currencyDetails__label'])) ? "&type=" . blobEncode($main['currencyDetails__label']) : "";
        $valasFKali = "&f=" . blobEncode(1);

        if (sizeof($tmpSign) > 0) {
            if (isset($printSettings['size'])) {
                switch ($printSettings['size']) {
                    case "normal":
                        $receiptLink = "top.popBig('" . MODUL_PATH . $printLocation . $this->jenisTr . "/" . "$no?mobMode=$mobMode&st=1$valasType$valasFKali');";
                        break;
                    case "small":
                        $receiptLink = "top.popSmall('" . MODUL_PATH . $printLocation . $this->jenisTr . "/" . "$no?mobMode=$mobMode&st=2');";
                        break;
                    default:
                        //                                cekkuning("size: UNKNOWN");
                        break;
                }
            }
            else {
                $receiptLink = "top.popBig('" . MODUL_PATH . $printLocation . $this->jenisTr . "/" . "$no?mobMode=$mobMode&st=3$valasType$valasFKali');";
            }
        }
        else {
            $receiptLink = "top.popBig('" . MODUL_PATH . $printLocation . $this->jenisTr . "/" . "$no?st=4');";
        }


        // ============== TAMBAHAN ============== ============== ==============
        $itemLabels = isset($this->configUi[$jenisMasterTrans]['shoppingCartFields'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartFields'][1] : array();
        $itemLabels2 = isset($this->configUi[$jenisMasterTrans]['shoppingCartFields2'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartFields2'][1] : array();
        $itemLabels3 = isset($this->configUi[$jenisMasterTrans]['shoppingCartFields3'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartFields3'][1] : array();
        $itemNumLabels = isset($this->configUi[$jenisMasterTrans]['shoppingCartNumFields'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartNumFields'][1] : array();
        $itemNumLabels2 = isset($this->configUi[$jenisMasterTrans]['shoppingCartNumFields2'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartNumFields2'][1] : array();
        $itemNumLabels3 = isset($this->configUi[$jenisMasterTrans]['shoppingCartNumFields3'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartNumFields3'][1] : array();
        $sumRows = isset($this->configUi[$jenisMasterTrans]['shoppingCartSumFields'][1]) ? $this->configUi[$jenisMasterTrans]['shoppingCartSumFields'][1] : $this->configLayout[$jenisMasterTrans]['receiptSumFields'][1];
        $noteEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteEnabled']) && $this->configUi[$this->jenisTr]['shoppingCartNoteEnabled'] == true ? true : false;

        $showScheme = isset($this->configUi[$this->jenisTr]['shoppingCartShowScheme']) ? $this->configUi[$this->jenisTr]['shoppingCartShowScheme'] : false;


        $arrCons = array();
        $headerScheme = array();

        if ($showScheme) {

            $awal_pinjaman = isset($main['awal_pinjaman']) ? $main['awal_pinjaman'] : date('Y-m-d');
            $jatuh_tempo = isset($main['jatuh_tempo']) ? $main['jatuh_tempo'] : date('Y-m-d');
            $nilai_pinjaman = isset($main['harga']) ? $main['harga'] : 0;
            $rate_bunga = isset($main['persen_bunga']) ? $main['persen_bunga'] : 0;

            $npwp = "";
            $pph_nilai = strlen($npwp) > 10 && $pph_nilai == 15 ? 15 : 15; //dipaksa 15% untuk pemegang saham
            $valid_bunga = ($nilai_pinjaman / 12);
            $nilai_bunga = ($valid_bunga * $rate_bunga) / 100;
            $nilai_pph23 = ($nilai_bunga * $pph_nilai) / 100;

            $period = new DatePeriod(
                new DateTime($awal_pinjaman),
                new DateInterval('P1D'),
                new DateTime($jatuh_tempo)
            );

            $periodNow = new DatePeriod(
                new DateTime($awal_pinjaman),
                new DateInterval('P1D'),
                new DateTime(date('Y-m-d'))
            );

            $arrBulan = array();
            $arrBulanNow = array();
            $arrHarian = array();
            $arrWaktu = array();

            foreach ($period as $key => $value) {
                if (!isset($arrBulan[$value->format('Y-m')])) {
                    $arrBulan[$value->format('Y-m')] = array();
                }
                $arrBulan[$value->format('Y-m')][] = $value->format('Y-m-d');
            }

            foreach ($periodNow as $key => $value) {
                if (!isset($arrBulanNow[$value->format('Y-m')])) {
                    $arrBulanNow[$value->format('Y-m')] = array();
                }
                $arrBulanNow[$value->format('Y-m')][] = $value->format('Y-m-d');
            }

            $hariPadaBulanJatuhTempo = isset($arrBulan[date('Y-m', strtotime($jatuh_tempo))]) ? count($arrBulan[date('Y-m', strtotime($jatuh_tempo))]) : 0;
            $arrBulan[date('Y-m', strtotime($jatuh_tempo))][$hariPadaBulanJatuhTempo] = date('Y-m-d', strtotime($jatuh_tempo));


            $total_hari = 0;
            $total_bulan = 0;
            foreach ($arrBulan as $thnbln => $thblntgl) {
                $tmp = array(
                    "thnbln"         => $thnbln,
                    "jml_hari_dbln"  => count($arrBulan[$thnbln]),
                    "nilai_pinjaman" => $nilai_pinjaman,
                    "rate_bunga"     => $rate_bunga,
                    "valid_bunga"    => $valid_bunga * (count($arrBulan[$thnbln]) / 30),
                    "nilai_bunga"    => $nilai_bunga * (count($arrBulan[$thnbln]) / 30),
                    "nilai_pph23"    => $nilai_pph23 * (count($arrBulan[$thnbln]) / 30),
                    "nett_bunga"     => $nilai_bunga * (count($arrBulan[$thnbln]) / 30) - ($nilai_pph23 * (count($arrBulan[$thnbln]) / 30)),
                    "silangan"       => isset($arrBulanNow[$thnbln]) ? ($thnbln != date('Y-m') ? "hijau" : "berjalan") : "merah",
                );
                if (!isset($arrCons[$thnbln])) {
                    $arrCons[$thnbln] = array();
                }
                $arrCons[$thnbln] = $tmp;
                $total_bulan++;
                $total_hari += count($arrBulan[$thnbln]);
            }

            $nmPemengangSaham = "belum memilih kreditur";
            foreach ($items as $ids => $data) {
                $nmPemengangSaham = isset($data['nama']) ? $data['nama'] : "<span class='text-bol text-red'>belum ditentunkan</span>";
            }

            $headerScheme = array(
                "nama"               => "$nmPemengangSaham",
                "jml_pinjaman"       => "$nilai_pinjaman",
                "bunga_tahunan"      => "$rate_bunga",
                "awal_meminjam"      => date('d F Y', strtotime($awal_pinjaman)),
                "pelunasan_pinjaman" => date('d F Y', strtotime($jatuh_tempo)),
                "lama_pinjaman"      => "$total_hari hari ($total_bulan bln)",
            );

        }

        $itemLabelsTop = $itemLabels + $itemNumLabels + array("subtotal" => "sub-amount");
        $item2LabelsTop = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "sub-amount");
        $item3LabelsTop = $itemLabels3 + $itemNumLabels3 + array("subtotal" => "sub-amount");
        $itemLabelBlacklist = array(
            "stok_center",
            "stok",
        );

        foreach ($itemLabelsTop as $key => $val) {
            if (in_array($key, $itemLabelBlacklist)) {
                unset($itemLabelsTop[$key]);
            }
        }
        if (isset($this->configUi[$jenisMasterTrans]['shoppingCartHideSubamount']) && $this->configUi[$jenisMasterTrans]['shoppingCartHideSubamount'][1] == true) {
            unset($itemLabelsTop['subtotal']);
            unset($item2LabelsTop['subtotal']);
            unset($item3LabelsTop['subtotal']);
        }
        $blacklistView = $this->config->item('userGroup_blacklist') != null ? $this->config->item('userGroup_blacklist') : array();
        $addFildRowFields = array();


        $allowedViewTop = false;
        foreach ($mems as $memsVal) {
            if (!in_array($memsVal, $blacklistView)) {
                $allowedViewTop = true;
            }
        }

        if ($allowedViewTop == true) {


            $m = new MdlTransaksi();
            $m->setFilters(array());
            $tmpReg = $m->lookupDataRegistriesByMasterID($transaksiTopID)->result();
            $regfields = $m->getFields()["dataRegistry"];
            $addRow = isset($this->configUi[$jenisMasterTrans]['additionalRows']['dummyElement']['yes']) ? $this->configUi[$jenisMasterTrans]['additionalRows']['dummyElement']['yes'] : array();
            $itemNotApprove = isset($this->configUi[$jenisMasterTrans]['closedRequest'][1]) ? $this->configUi[$jenisMasterTrans]['closedRequest'][1] : true;
            $detailCore = isset($this->configCore[$jenisMasterTrans]['valueGates']['detail']) ? $this->configCore[$jenisMasterTrans]['valueGates']['detail'] : array();

            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($regfields as $params) {
                        //                        cekHitam($params);
                        if ($params != "transaksi_id") {
                            if (isset($row->$params)) {
                                $var = $params . "_reg";
                                $$var = unserialize(base64_decode($row->$params));
                            }
                        }

                    }
                    // $$var = unserialize(base64_decode($row->values));
                }
                if (sizeof($addRow) > 0) {
                    foreach ($addRow as $gateKey => $mpFields) {

                        if (isset($mpFields['hideRow']) && $mpFields['hideRow'] == true) {

                        }
                        else {
                            $addFildRowFields[$gateKey] = $mpFields['label'];
                        }
                    }
                }

                //----------------------------------
                if ($itemNotApprove == true) {
                    $dTmp = $m->lookupDetailTransaksi($transaksiTopID)->result();

                    $notApprove = array();
                    foreach ($dTmp as $spec) {
                        if ((isset($spec->valid_qty_no_approve)) && ($spec->valid_qty_no_approve > 0)) {
                            $notApprove[$spec->produk_id] = $spec->valid_qty_no_approve;
                        }
                    }
                    $mainNotApprove = array();
                    $itemsNotApprove = array();
                    if (sizeof($notApprove) > 0) {
                        $itemsNotApprove = $items_reg;
                        foreach ($notApprove as $pid => $pqty_not_approve) {
                            $itemsNotApprove[$pid]['qty'] = $pqty_not_approve;
                            $itemsNotApprove[$pid]['jml'] = $pqty_not_approve;
                            $itemsNotApprove[$pid]['subtotal'] = $pqty_not_approve * $itemsNotApprove[$pid]['harga'];
                            if (sizeof($detailCore) > 0) {
                                foreach ($detailCore as $key_c => $val_c) {
                                    $itemsNotApprove[$pid]['sub_' . $key_c] = $pqty_not_approve * $itemsNotApprove[$pid][$key_c];
                                    if (!isset($mainNotApprove[$key_c])) {
                                        $mainNotApprove[$key_c] = 0;
                                    }
                                    $mainNotApprove[$key_c] += ($pqty_not_approve * $itemsNotApprove[$pid][$key_c]);
                                }
                            }
                            if (!isset($mainNotApprove['harga'])) {
                                $mainNotApprove['harga'] = 0;
                            }
                            $mainNotApprove['harga'] += ($pqty_not_approve * $itemsNotApprove[$pid]['harga']);
                        }
                    }
                }
            }

            //tambahan jika ada result item
            // arrPrint($main_reg);
            if (sizeof($rsltItems_reg) > 0) {
                //region reference detil
                $m->setFilters(array());
                $tmpRegRef = $m->lookupDataRegistriesByMasterID($main_reg['referenceID']);
                foreach ($tmpRegRef as $refRow) {
                    foreach ($regfields as $params) {
                        if (isset($refRow->$params)) {
                            $varR = $params . "_ref";
                            $$varR = unserialize(base64_decode($refRow->$params));
                        }
                    }
                }

                $tmpRowRslts_ref = array();
                $totalNilaiRef = 0;
                if (sizeof($rsltItems_ref) > 0) {
                    foreach ($rsltItems_ref as $rowRefID => $rowref_data) {
                        // $hpp = number_format($rowref_data['hpp'],0);
                        $hpp = $rowref_data['hpp'];
                        if (!isset($tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['qty'])) {
                            $tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['qty'] = 0;

                        }
                        if (!isset($tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['subtotal'])) {
                            $tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['subtotal'] = 0;
                        }

                        $tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['qty'] += $rowref_data['qty'];
                        $tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['subtotal'] += $rowref_data['sub_hpp'];
                        $tmpRowRslts_ref[$rowref_data['id']][$main_reg['pihakExternID']][$hpp]['harga'] = $rowref_data['hpp'];
                        $totalNilaiRef += $rowref_data['sub_hpp'];
                    }
                    $rowDetilRslt_label[$main_reg['pihakExternID']] = array(
                        "harga"    => "harga",
                        "qty"      => "qty",
                        "subtotal" => "subtotal",
                    );
                }
                //endregion

                //region current detil
                $tmpRowRslts = array();
                $tmpRowRsltsnilai = 0;
                foreach ($rsltItems_reg as $rowFifo => $fifoData) {
                    // $hpp_0 = number_format($fifoData['hpp'],0);
                    $hpp_0 = $fifoData['hpp'];
                    if (!isset($tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['qty'])) {
                        $tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['qty'] = 0;
                    }
                    if (!isset($tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['subtotal'])) {
                        $tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['subtotal'] = 0;
                    }
                    $tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['qty'] += $fifoData['qty'];
                    $tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['subtotal'] += $fifoData['sub_hpp'];
                    $tmpRowRslts_ref[$fifoData['id']][$main_reg['jenisTr']][$hpp_0]['harga'] = $fifoData['hpp'];
                    $tmpRowRsltsnilai += $fifoData['sub_hpp'];
                }
                $tmpRowRslts_label = array(
                    "nama"                     => "produk",
                    "qty"                      => "qty",
                    $main_reg['pihakExternID'] => $main_reg['pihakExternName'],
                    $main_reg['jenisTr']       => $main_reg['jenisTrName'],
                );
                $rowDetilRslt_label[$main_reg['jenisTr']] = array(
                    "harga"    => "harga",
                    "qty"      => "qty",
                    "subtotal" => "subtotal",
                );

                //endregion
            }
        }

        $transaksiJenisTopLabel = isset($main_reg['jenisTrName']) ? $main_reg['jenisTrName'] : "";
        //-------------------------------------
        if (($configNotes != NULL) && ($globalVars['trash_4'] == 1)) {
            foreach ($globalVars as $key => $val) {
                if (!is_array($val)) {
                    $configNotes = str_replace("{" . $key . "}", $val, $configNotes);
                }
            }
            $notes_final = $configNotes;
        }
        else {
            $notes_final = NULL;
        }
        //-------------------------------------
        //        cekKuning("$notes_final");
        $data = array(
            "mode"         => $this->uri->segment(3),
            "title"        => $no,
            "showScheme"   => $arrCons,
            "headerScheme" => $headerScheme,
            "headers"      => $headers,
            "main"         => isset($main) ? $main : array(),
            "items"        => $lItems,
            "receiptLink"  => $receiptLink,
            "signStr"      => $signStr,
            "cabangData"   => $arrCabang,

            "urutCounter"      => $urutCounters,
            "underMaintenance" => underConstruction(),

            // ===== ======
            "detail_title"     => "Pengajuan $transaksiJenisTopLabel",

            "itemLabels"  => isset($itemLabelsTop) ? $itemLabelsTop : array(),
            "item2Labels" => isset($item2LabelsTop) ? $item2LabelsTop : array(),
            "item3Labels" => isset($item3LabelsTop) ? $item3LabelsTop : array(),

            "detail_main"            => isset($main_reg) ? $main_reg : array(),
            "detail_items"           => isset($items_reg) ? $items_reg : array(),
            "detil_item_rslt"        => isset($tmpRowRslts_ref) ? $tmpRowRslts_ref : array(),
            // "detil_item_rslt_ref" => isset($tmpRowRslts_ref) ? $tmpRowRslts_ref : array(),
            "detil_item_rslt_label"  => isset($tmpRowRslts_label) ? $tmpRowRslts_label : array(),
            "detil_item_rslt_label2" => isset($rowDetilRslt_label) ? $rowDetilRslt_label : array(),
            "detail2_items"          => isset($items2_sum_reg) ? $items2_sum_reg : array(),
            "detail3_items"          => isset($items3_sum_reg) ? $items3_sum_reg : array(),

            "detail_sumRows"           => $sumRows,
            "detail2_sumRows"          => isset($sumRows2) ? $sumRows2 : array(),
            "detail3_sumRows"          => isset($sumRows3) ? $sumRows3 : array(),
            "noteEnabled"              => $noteEnabled,
            "addRows"                  => $addFildRowFields,
            //--------------------
            "mainNotApprove"           => isset($mainNotApprove) ? $mainNotApprove : array(),
            "itemsNotApprove"          => isset($itemsNotApprove) ? $itemsNotApprove : array(),
            "detail_not_approve_title" => "Pengajuan $transaksiJenisTopLabel (tidak diapprove)",
            //--------------------
            "notes_final"              => $notes_final,
        );
        $this->load->view("transaksi", $data);
    }

    public function viewResumeDetails()
    {

        $selectedID = $this->uri->segment(5);

        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("transaksi_data.trash='0'");
        $joinedTrans = $tr->lookupJoinedByID($selectedID)->result()[0];

        $jenisTr = $joinedTrans->jenis_master;
        $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
        $receiptElemets = isset($this->configUi[$jenisTr]["receiptElements"]) ? $this->configUi[$jenisTr]["receiptElements"] : array();
        $receiptDetailCompactListlabel = isset($this->configLayout[$jenisTr]["reviewDetailCompactListsLabel"]) ? $this->configLayout[$jenisTr]["reviewDetailCompactListsLabel"] : array();
        $receiptDetailCompactListlabel2 = isset($this->configLayout[$jenisTr]["reviewDetailCompactListsLabel2"]) ? $this->configLayout[$jenisTr]["reviewDetailCompactListsLabel2"] : array();
        $receiptCompactDetailsSum = isset($this->configLayout[$jenisTr]["reviewCompactListDetailSum"]) ? $this->configLayout[$jenisTr]["reviewCompactListDetailSum"] : array();
        $receiptCompactDetailsSum2 = isset($this->configLayout[$jenisTr]["reviewCompactListDetailSum2"]) ? $this->configLayout[$jenisTr]["reviewCompactListDetailSum2"] : array();
        $receiptMainLabel = isset($this->configLayout[$jenisTr]["reviewMainCompactListsLabel"]) ? $this->configLayout[$jenisTr]["reviewMainCompactListsLabel"] : array();
        $reviewCompactListSum = isset($this->configLayout[$jenisTr]["reviewCompactListSum"]) ? $this->configLayout[$jenisTr]["reviewCompactListSum"] : array();
        $reviewAddRows = isset($this->configLayout[$jenisTr]["reviewAddRows"]) ? $this->configLayout[$jenisTr]["reviewAddRows"] : array();
        $reviewSign = isset($this->configLayout[$jenisTr]["reviewSign"][$joinedTrans->step_number]) ? $this->configLayout[$jenisTr]["reviewSign"][$joinedTrans->step_number] : array();

        $d_start = backCustomDate(30, $joinedTrans->fulldate);
        $d_stop = $joinedTrans->fulldate;

        $tr->setFilters(array());
        $tr->addFilter("transaksi_id='$selectedID'");
        $tmpReg = $tr->lookupDataRegistries()->result();

        $mainElements = array();

        $mainData = array();
        $receiptDetailFields = array();
        $receiptSumFields = array();
        $masterItems = array();
        $masterItems2_sum = array();
        foreach ($tmpReg as $regData) {
            foreach ($regData as $key_reg => $val_reg) {
                switch ($key_reg) {
                    case "main":
                        $mainData = blobDecode($val_reg);
                        break;
                    case "items":
                        $masterItems_0 = blobDecode($val_reg);
                        foreach ($masterItems_0 as $pId => $masterItem) {
                            if (isset($masterItem['nett1']) && ($masterItem['nett1'] > 0)) {
                                $ppn_key = $masterItem['ppn'] / $masterItem['nett1'];
                            }
                            else {
                                $ppn_key = 0;
                            }
                            $addItem['harganppn'] = $masterItem['harga'] + ($masterItem['harga'] * $ppn_key);
                            $masterItems[$pId] = $masterItem + $addItem;
                        }
                        break;
                    case "items2_sum":
                        $masterItems2_sum = blobDecode($val_reg);
                        //                    foreach ($masterItems_0 as $pId => $masterItem) {
                        //                        $ppn_key = $masterItem['ppn'] / $masterItem['nett1'];
                        //                        $addItem['harganppn'] = $masterItem['harga'] + ($masterItem['harga'] * $ppn_key);
                        //                        $masterItems[$pId] = $masterItem + $addItem;
                        //                    }
                        break;
                    case "main_elements"://
                        $mainElements = blobDecode($val_reg);
                        break;
                    case "receiptDetailFields"://
                        $receiptDetailFields = blobDecode($val_reg);
                        break;
                    case "receiptSumFields"://
                        $receiptSumFields = blobDecode($val_reg);
                        break;
                }
            }

        }
        switch ($joinedTrans->produk_jenis) {
            case "produk":
                $link = base_url() . "Ledger/viewMoveDetails/RekeningPembantuProduk/persediaan produk/";
                break;
            case "supplies":
                $link = base_url() . "Ledger/viewMoveDetails/RekeningPembantuSupplies/persediaan supplies/";
                break;
            default:
                $link = NULL;
                break;
        }


        $sumQty = array();
        $arrItemsLink = array();
        if (sizeof($masterItems) > 0) {
            $qty_sum = 0;
            foreach ($masterItems as $data) {
                $qty_sum += $data["qty"];

                if ($link != NULL) {
                    $arrItemsLink[$data['id']] = $link . $data['id'] . "?o=" . $data['cabangID'] . "&trID=" . $joinedTrans->transaksi_id . "&date1=$d_start&date2=$d_stop";
                }
            }
            $sumQty["qty"] = $qty_sum;
        }
        $mainData = $mainData + $sumQty + (array)$joinedTrans;

        //region signatures
        $signNumbers = array();
        $signValues = array();
        $signExtValues = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($joinedTrans->id_master)->result();

        $signHeader = array();
        if (sizeof($tmpSign) > 0) {
            foreach ($tmpSign as $row) {
                $signValues['sign_' . $row->step_number] = array(
                    "label"              => isset($this->configUi[$joinedTrans->jenis_master]['steps'][$row->step_number]['stateCaption']) ? $this->configUi[$joinedTrans->jenis_master]['steps'][$row->step_number]['stateCaption'] : "",
                    "contents"           => isset($row->oleh_nama) ? $row->oleh_nama : "",
                    "caption_department" => isset($this->config->item("userGroup")[$row->group_code]) ? $this->config->item("userGroup")[$row->group_code] : "",
                );
            }
        }
        //endregion


        $data = array(
            "mode"                       => $this->uri->segment(3),
            "mainFields"                 => $mainData,
            "items"                      => $masterItems,
            "items2_sum"                 => $masterItems2_sum,
            "itemsLabel"                 => $receiptDetailCompactListlabel,
            "itemsLabel2"                => $receiptDetailCompactListlabel2,
            "mainSumDetailsFieldsLabel"  => $receiptCompactDetailsSum,
            "mainSumDetailsFieldsLabel2" => $receiptCompactDetailsSum2,
            "mainSumFieldsLabel"         => $reviewCompactListSum,
            "mainFieldsLabel"            => $receiptMainLabel,
            "mainElements"               => $mainElements,
            "receiptSumFields"           => $receiptSumFields,
            "reviewAddRows"              => $reviewAddRows,
            "sign"                       => $signValues,
            "reviewSign"                 => $reviewSign,

            "itemsLink"        => $arrItemsLink,
            "itemsKolomLink"   => array("nama", "produk_kode"),
            "underMaintenance" => underConstruction(),
        );

        $this->load->view("transaksi", $data);

    }

    public function swapFrom()
    {
        //        die("swapping................");
        $starttime = microtime(true);
        // arrPrint($this->uri->segment_array());
        // arrPrint($_POST);
        // matiHEre();
        $jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;

        $needToClear = false;
        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
            // $needToClear = true; // mati hanya buat ngecek normalnya script hidup
        }
        if ($needToClear) {
            die(lgShowAlert("untuk berganti ke transaksi lain, shoping cart harus dikosongkan terlebih dahulu"));
        }

        if (sizeof($_POST['trID']) > 0) {
            //            arrprint($_POST['trID']);
            $post_id = $_POST['trID'][0];
            $transaksies = explode("_", $post_id);
            // cekBiru($transaksies);
            /*-------data dari apk dari reguler------*/
            if (isset($transaksies[1])) {

                $apk_id = $transaksies[0];
                $reg_id[] = $apk_id * -1;

                /*--pembaca takein order dari apk ----*/
                $this->load->library('curl');
                $urlApi = $this->apiApk["order_request"] . my_toko_id();

                $preOrderRequest = json_decode($this->curl->simple_get($urlApi));
                $tmpReg = $src_preOrderRequest = $preOrderRequest->data;
                // arrPrint($src_preOrderRequest);
                // $tr_id_apk = str_replace("_apk", "", $tr_id);
                $oldMain = array();
                $spk_request_datas = array();
                foreach ($src_preOrderRequest as $item) {
                    $id = $item->id;
                    if ($apk_id == $id) {
                        // arrPrintHijau($item);
                        $produk = json_decode(base64_decode($item->produk));
                        // $produk = $item->produk;
                        // $oldMain["pihakID"] = $item->id_cust;
                        // $oldMain["pihakName"] = $item->nm_cust;
                        // $oldMain["apk_version"] = $item->apk_version;
                        // $oldMain["lattitude"] = $item->dev_Latitude;
                        // $oldMain["apk_trid"] = $item->id;

                        $pihakNama = $item->nm_cust;
                        $spk_request_datas[] = $item;
                    }
                }

                // arrPrintKuning($oldMain);
                // arrPrintKuning($spk_request_datas);
                // matiHere(__LINE__);
                // arrPrintKuning($produk);

                //---item
                $items = array();
                $trIDs = array();
                $lastTRID = 0;
                $trRegistry = "";
                foreach ($produk as $row) {
                    // arrPrintPink(__LINE__);
                    // arrPrintPink($row);
                    if (!array_key_exists($row->produk_id, $items)) {
                        $items[$row->produk_id] = 0;
                    }
                    $items[$row->produk_id] += $row->produk_qty;
                    if (isset($row->id_master) && !in_array($row->id_master, $trIDs)) {
                        $trIDs[] = $row->id_master;
                    }
                    $lastTRID = $apk_id;
                    // $trRegistry = $row->indexing_registry;
                    // $trRegistry_decode = blobDecode($trRegistry);
                    // $trRegistry_decode_main = $trRegistry_decode['main'];
                }
                //---item

                $swappedKeys = isset($this->configUi[$jenisTr]['swappedKeys']) ? $this->configUi[$jenisTr]['swappedKeys'] : array();
                $swappedKeys["apk_version"] = "apk_version";
                $swappedKeys["apk_trid"] = "apk_trid";
                // arrPrintPink($swappedKeys);
                // arrPrintPink($oldMain);
                $allowMultiSelect = isset($this->configUi[$jenisTr]['requestCode']['allowMultiSelect']) ? $this->configUi[$jenisTr]['requestCode']['allowMultiSelect'] : false;
                // if (sizeof($tmpReg) > 0 && sizeof($swappedKeys) > 0) {
                //     // $oldMain = blobDecode($tmpReg[0]->main);
                //     foreach ($swappedKeys as $kr) {
                //         $_SESSION[$cCode]['main'][$kr] = $oldMain[$kr];
                //         echo "<script>";
                //         echo "if(top.document.getElementById('$kr')){top.document.getElementById('$kr').value='" . $oldMain[$kr] . "'}";
                //         echo "</script>";
                //     }
                // }

                $this->load->library("Selector");
                $tr = new Selector();

                $tr->setTransaksiId($apk_id);
                $tr->setTokoId(my_toko_id());
                $tr->setConfigValuesModul($this->configValues);
                $tr->setConfigCoreModul($this->configCore);
                $tr->setconfigUiModul($this->configUi);
                $tr->setJenisTr($jenisTr);
                $tr->setDataExt($spk_request_datas);
                $dd = $tr->multiSelect();

                // arrPrintPink($post_id);
                // matiHere($post_id);
                /* --------------------------------------------------------
                 * melarikan ke executor bila blom ada di tempatnya
                 * --------------------------------------------------------*/
                $http_referer = $_SERVER['HTTP_REFERER'];
                $modul_ini = url_segment(1);
                // arrPrintPink(uri_string($http_referer));
                $expl_url = explode('/', $http_referer);
                $controler_ky = array_flip($expl_url)[$modul_ini] + 1;
                $referer_controler = $expl_url[$controler_ky];
                if ($referer_controler != "Create") {
                    $url_tujuan = str_replace($referer_controler, "Create", $http_referer);

                    echo "<script>top.location.href='$url_tujuan';</script>";
                }
                // matiHere(__LINE__);
                /* --------------------------------------------------------
                 * goto shopingCart
                 * --------------------------------------------------------*/
                echo "<script>";
                echo "  top.$('#shopping_cart').load('" . base_url() . $this->modul . "/_shoppingCart/viewCart/" . $this->jenisTr . "?selID=$id');";
                echo "top.$('#pihakName').val('$pihakNama');";
                // echo "top.$('.order_request').attr('disabled',true);";
                echo "top.$('#$post_id').css('background-color','yellow');";
                echo "top.$('#btn_clear_create').css('display','block');";
                echo "top.$('#btnProcess').attr('disabled',false);";

                echo "</script>";

                die();

                $targetProc = base_url() . $this->modul . "/" . $this->configUi[$jenisTr]['itemSwapper'] . "/$jenisTr/?items=" . base64_encode(serialize($items)) . "&main=" . base64_encode(serialize($oldMain)) . "&trs=" . base64_encode(serialize($trIDs));
                $targetSuffix = $allowMultiSelect == true ? "" : "&singleRefID=$lastTRID";
                $targetProc .= $targetSuffix;
                matiHere($targetProc);
                // echo "<script>";
                // echo "top.document.getElementById('result').src='$targetProc';";
                // echo "</script>";
            }
            else {
                $reg_id = $transaksies;
                $this->load->model("MdlTransaksi");
                $tr = new MdlTransaksi();
                $tr->addFilter("transaksi_id in (" . implode(",", $reg_id) . ")");
                $tmpTr = $tr->lookupJoined()->result();
                cekKuning($this->db->last_query());
                if (sizeof($tmpTr) > 0) {
                    $items = array();
                    $trIDs = array();
                    $lastTRID = 0;
                    $trRegistry = "";
                    foreach ($tmpTr as $row) {
                        if (!array_key_exists($row->produk_id, $items)) {
                            $items[$row->produk_id] = 0;
                        }
                        $items[$row->produk_id] += $row->produk_ord_jml;
                        if (!in_array($row->id_master, $trIDs)) {
                            $trIDs[] = $row->id_master;
                        }
                        $lastTRID = $row->transaksi_id;
                        $trRegistry = $row->indexing_registry;
                        $trRegistry_decode = blobDecode($trRegistry);
                        $trRegistry_decode_main = $trRegistry_decode['main'];
                    }

                    //                cekHijau($trRegistry);
                    //==ambil value-gate
                    $trr = new MdlTransaksi();
                    $trr->setFilters(array());

                    //                 arrPrintWebs($trRegistry_decode_main);
                    // matiHere();
                    $trr->addFilter("transaksi_id in (" . implode(",", $_POST['trID']) . ")");
                    // $trr->addFilter("id=$trRegistry_decode_main");
                    //                $trr->addFilter("transaksi_id in (" . implode(",", $_POST['trID']) . ")");
                    //                $trr->addFilter("param='main'");


                    $tmpReg = $trr->lookupDataRegistries()->result();
                    // arrPrint($tmpReg);
                    // cekMErah($this->db->last_query());
                    $endtime = microtime(true); // Bottom of page

                    // matiHere("sini lama gak? starttime:$starttime,  endTime: $endtime");

                    $swappedKeys = isset($this->configUi[$jenisTr]['swappedKeys']) ? $this->configUi[$jenisTr]['swappedKeys'] : array();
                    $allowMultiSelect = isset($this->configUi[$jenisTr]['requestCode']['allowMultiSelect']) ? $this->configUi[$jenisTr]['requestCode']['allowMultiSelect'] : false;
                    $oldMain = blobDecode($tmpReg[0]->main);
                    // if (sizeof($tmpReg) > 0 && sizeof($swappedKeys) > 0) {
                    //     foreach ($swappedKeys as $kr) {
                    //         $_SESSION[$cCode]['main'][$kr] = $oldMain[$kr];
                    //         echo "<script>";
                    //         echo "if(top.document.getElementById('$kr')){top.document.getElementById('$kr').value='" . $oldMain[$kr] . "'}";
                    //         echo "</script>";
                    //     }
                    // }

                    // matiHEre();
                    //                die();
                    $targetProc = base_url() . $this->modul . "/" . $this->configUi[$jenisTr]['itemSwapper'] . "/$jenisTr/?items=" . base64_encode(serialize($items)) . "&main=" . base64_encode(serialize($oldMain)) . "&trs=" . base64_encode(serialize($trIDs));
                    $targetSuffix = $allowMultiSelect == true ? "" : "&singleRefID=$lastTRID";
                    $targetProc .= $targetSuffix;
                    // matiHere($targetProc);
                    // echo "<script>";
                    // echo "top.document.getElementById('result').src='$targetProc';";
                    // echo "</script>";
                }
                else {
                    cekAlert("data tidak ditemukan untuk transaksi reguler");
                }
            }

            // cekMerah($targetProc);
            // matiHere(__LINE__);
            /*----pembentuk session main pihak----*/
            if (sizeof($tmpReg) > 0 && sizeof($swappedKeys) > 0) {
                foreach ($swappedKeys as $kr) {
                    $_SESSION[$cCode]['main'][$kr] = $oldMain[$kr];
                    echo "<script>";
                    echo "if(top.document.getElementById('$kr')){top.document.getElementById('$kr').value='" . $oldMain[$kr] . "'}";
                    echo "</script>";
                }
            }
            //            mati_disini($targetProc);
            /*----pembentuk session main dan item----*/
            echo "<script>";
            echo "top.document.getElementById('result').src='$targetProc';";
            echo "</script>";

        }
        else {
            echo(lgShowAlert("please select at least one item"));
            echo "<script>";
            echo "top.fillBoxes();";
            //            echo "top.document.getElementById('btnConnect').disabled=false;";
            //            echo "top.document.getElementById('btnConnect').innerHTML='<span class=\'fa fa-external-link\'></span> followup selected entry';";
            echo "</script>";
            die();
        }


        $no = $this->uri->segment(3);
        $cCode = "_TR_" . $this->jenisTr;


    }

}
