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

class History 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";

    }

    public function index()
    {
    }

    public function viewHistory()
    {
        // cekBiru(url_segment());

        if (!isset($this->session->login['id'])) {
            gotoLogin();
        }
        // cekBiru(ipadd());

        $limit = 10000;
        // if (ipadd() == '202.65.117.72') {
        //     $limit = 10;
        // }

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

        $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");
        $menu_gr = isset($_GET['gr']) ? $_GET['gr'] : "";
        $menu_md = isset($_GET['md']) ? $_GET['md'] : "";

        if (isset($_GET['gr'])) {
            $str_menu = "&gr=$menu_gr";
            if (isset($_GET['md'])) {
                $str_menu .= "&md=$menu_md";
            }
        }
        else {
            $str_menu = "";
        }
        // cekBiru(url_segment());
        // arrPrint(MODUL_URL);
        // arrPrintWebs(base_url(url_segment()));
        $myUrl = MODUL_URL . "/" . $this->jenisTr;
        //region preparing ERP step labels for top link
        $steps = $this->configUi[$jenisTr]['steps'];
        $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] = $myUrl . "/" . $stepSpec['target'] . "?date1=$date1&date2=$date2" . $str_menu;
                }
            }
            // arrPrintPink($stepLinks);
            if (isset($_GET['stID'])) {
                $currentState = $_GET['stID'];
            }
            else {
                $currentState = strlen($this->uri->segment(5)) > 0 ? $this->uri->segment(5) : $this->configUi[$jenisTr]['steps'][1]['target'];
            }
        }
        //endregion
        // matiDisini(__LINE__);
        //region lookup histories
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
        // $tr->addFilter("toko_id='" . $this->placeId . "'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        // $tr->addFilter("div_id='" . $this->session->login['div_id'] . "'");
        $searchStr = isset($_GET['search']) ? $_GET['search'] : "";

        //region date filter
        // $this->db->where("fulldate>='" . $date1 . "'");
        // $this->db->where("fulldate<='" . $date2 . "'");
        //endregion

        if (isset($currentState)) {
            $tr->addFilter("jenis='" . $currentState . "'");
        }

        $addParams = array();
        if (isset($_GET['addParams'])) {
            $addParams = unserialize(base64_decode($_GET['addParams']));
        }
        if ($addParams != null && sizeof($addParams) > 0) {
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        //        $action = array(
        //            "viewDetails" => base_url() . get_class($this) . "/viewDetails",
        //        );

        if (isset($_GET['search'])) {
            $tr->setKeyWord($searchStr);
        }
        else {
            $this->db->where("fulldate>='" . $date1 . "'");
            $this->db->where("fulldate<='" . $date2 . "'");
        }

        $jmlData = $tr->lookupDataCount();
        $page = (isset($_GET['page']) && $_GET['page'] > 0) ? ($_GET['page']) : 1;
        $offset = ($limit * ($page - 1));

        $addParams = array();
        if (isset($_GET['addParams'])) {
            $addParams = unserialize(base64_decode($_GET['addParams']));
        }
        if ($addParams != null && sizeof($addParams) > 0) {
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        $action = array(
            "viewDetails" => base_url() . get_class($this) . "/viewDetails",
        );

        if (isset($_GET['search'])) {
            $tr->setKeyWord($searchStr);
        }
        else {
            $this->db->where("fulldate>='" . $date1 . "'");
            $this->db->where("fulldate<='" . $date2 . "'");
        }
        $tmpHist = $tr->lookupHistories($jmlData, $limit, $page)->result();
        // showLast_query("biru");
        // cekBiru(sizeof($tmpHist));
        // arrPrint($tmpHist);
        $arrCurrency = array();
        if (sizeof($printValas) > 0) {
            $trv = new MdlCurrency();
            $tmpCurrency = $trv->lookupAll()->result();
            if (sizeof($tmpCurrency) > 0) {
                foreach ($tmpCurrency as $key => $value) {
                    $arrCurrency[$key] = $value;
                }
            }
        }

        $cabang_id = $this->placeId;

        $arrayHistory = array();
        $arrayHistory_ids = array();
        $arrayHistory_canceled = array();
        $sumValue = array();
        if (sizeof($tmpHist) > 0) {

            if (sizeof($pairRegistries) > 0) {
                $arrSalesName = array();
                $arrTransID = array();
                $arrTransTopID = array();
                $arrIndexID = array();
                $arrIdsHist = array();
                $arrTransHist = array();
                $arrTransMainHist = array();
                foreach ($tmpHist as $row) {
                    $arrTransID[] = $row->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'];
                        }
                    }

                    if (($row->indexing_registry)) {
                        $indexing_registry = blobDecode($row->indexing_registry);
                        // cekPink($indexing_registry['main']);
                        $indexMainRegistries[$row->id] = $indexing_registry['main'];
                    }
                }

                $tmpReg_result = array();
                $trReg = new MdlTransaksi();
                // $trReg->setFilters(array());
                // $trReg->addFilter("param='main'");
                // $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
                // $trReg->addFilter("id in ('" . implode("','", $indexMainRegistries) . "')");

                // $tmpReg = $trReg->lookupRegistries()->result();
                // showLast_query("lime");
                // arrPrint($tmpReg);

                $fieldDataRegistries = $trReg->getFields();
                $fDataRegistries = $fieldDataRegistries['dataRegistry'];
                $fieldBlock = array(
                    "transaksi_id",
                );
                $paramRegistries = array_diff($fDataRegistries, $fieldBlock);
                $tmpReg = $trReg->lookupBaseDataRegistries($arrTransID)->result();
                // cekHere($this->db->last_query());
                // arrPrint($tmpReg);
//arrPrintPink($paramRegistries);
                // matiDisini(__LINE__);
                if (sizeof($tmpReg) > 0) {
                    // foreach ($tmpReg as $regRow) {
                    //     $param = $regRow->param;
                    //     $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
                    // }
                    foreach ($tmpReg as $regRow) {
                        // $param = $regRow->param;
//                        arrPrint($regRow);
                        foreach ($paramRegistries as $param) {
                            $regValue = blobDecode($regRow->$param);
                            $regParams[$param] = $regValue;
                            $tmpReg_result[$regRow->transaksi_id] = array_filter($regParams);
                        }
                    }
                }
                // arrPrint($tmpReg_result);
                // if (ipadd() == '202.65.117.72') {
                //     mati_disini(__LINE__);
                // }

                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("id in ('" . implode("','", $arrTransTopID) . "')");
                $tmpTrTop = $tr->lookupAll()->result();
                if (sizeof($tmpTrTop) > 0) {
                    foreach ($tmpTrTop as $topSpec) {
                        $arrSalesName[$topSpec->id_top] = $topSpec->oleh_nama;
                    }
                }

                //arrPrint($arrTransHist);
                //mati_disini();
                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,
                            );
                        }
                    }
                    //                    mati_disini();
                    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;
                        }
                    }
                }

            }
            //arrPrint($arrTransMainHist);
//            arrPrint($tmpReg_result);
            //            mati_disini("::: ");
            $numb = 0;
            foreach ($tmpHist as $ii => $row) {
                // region ids_his
                $id_hist = blobDecode($row->ids_his);
                // endregion ids_his

                //region memangil global counter
                $tNomer_top = $row->nomer_top;
                //                $tr = new MdlTransaksi();
                //                $tr->addFilter("param='main'");
                //                $tmpReg = $tr->lookupRegistriesByNumber($tNomer_top)->result();
                //
                //                $arrSalesName = "";
                //                foreach ($tmpReg as $tmpRowReg) {
                //                    $arrSalesName = $tmpRowReg->oleh_nama;
                //                }
                $salesName = isset($arrSalesName[$row->id_top]) ? $arrSalesName[$row->id_top] : "-";


                $tNomer = $row->nomer;
                $jenisTrtop = explode(".", $tNomer_top)[0];
                $jenisTrsub = explode(".", $tNomer)[0];
                $counterjenis = "$jenisTrsub|" . $this->placeId;
                // cekHere($tNomer_top);
                $arrIdHist = blobDecode($row->ids_his);
                $arrCounters = isset($arrIdHist[1]['counters']) ? blobDecode($arrIdHist[1]['counters']) : "";

                $counterIds_his = is_array($arrCounters) ? blobDecode(blobDecode($row->ids_his)[1]['counters']) : "";
                $counters = blobDecode($row->counters);
                $counterGlobal = $counters['stepCode|placeID'][$counterjenis];


                $counterIds_his_global = isset($counterIds_his['stepCode|placeID']["$jenisTrtop|$cabang_id"]) ? $counterIds_his['stepCode|placeID']["$jenisTrtop|$cabang_id"] : "";
                $cGlobals = digit_5($counterGlobal);
                $cGlobal_spo = digit_5($counterIds_his_global);

                //endregion

                if (sizeof($pairRegistries) > 0) {
                    //                    $trReg = new MdlTransaksi();
                    //                    $trReg->setFilters(array());
                    //                    $trReg->addFilter("param in ('" . implode("','", $pairRegistries) . "')");
                    //                    $trReg->addFilter("transaksi_id='" . $row->id . "'");
                    //                    $tmpReg = $trReg->lookupRegistries()->result();
                    ////                    cekBiru($this->db->last_query());
                    //                    if (sizeof($tmpReg) > 0) {
                    //                        foreach ($tmpReg as $regRow) {
                    //                            $param = $regRow->param;
                    //                            // arrPrint(blobDecode($regRow->values));
                    //                            $$param = blobDecode($regRow->values);
                    //                        }
                    //                        foreach ($pairRegistries as $eReg) {
                    //                            foreach ($$eReg as $k => $v) {
                    //                                if (!isset($row->$k)) {
                    //                                    $row->$k = $v;
                    //                                }
                    //                            }
                    //                        }
                    //                    }

                    if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->id]['main']))) {
//                        arrPrint($tmpReg_result[$row->id]['main']);
//                        foreach ($tmpReg_result[$row->id]['main'] as $param => $eReg) {
                        foreach ($tmpReg_result[$row->id]['main'] as $k => $v) {
//                            foreach ($eReg as $k => $v) {
                            if (!isset($row->$k)) {
                                if (!empty($k)) {
                                    $row->$k = $v;
                                }
                            }
//                            }
                        }
                    }
                    //                        cekHijau(":: SRN $row->referenceID ::");
                    //                        cekHijau(":: SRN $row->referenceNomer ::");
                    if (sizeof($pairTransaksi) > 0) {
                        if ($row->referenceID > 0) {
                            $trPair = new MdlTransaksi();
                            $trPair->addFilter("id='" . $row->referenceID . "'");
                            $trPairTmp = $trPair->lookupMainTransaksi()->result();
                            if (sizeof($trPairTmp) > 0) {
                                $hisTr = isset($trPairTmp[0]->ids_his) ? blobDecode($trPairTmp[0]->ids_his) : array();
                                foreach ($hisTr as $step => $hisTrSpec) {
                                    foreach ($pairTransaksi['kolom'] as $keyPair => $labelPair) {
                                        $keyPairs = $keyPair . "_" . $step;
                                        $row->$keyPairs = isset($hisTrSpec[$labelPair]) ? $hisTrSpec[$labelPair] : "--";
                                    }
                                }
                            }
                        }
                    }
                }


                if (sizeof($historyFieldsExt) > 0) {
                    foreach ($historyFieldsExt as $alias => $colom) {
                        $row->$alias = $row->$colom;
                    }
                }
                $tmp = array();
                $tmp1 = array();

                $numb++;
                foreach ($historyFields as $fName => $fLabel) {

                    if (strpos($fName, '+') !== false) {//==mengandung penggabungan (+)
                        $chars = explode("+", $fName);
                        $colValue = "";
                        foreach ($chars as $key) {
                            if (is_numeric($row->$key)) {
                                if (!isset($sumValue[$key])) {
                                    $sumValue[$key] = 0;
                                }
                                $sumValue[$key] += $row->$key;
                            }
                            $colValue .= isset($row->$key) ? formatField_he_format($key, $row->$key) . "<br>" : "";
                        }
                        $colValue = rtrim($colValue, "<br>");
                    }
                    else {

                        if (is_numeric(isset($row->$fName) ? $row->$fName : "")) {
                            if (!isset($sumValue[$fName])) {
                                $sumValue[$fName] = 0;
                            }
                            $sumValue[$fName] += $row->$fName;
                        }

                        //region nomer dengan global counter
                        if ($fName == "nomer") {
                            // switch ($jenisTr) {
                            switch ($jenisTrsub) {
                                case "582s":
                                    $kolomValues = $row->$fName . "&#x2011;$cGlobals";
                                    break;
                                // case "582spd":
                                default:
                                    $kolomValue_0s = formatField_he_format($fName, $row->$fName);
                                    $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobals, $kolomValue_0s);
                                    break;
                            }
                        }
                        elseif ($fName == "nomer_top") {
                            $kolomValue_0s = formatField_he_format($fName, $row->$fName);
                            $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobal_spo, $kolomValue_0s);
                        }
                        else {
                            $kolomValues = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : "-";
                        }
                        //endregion

                        if ($fName == "print_label") {

                            $link_barcode_print = base_url() . "Printing/barcodeTransaksi/" . $row->id;
                            // $kolomValues .= " &nbsp;&nbsp;<a href='$link_barcode_print' class='btn btn-info btn-xs' target='_blank' title='print barcode'><i class='fa fa-print'> barcode</i></a>";
                        }

                        // $colValue = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : "";
                        $colValue = isset($row->$fName) ? $kolomValues : "";
                    }

                    if ($fName == "ids_his") {
                        if (is_array($fLabel)) {

                            $hisStep = $fLabel['step'];
                            $hisKey = $fLabel['key'];
                            $tNomer = $id_hist[$hisStep][$hisKey];


                            $colValue = isset($row->ids_his) ? showHistoriGlobalNumbers($row->ids_his, $hisStep, true) : "";

                            //                            $tr = new MdlTransaksi();
                            //                            $tr->setFilters(array());
                            //                            $tr->addFilter("param='main'");
                            //                            $tmpReg = $tr->lookupRegistriesByNumber($tNomer)->result();
                            ////                            cekHere($this->db->last_query());
                            //
                            //                            $logistic = $tmpReg[0]->oleh_nama;
                            $logistic = "";
                            if (isset($arrTransMainHist[$row->id][$hisStep]['main'])) {
                                $main = $arrTransMainHist[$row->id][$hisStep]['main'];
                                $logistic = $main['oleh_nama'];
                            }
                        }
                    }

                    if ($fName == "no") {
                        $colValue = formatField_he_format($fName, $numb);
                    }

                    //                    cekHere($logistic);
                    $tmp['logistic'] = isset($logistic) && $logistic != null ? $logistic : 'undefined';
                    $tmp['sales_name'] = $salesName;
                    $tmp[$fName] = $colValue;
                    $tmp1["id"] = $row->id;
                }


                if (sizeof($arrCurrency) > 0) {
                    $valas = "";
                    $valas .= "<div class='btn-group'>";
                    $valas .= "<button type='button' class='btn btn-primary dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
                    $valas .= "<i class='fa fa-print'></i>";
                    $valas .= "<span class='caret'></span>";
                    $valas .= "</button>";

                    $valas .= "<ul style='background:#cde8ff;' class='dropdown-menu dropdown-menu-right'>";
                    foreach ($arrCurrency as $arrV) {
                        $nama = $arrV->nama;
                        $nomer = $row->nomer;
                        $nilai = number_format($arrV->exchange, 0);
                        $valas .= " <li class='text-bold'><a class='dropdown-item' href='javascript:void(0);' onclick=\"top.popBig('" . base_url() . "Transaksi/viewReceipt/$nomer?type=" . blobEncode($nama) . "&f=" . blobEncode($arrV->exchange) . "')\"> <i class='fa fa-print'></i> in $nama - ($nilai) </a></li>";
                    }

                    $valas .= " <li><a class='btn btn-xs btn-warning' href='javascript:void(0);' onclick=\"top.location.href='" . base_url() . "data/view/Currency'\"> <i class='fa fa-plus'></i> tambah currency </a></li>";
                    $valas .= "</ul>";
                    $valas .= "</div>";
                    $tmp["print_nvalas"] = $valas;
                }

                $tmp['next_pic'] = "-";

                // menambah background-color karena dicancel/reject/undo, atau yang dibatalkan
                $tmp['keterangan'] = "-";
                if (isset($row->trash_4) && ($row->trash_4 == 1)) {
                    $tmp['keterangan'] = "CANCELED";
                    $arrayHistory_canceled[$ii] = array(
                        "bgcolor" => "background-color:#FA8072;",
                    );
                }

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


            }
        }
        //endregion


        //region link to add new transaction
        if (placeCanMakeTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr)) {
            //        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 = base_url() . $createIndexes[$this->jenisTr] . "/" . $this->jenisTr;
            }
            else {
                $targetUrl = base_url() . "Transaksi/createForm/" . $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
        // arrPrint($arrayHistory);
        // cekHere(MODUL_TEMPLATE_PATH);
        //region prepare params for viewer
        $data = array(
            "mode" => "viewHistory",
            //            "mode" => "viewHistory",
            "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,
            "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" => base_url() . $this->modul . "/" . $this->uri->segment(2) . "/viewIncomplete/" . $this->uri->segment(4),
            "alternateLinkCaption" => "incomplete " . $this->configUi[$jenisTr]["label"] . " <span class='glyphicon glyphicon-arrow-right'></span>",
            "addLink" => $addLink,
            "filters" => array(
                "dates" => $this->dates,
                "date1" => $date1,
                "date2" => $date2,
            ),
            "thisPage" => MODUL_URL . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5),

            "history_canceled" => isset($arrayHistory_canceled) ? $arrayHistory_canceled : array(),
        );
        //endregion


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

    public function showData_old()
    {
        if (!isset($this->session->login['id'])) {
            gotoLogin();
        }
        // cekBiru(ipadd());
        // cekBiru(url_segment());
        // cekBiru($_GET);

        $limit = isset($_GET['limit']) ? $_GET['limit'] : 1000;
        $str_limit = "&limit=$limit";
        // if (ipadd() == '202.65.117.72') {
        //     $limit = 10;
        // }

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

        // arrPrintPink($historyFields);
        $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");
        $menu_gr = isset($_GET['gr']) ? $_GET['gr'] : "";
        $menu_md = isset($_GET['md']) ? $_GET['md'] : "";

        if (isset($_GET['gr'])) {
            $str_menu = "&gr=$menu_gr";
            if (isset($_GET['md'])) {
                $str_menu .= "&md=$menu_md";
            }
        }
        else {
            $str_menu = "";
        }
        // cekBiru(url_segment());
        // arrPrint(MODUL_URL);
        // arrPrintWebs(base_url(url_segment()));
        $myUrl = MODUL_URL . "/" . $this->jenisTr;
        //region preparing ERP step labels for top link
        $steps = $this->configUi[$jenisTr]['steps'];
        $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] = $myUrl . "/" . $stepSpec['target'] . "?date1=$date1&date2=$date2" . $str_menu . $str_limit;
                }
            }
            // arrPrintPink($stepLinks);
            if (isset($_GET['stID'])) {
                $currentState = $_GET['stID'];
            }
            else {
                $currentState = strlen($this->uri->segment(5)) > 0 ? $this->uri->segment(5) : $this->configUi[$jenisTr]['steps'][1]['target'];
            }
        }
        //endregion
        // matiDisini(__LINE__);
        //region lookup histories
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->addFilter("id='210'");
        // $tr->addFilter("div_id='" . $this->session->login['div_id'] . "'");
        $searchStr = isset($_GET['search']) ? $_GET['search'] : "";

        //region date filter
        // $this->db->where("fulldate>='" . $date1 . "'");
        // $this->db->where("fulldate<='" . $date2 . "'");
        //endregion

        if (isset($currentState)) {
            $tr->addFilter("jenis='" . $currentState . "'");
        }

        $addParams = array();
        if (isset($_GET['addParams'])) {
            $addParams = unserialize(base64_decode($_GET['addParams']));
        }
        if ($addParams != null && sizeof($addParams) > 0) {
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        //        $action = array(
        //            "viewDetails" => base_url() . get_class($this) . "/viewDetails",
        //        );

        if (isset($_GET['search'])) {
            $tr->setKeyWord($searchStr);
        }
        else {
            $this->db->where("fulldate>='" . $date1 . "'");
            $this->db->where("fulldate<='" . $date2 . "'");
        }

        $jmlData = $tr->lookupDataCount();
        $page = (isset($_GET['page']) && $_GET['page'] > 0) ? ($_GET['page']) : 1;
        $offset = ($limit * ($page - 1));

        $addParams = array();
        if (isset($_GET['addParams'])) {
            $addParams = unserialize(base64_decode($_GET['addParams']));
        }
        if ($addParams != null && sizeof($addParams) > 0) {
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        $action = array(
            "viewDetails" => base_url() . get_class($this) . "/viewDetails",
        );

        if (isset($_GET['search'])) {
            $tr->setKeyWord($searchStr);
        }
        else {
            $this->db->where("fulldate>='" . $date1 . "'");
            $this->db->where("fulldate<='" . $date2 . "'");
        }
        $tmpHist = $tr->lookupHistories($jmlData, $limit, $page)->result();
        showLast_query("biru");
        // cekBiru(sizeof($tmpHist));
        // arrPrint($tmpHist);
        $arrCurrency = array();
        if (sizeof($printValas) > 0) {
            $trv = new MdlCurrency();
            $tmpCurrency = $trv->lookupAll()->result();
            if (sizeof($tmpCurrency) > 0) {
                foreach ($tmpCurrency as $key => $value) {
                    $arrCurrency[$key] = $value;
                }
            }
        }

        $cabang_id = $this->placeId;

        $arrayHistory = array();
        $arrayHistory_ids = array();
        $arrayHistory_canceled = array();
        $sumValue = array();
        if (sizeof($tmpHist) > 0) {

            if (sizeof($pairRegistries) > 0) {
                $arrSalesName = array();
                $arrTransID = array();
                $arrTransTopID = array();
                $arrIndexID = array();
                $arrIdsHist = array();
                $arrTransHist = array();
                $arrTransMainHist = array();
                foreach ($tmpHist as $row) {
                    $arrTransID[] = $row->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'];
                        }
                    }

                    if (($row->indexing_registry)) {
                        $indexing_registry = blobDecode($row->indexing_registry);
                        // cekPink($indexing_registry['main']);
                        $indexMainRegistries[$row->id] = $indexing_registry['main'];
                    }
                }

                $tmpReg_result = array();
                $trReg = new MdlTransaksi();
                // $trReg->setFilters(array());
                // $trReg->addFilter("param='main'");
                // $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
                // $trReg->addFilter("id in ('" . implode("','", $indexMainRegistries) . "')");

                // $tmpReg = $trReg->lookupRegistries()->result();
                // showLast_query("lime");
                // arrPrint($tmpReg);

                $fieldDataRegistries = $trReg->getFields();
                $fDataRegistries = $fieldDataRegistries['dataRegistry'];
                $fieldBlock = array(
                    "transaksi_id",
                );
                $paramRegistries = array_diff($fDataRegistries, $fieldBlock);
                $tmpReg = $trReg->lookupBaseDataRegistries($arrTransID)->result();
                // cekHere($this->db->last_query());
                // arrPrint($tmpReg);

                // matiDisini(__LINE__);
                if (sizeof($tmpReg) > 0) {
                    // foreach ($tmpReg as $regRow) {
                    //     $param = $regRow->param;
                    //     $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
                    // }
                    foreach ($tmpReg as $regRow) {
                        // $param = $regRow->param;
                        foreach ($pairRegistries as $reqParamKey) {
                            $regParams[$reqParamKey] = blobDecode($regRow->$reqParamKey);

                            $tmpReg_result[$regRow->transaksi_id] = array_filter($regParams);
                        }
                        // foreach ($paramRegistries as $param) {
                        //     $regValue = blobDecode($regRow->$param);
                        //     $regParams[$param] = $regValue;
                        //     $tmpReg_result[$regRow->transaksi_id] = array_filter($regParams);
                        // }
                    }
                }
                // arrPrint($tmpReg_result);
                // if (ipadd() == '202.65.117.72') {
                //     mati_disini(__LINE__);
                // }

                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("id in ('" . implode("','", $arrTransTopID) . "')");
                $tmpTrTop = $tr->lookupAll()->result();
                if (sizeof($tmpTrTop) > 0) {
                    foreach ($tmpTrTop as $topSpec) {
                        $arrSalesName[$topSpec->id_top] = $topSpec->oleh_nama;
                    }
                }

                //arrPrint($arrTransHist);
                //mati_disini();
                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,
                            );
                        }
                    }
                    //                    mati_disini();
                    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;
                        }
                    }
                }

            }
            // arrPrint($tmpHist);
            //            mati_disini("::: ");
            $numb = 0;
            foreach ($tmpHist as $ii => $row) {
                // region ids_his
                $id_hist = blobDecode($row->ids_his);
                // endregion ids_his

                //region memangil global counter
                $tNomer_top = $row->nomer_top;
                //                $tr = new MdlTransaksi();
                //                $tr->addFilter("param='main'");
                //                $tmpReg = $tr->lookupRegistriesByNumber($tNomer_top)->result();
                //
                //                $arrSalesName = "";
                //                foreach ($tmpReg as $tmpRowReg) {
                //                    $arrSalesName = $tmpRowReg->oleh_nama;
                //                }
                $salesName = isset($arrSalesName[$row->id_top]) ? $arrSalesName[$row->id_top] : "-";


                $tNomer = $row->nomer;
                $jenisTrtop = explode(".", $tNomer_top)[0];
                $jenisTrsub = explode(".", $tNomer)[0];
                $counterjenis = "$jenisTrsub|" . $this->placeId;
                // cekHere($tNomer_top);
                $arrIdHist = blobDecode($row->ids_his);
                $arrCounters = isset($arrIdHist[1]['counters']) ? blobDecode($arrIdHist[1]['counters']) : "";

                $counterIds_his = is_array($arrCounters) ? blobDecode(blobDecode($row->ids_his)[1]['counters']) : "";
                $counters = blobDecode($row->counters);
                $counterGlobal = $counters['stepCode|placeID'][$counterjenis];


                $counterIds_his_global = isset($counterIds_his['stepCode|placeID']["$jenisTrtop|$cabang_id"]) ? $counterIds_his['stepCode|placeID']["$jenisTrtop|$cabang_id"] : "";
                $cGlobals = digit_5($counterGlobal);
                $cGlobal_spo = digit_5($counterIds_his_global);

                //endregion
// arrPrint($tmpReg_result);
// matiHEre();
                if (sizeof($pairRegistries) > 0) {
                    //                    $trReg = new MdlTransaksi();
                    //                    $trReg->setFilters(array());
                    //                    $trReg->addFilter("param in ('" . implode("','", $pairRegistries) . "')");
                    //                    $trReg->addFilter("transaksi_id='" . $row->id . "'");
                    //                    $tmpReg = $trReg->lookupRegistries()->result();
                    ////                    cekBiru($this->db->last_query());
                    //                    if (sizeof($tmpReg) > 0) {
                    //                        foreach ($tmpReg as $regRow) {
                    //                            $param = $regRow->param;
                    //                            // arrPrint(blobDecode($regRow->values));
                    //                            $$param = blobDecode($regRow->values);
                    //                        }
                    //                        foreach ($pairRegistries as $eReg) {
                    //                            foreach ($$eReg as $k => $v) {
                    //                                if (!isset($row->$k)) {
                    //                                    $row->$k = $v;
                    //                                }
                    //                            }
                    //                        }
                    //                    }

                    if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->id]))) {
                        foreach ($tmpReg_result[$row->id] as $param => $eReg) {
                            // arrPrint($eReg);
                            // matiHEre();
                            foreach ($eReg as $k => $v) {
                                // arrPrint($eReg);
                                // cekMerah($k);
                                if (strlen($k) > 0) {
                                    if (!isset($row->$k)) {
                                        // matiHEre($k." $v");
                                        $row->$k = $v;
                                        // cekMErah($k." ".$v);
                                    }
                                }
                                // if (!isset($row->$k)) {
                                //     // matiHEre($k." $v");
                                //     // $row->$k = $v;
                                //     cekMErah($k." ".$v);
                                // }
                            }
                        }
                    }
                    //                        cekHijau(":: SRN $row->referenceID ::");
                    //                        cekHijau(":: SRN $row->referenceNomer ::");
                    if (sizeof($pairTransaksi) > 0) {
                        if ($row->referenceID > 0) {
                            $trPair = new MdlTransaksi();
                            $trPair->addFilter("id='" . $row->referenceID . "'");
                            $trPairTmp = $trPair->lookupMainTransaksi()->result();
                            if (sizeof($trPairTmp) > 0) {
                                $hisTr = isset($trPairTmp[0]->ids_his) ? blobDecode($trPairTmp[0]->ids_his) : array();
                                foreach ($hisTr as $step => $hisTrSpec) {
                                    foreach ($pairTransaksi['kolom'] as $keyPair => $labelPair) {
                                        $keyPairs = $keyPair . "_" . $step;
                                        $row->$keyPairs = isset($hisTrSpec[$labelPair]) ? $hisTrSpec[$labelPair] : "--";
                                    }
                                }
                            }
                        }
                    }
                }

// arrPrint($row);
                if (sizeof($historyFieldsExt) > 0) {
                    foreach ($historyFieldsExt as $alias => $colom) {
                        $row->$alias = $row->$colom;
                    }
                }
                $tmp = array();
                $tmp1 = array();

                $numb++;
                foreach ($historyFields as $fName => $fLabel) {

                    if (strpos($fName, '+') !== false) {//==mengandung penggabungan (+)
                        $chars = explode("+", $fName);
                        $colValue = "";
                        foreach ($chars as $key) {
                            if (is_numeric($row->$key)) {
                                if (!isset($sumValue[$key])) {
                                    $sumValue[$key] = 0;
                                }
                                $sumValue[$key] += $row->$key;
                            }
                            $colValue .= isset($row->$key) ? formatField_he_format($key, $row->$key) . "<br>" : "";
                        }
                        $colValue = rtrim($colValue, "<br>");
                    }
                    else {

                        if (is_numeric(isset($row->$fName) ? $row->$fName : "")) {
                            if (!isset($sumValue[$fName])) {
                                $sumValue[$fName] = 0;
                            }
                            $sumValue[$fName] += $row->$fName;
                        }

                        //region nomer dengan global counter
                        if ($fName == "nomer") {
                            // switch ($jenisTr) {
                            switch ($jenisTrsub) {
                                case "582s":
                                    $kolomValues = $row->$fName . "&#x2011;$cGlobals";
                                    break;
                                // case "582spd":
                                default:
                                    $kolomValue_0s = formatField_he_format($fName, $row->$fName);
                                    $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobals, $kolomValue_0s);
                                    break;
                            }
                        }
                        elseif ($fName == "nomer_top") {
                            $kolomValue_0s = formatField_he_format($fName, $row->$fName);
                            $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobal_spo, $kolomValue_0s);
                        }
                        else {
                            $kolomValues = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : "-";
                        }
                        //endregion

                        if ($fName == "print_label") {

                            $link_barcode_print = base_url() . "Printing/barcodeTransaksi/" . $row->id;
                            // $kolomValues .= " &nbsp;&nbsp;<a href='$link_barcode_print' class='btn btn-info btn-xs' target='_blank' title='print barcode'><i class='fa fa-print'> barcode</i></a>";
                        }
// if($fName == "print_barcode_suka"){
//     $colValue = isset($row->$fName) ? $kolomValues : "***";
// }
                        // $colValue = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : "";
                        $colValue = isset($row->$fName) ? $kolomValues : "";
                    }

                    if ($fName == "ids_his") {
                        if (is_array($fLabel)) {

                            $hisStep = $fLabel['step'];
                            $hisKey = $fLabel['key'];
                            // $tNomer = $id_hist[$hisStep][$hisKey];


                            $colValue = isset($row->ids_his) ? showHistoriGlobalNumbers($row->ids_his, $hisStep, true) : "";

                            //                            $tr = new MdlTransaksi();
                            //                            $tr->setFilters(array());
                            //                            $tr->addFilter("param='main'");
                            //                            $tmpReg = $tr->lookupRegistriesByNumber($tNomer)->result();
                            ////                            cekHere($this->db->last_query());
                            //
                            //                            $logistic = $tmpReg[0]->oleh_nama;
                            $logistic = "";
                            if (isset($arrTransMainHist[$row->id][$hisStep]['main'])) {
                                $main = $arrTransMainHist[$row->id][$hisStep]['main'];
                                $logistic = $main['oleh_nama'];
                            }
                        }
                    }

                    if ($fName == "no") {
                        $colValue = formatField_he_format($fName, $numb);
                    }

                    //                    cekHere($logistic);
                    $tmp['logistic'] = isset($logistic) && $logistic != null ? $logistic : 'undefined';
                    $tmp['sales_name'] = $salesName;
                    $tmp[$fName] = $colValue;
                    $tmp1["id"] = $row->id;
                }


                if (sizeof($arrCurrency) > 0) {
                    $valas = "";
                    $valas .= "<div class='btn-group'>";
                    $valas .= "<button type='button' class='btn btn-primary dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
                    $valas .= "<i class='fa fa-print'></i>";
                    $valas .= "<span class='caret'></span>";
                    $valas .= "</button>";

                    $valas .= "<ul style='background:#cde8ff;' class='dropdown-menu dropdown-menu-right'>";
                    foreach ($arrCurrency as $arrV) {
                        $nama = $arrV->nama;
                        $nomer = $row->nomer;
                        $nilai = number_format($arrV->exchange, 0);
                        $valas .= " <li class='text-bold'><a class='dropdown-item' href='javascript:void(0);' onclick=\"top.popBig('" . base_url() . "Transaksi/viewReceipt/$nomer?type=" . blobEncode($nama) . "&f=" . blobEncode($arrV->exchange) . "')\"> <i class='fa fa-print'></i> in $nama - ($nilai) </a></li>";
                    }

                    $valas .= " <li><a class='btn btn-xs btn-warning' href='javascript:void(0);' onclick=\"top.location.href='" . base_url() . "data/view/Currency'\"> <i class='fa fa-plus'></i> tambah currency </a></li>";
                    $valas .= "</ul>";
                    $valas .= "</div>";
                    $tmp["print_nvalas"] = $valas;
                }

                $tmp['next_pic'] = "-";

                // menambah background-color karena dicancel/reject/undo, atau yang dibatalkan
                $tmp['keterangan'] = "-";
                if (isset($row->trash_4) && ($row->trash_4 == 1)) {
                    $tmp['keterangan'] = "CANCELED";
                    $arrayHistory_canceled[$ii] = array(
                        "bgcolor" => "background-color:#FA8072;",
                    );
                }

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


            }
        }
        //endregion
        // arrPrint($historyFields);
        // arrPrint($arrayHistory);
        $data = array(
            "mode" => "showData",
            //            "mode" => "viewHistory",
            "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,
            "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" => base_url() . $this->modul . "/" . $this->uri->segment(2) . "/viewIncomplete/" . $this->uri->segment(4),
            "alternateLinkCaption" => "incomplete " . $this->configUi[$jenisTr]["label"] . " <span class='glyphicon glyphicon-arrow-right'></span>",
            // "addLink"              => $addLink,
            "filters" => array(
                "dates" => $this->dates,
                "date1" => $date1,
                "date2" => $date2,
            ),
            "thisPage" => MODUL_URL . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5),

            "history_canceled" => isset($arrayHistory_canceled) ? $arrayHistory_canceled : array(),
        );
        //endregion


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

    public function showData()
    {
        if (!isset($this->session->login['id'])) {
            gotoLogin();
        }
        // cekBiru(ipadd());
        // cekBiru(url_segment());
        // cekBiru($_GET);

        $limit = isset($_GET['limit']) ? $_GET['limit'] : 1000;
        $str_limit = "&limit=$limit";
        // if (ipadd() == '202.65.117.72') {
        //     $limit = 10;
        // }

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

        // arrPrintPink($historyFields);
        $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");
        $menu_gr = isset($_GET['gr']) ? $_GET['gr'] : "";
        $menu_md = isset($_GET['md']) ? $_GET['md'] : "";

        if (isset($_GET['gr'])) {
            $str_menu = "&gr=$menu_gr";
            if (isset($_GET['md'])) {
                $str_menu .= "&md=$menu_md";
            }
        }
        else {
            $str_menu = "";
        }
        // cekBiru(url_segment());
        // arrPrint(MODUL_URL);
        // arrPrintWebs(base_url(url_segment()));
        $myUrl = MODUL_URL . "/" . $this->jenisTr;
        //region preparing ERP step labels for top link
        $steps = $this->configUi[$jenisTr]['steps'];
        $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] = $myUrl . "/" . $stepSpec['target'] . "?date1=$date1&date2=$date2" . $str_menu . $str_limit;
                }
            }
            // arrPrintPink($stepLinks);
            if (isset($_GET['stID'])) {
                $currentState = $_GET['stID'];
            }
            else {
                $currentState = strlen($this->uri->segment(5)) > 0 ? $this->uri->segment(5) : $this->configUi[$jenisTr]['steps'][1]['target'];
            }
        }
        //endregion
        // matiDisini(__LINE__);
        //region lookup histories
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("cabang_id='" . $this->placeId . "'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->addFilter("div_id='" . $this->session->login['div_id'] . "'");
        $searchStr = isset($_GET['search']) ? $_GET['search'] : "";

        //region date filter
        // $this->db->where("fulldate>='" . $date1 . "'");
        // $this->db->where("fulldate<='" . $date2 . "'");
        //endregion

        if (isset($currentState)) {
            $tr->addFilter("jenis='" . $currentState . "'");
        }

        $addParams = array();
        if (isset($_GET['addParams'])) {
            $addParams = unserialize(base64_decode($_GET['addParams']));
        }
        if ($addParams != null && sizeof($addParams) > 0) {
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        //        $action = array(
        //            "viewDetails" => base_url() . get_class($this) . "/viewDetails",
        //        );

        if (isset($_GET['search'])) {
            $tr->setKeyWord($searchStr);
        }
        else {
            $this->db->where("fulldate>='" . $date1 . "'");
            $this->db->where("fulldate<='" . $date2 . "'");
        }

        $jmlData = $tr->lookupDataCount();
        $page = (isset($_GET['page']) && $_GET['page'] > 0) ? ($_GET['page']) : 1;
        $offset = ($limit * ($page - 1));

        $addParams = array();
        if (isset($_GET['addParams'])) {
            $addParams = unserialize(base64_decode($_GET['addParams']));
        }
        if ($addParams != null && sizeof($addParams) > 0) {
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        $action = array(
            "viewDetails" => base_url() . get_class($this) . "/viewDetails",
        );

        if (isset($_GET['search'])) {
            $tr->setKeyWord($searchStr);
        }
        else {
            $this->db->where("fulldate>='" . $date1 . "'");
            $this->db->where("fulldate<='" . $date2 . "'");
        }
        $tmpHist = $tr->lookupHistories($jmlData, $limit, $page)->result();
        // showLast_query("biru");
        // cekBiru(sizeof($tmpHist));
        // arrPrint($tmpHist);
        $arrCurrency = array();
        if (sizeof($printValas) > 0) {
            $trv = new MdlCurrency();
            $tmpCurrency = $trv->lookupAll()->result();
            if (sizeof($tmpCurrency) > 0) {
                foreach ($tmpCurrency as $key => $value) {
                    $arrCurrency[$key] = $value;
                }
            }
        }

        $cabang_id = $this->placeId;

        $arrayHistory = array();
        $arrayHistory_ids = array();
        $arrayHistory_canceled = array();
        $sumValue = array();
        if (sizeof($tmpHist) > 0) {

            if (sizeof($pairRegistries) > 0) {
                $arrSalesName = array();
                $arrTransID = array();
                $arrTransTopID = array();
                $arrIndexID = array();
                $arrIdsHist = array();
                $arrTransHist = array();
                $arrTransMainHist = array();
                foreach ($tmpHist as $row) {
                    $arrTransID[] = $row->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'];
                        }
                    }

                    if (($row->indexing_registry)) {
                        $indexing_registry = blobDecode($row->indexing_registry);
                        // cekPink($indexing_registry['main']);
                        $indexMainRegistries[$row->id] = $indexing_registry['main'];
                    }
                }

                $tmpReg_result = array();
                $trReg = new MdlTransaksi();
                // $trReg->setFilters(array());
                // $trReg->addFilter("param='main'");
                // $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
                // $trReg->addFilter("id in ('" . implode("','", $indexMainRegistries) . "')");

                // $tmpReg = $trReg->lookupRegistries()->result();
                // showLast_query("lime");
                // arrPrint($tmpReg);

                $fieldDataRegistries = $trReg->getFields();
                $fDataRegistries = $fieldDataRegistries['dataRegistry'];
                $fieldBlock = array(
                    "transaksi_id",
                );
                $paramRegistries = array_diff($fDataRegistries, $fieldBlock);
                $tmpReg = $trReg->lookupBaseDataRegistries($arrTransID)->result();
                // cekHere($this->db->last_query());
                // arrPrint($tmpReg);

                // matiDisini(__LINE__);
                if (sizeof($tmpReg) > 0) {
                    // foreach ($tmpReg as $regRow) {
                    //     $param = $regRow->param;
                    //     $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
                    // }
                    foreach ($tmpReg as $regRow) {
                        // $param = $regRow->param;
                        foreach ($paramRegistries as $param) {
                            $regValue = isset($regRow->$param) ? blobDecode($regRow->$param): array();
                            $regParams[$param] = $regValue;
                            $tmpReg_result[$regRow->transaksi_id] = array_filter($regParams);
                        }
                    }
                }
                // arrPrint($tmpReg_result);
                // if (ipadd() == '202.65.117.72') {
                //     mati_disini(__LINE__);
                // }

                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("id in ('" . implode("','", $arrTransTopID) . "')");
                $tmpTrTop = $tr->lookupAll()->result();
                if (sizeof($tmpTrTop) > 0) {
                    foreach ($tmpTrTop as $topSpec) {
                        $arrSalesName[$topSpec->id_top] = $topSpec->oleh_nama;
                    }
                }

                //arrPrint($arrTransHist);
                //mati_disini();
                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,
                            );
                        }
                    }
                    //                    mati_disini();
                    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;
                        }
                    }
                }

            }
            //arrPrint($arrTransMainHist);
            //            mati_disini("::: ");
            $numb = 0;
            foreach ($tmpHist as $ii => $row) {
                // region ids_his
                $id_hist = blobDecode($row->ids_his);
                // endregion ids_his

                //region memangil global counter
                $tNomer_top = $row->nomer_top;
                //                $tr = new MdlTransaksi();
                //                $tr->addFilter("param='main'");
                //                $tmpReg = $tr->lookupRegistriesByNumber($tNomer_top)->result();
                //
                //                $arrSalesName = "";
                //                foreach ($tmpReg as $tmpRowReg) {
                //                    $arrSalesName = $tmpRowReg->oleh_nama;
                //                }
                $salesName = isset($arrSalesName[$row->id_top]) ? $arrSalesName[$row->id_top] : "-";


                $tNomer = $row->nomer;
                $jenisTrtop = explode(".", $tNomer_top)[0];
                $jenisTrsub = explode(".", $tNomer)[0];
                $counterjenis = "$jenisTrsub|" . my_toko_id();
                // cekHere($tNomer_top);
                $arrIdHist = blobDecode($row->ids_his);
                $arrCounters = isset($arrIdHist[1]['counters']) ? blobDecode($arrIdHist[1]['counters']) : "";

                $counterIds_his = is_array($arrCounters) ? blobDecode(blobDecode($row->ids_his)[1]['counters']) : "";
                $counters = blobDecode($row->counters);
                // arrPrint($counterIds_his);
                // $counterGlobal = $counters['stepCode|placeID'][$counterjenis];
                $counterGlobal = $counters['stepCode|tokoID'][$counterjenis];


                $counterIds_his_global = isset($counterIds_his['stepCode|tokoID']["$jenisTrtop|$cabang_id"]) ? $counterIds_his['stepCode|placeID']["$jenisTrtop|$cabang_id"] : "";
                $cGlobals = digit_5($counterGlobal);
                $cGlobal_spo = digit_5($counterIds_his_global);

                //endregion

                if (sizeof($pairRegistries) > 0) {
                    //                    $trReg = new MdlTransaksi();
                    //                    $trReg->setFilters(array());
                    //                    $trReg->addFilter("param in ('" . implode("','", $pairRegistries) . "')");
                    //                    $trReg->addFilter("transaksi_id='" . $row->id . "'");
                    //                    $tmpReg = $trReg->lookupRegistries()->result();
                    ////                    cekBiru($this->db->last_query());
                    //                    if (sizeof($tmpReg) > 0) {
                    //                        foreach ($tmpReg as $regRow) {
                    //                            $param = $regRow->param;
                    //                            // arrPrint(blobDecode($regRow->values));
                    //                            $$param = blobDecode($regRow->values);
                    //                        }
                    //                        foreach ($pairRegistries as $eReg) {
                    //                            foreach ($$eReg as $k => $v) {
                    //                                if (!isset($row->$k)) {
                    //                                    $row->$k = $v;
                    //                                }
                    //                            }
                    //                        }
                    //                    }

                    if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->id]))) {
                        foreach ($tmpReg_result[$row->id] as $param => $eReg) {
                            foreach ($eReg as $k => $v) {
                                if (!isset($row->$k)) {
                                    $row->$k = $v;
                                }
                            }
                        }
                    }
                    //                        cekHijau(":: SRN $row->referenceID ::");
                    //                        cekHijau(":: SRN $row->referenceNomer ::");
                    if (sizeof($pairTransaksi) > 0) {
                        if ($row->referenceID > 0) {
                            $trPair = new MdlTransaksi();
                            $trPair->addFilter("id='" . $row->referenceID . "'");
                            $trPairTmp = $trPair->lookupMainTransaksi()->result();
                            if (sizeof($trPairTmp) > 0) {
                                $hisTr = isset($trPairTmp[0]->ids_his) ? blobDecode($trPairTmp[0]->ids_his) : array();
                                foreach ($hisTr as $step => $hisTrSpec) {
                                    foreach ($pairTransaksi['kolom'] as $keyPair => $labelPair) {
                                        $keyPairs = $keyPair . "_" . $step;
                                        $row->$keyPairs = isset($hisTrSpec[$labelPair]) ? $hisTrSpec[$labelPair] : "--";
                                    }
                                }
                            }
                        }
                    }
                }


                if (sizeof($historyFieldsExt) > 0) {
                    foreach ($historyFieldsExt as $alias => $colom) {
                        $row->$alias = $row->$colom;
                    }
                }
                $tmp = array();
                $tmp1 = array();

                $numb++;
                foreach ($historyFields as $fName => $fLabel) {

                    if (strpos($fName, '+') !== false) {//==mengandung penggabungan (+)
                        $chars = explode("+", $fName);
                        $colValue = "";
                        foreach ($chars as $key) {
                            if (is_numeric($row->$key)) {
                                if (!isset($sumValue[$key])) {
                                    $sumValue[$key] = 0;
                                }
                                $sumValue[$key] += $row->$key;
                            }
                            $colValue .= isset($row->$key) ? formatField_he_format($key, $row->$key) . "<br>" : "";
                        }
                        $colValue = rtrim($colValue, "<br>");
                    }
                    else {

                        if (is_numeric(isset($row->$fName) ? $row->$fName : "")) {
                            if (!isset($sumValue[$fName])) {
                                $sumValue[$fName] = 0;
                            }
                            $sumValue[$fName] += $row->$fName;
                        }

                        //region nomer dengan global counter
                        if ($fName == "nomer") {
                            // switch ($jenisTr) {
                            switch ($jenisTrsub) {
                                case "582s":
                                    $kolomValues = $row->$fName . "&#x2011;$cGlobals";
                                    break;
                                // case "582spd":
                                default:
                                    $kolomValue_0s = formatField_he_format($fName, $row->$fName);
                                    $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobals, $kolomValue_0s);
                                    break;
                            }
                        }
                        elseif ($fName == "nomer_top") {
                            $kolomValue_0s = formatField_he_format($fName, $row->$fName);
                            $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobal_spo, $kolomValue_0s);
                        }
                        else {
                            $kolomValues = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : "-";
                        }
                        //endregion

                        if ($fName == "print_label") {

                            $link_barcode_print = base_url() . "Printing/barcodeTransaksi/" . $row->id;
                            // $kolomValues .= " &nbsp;&nbsp;<a href='$link_barcode_print' class='btn btn-info btn-xs' target='_blank' title='print barcode'><i class='fa fa-print'> barcode</i></a>";
                        }

                        // $colValue = isset($row->$fName) ? formatField_he_format($fName, $row->$fName) : "";
                        $colValue = isset($row->$fName) ? $kolomValues : "";
                    }

                    if ($fName == "ids_his") {
                        if (is_array($fLabel)) {

                            $hisStep = $fLabel['step'];
                            $hisKey = $fLabel['key'];
                            // $tNomer = $id_hist[$hisStep][$hisKey];


                            $colValue = isset($row->ids_his) ? showHistoriGlobalNumbers($row->ids_his, $hisStep, true) : "";

                            //                            $tr = new MdlTransaksi();
                            //                            $tr->setFilters(array());
                            //                            $tr->addFilter("param='main'");
                            //                            $tmpReg = $tr->lookupRegistriesByNumber($tNomer)->result();
                            ////                            cekHere($this->db->last_query());
                            //
                            //                            $logistic = $tmpReg[0]->oleh_nama;
                            $logistic = "";
                            if (isset($arrTransMainHist[$row->id][$hisStep]['main'])) {
                                $main = $arrTransMainHist[$row->id][$hisStep]['main'];
                                $logistic = $main['oleh_nama'];
                            }
                        }
                    }

                    if ($fName == "no") {
                        $colValue = formatField_he_format($fName, $numb);
                    }

                    //                    cekHere($logistic);
                    $tmp['logistic'] = isset($logistic) && $logistic != null ? $logistic : 'undefined';
                    $tmp['sales_name'] = $salesName;
                    $tmp[$fName] = $colValue;
                    $tmp1["id"] = $row->id;
                }


                if (sizeof($arrCurrency) > 0) {
                    $valas = "";
                    $valas .= "<div class='btn-group'>";
                    $valas .= "<button type='button' class='btn btn-primary dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
                    $valas .= "<i class='fa fa-print'></i>";
                    $valas .= "<span class='caret'></span>";
                    $valas .= "</button>";

                    $valas .= "<ul style='background:#cde8ff;' class='dropdown-menu dropdown-menu-right'>";
                    foreach ($arrCurrency as $arrV) {
                        $nama = $arrV->nama;
                        $nomer = $row->nomer;
                        $nilai = number_format($arrV->exchange, 0);
                        $valas .= " <li class='text-bold'><a class='dropdown-item' href='javascript:void(0);' onclick=\"top.popBig('" . base_url() . "Transaksi/viewReceipt/$nomer?type=" . blobEncode($nama) . "&f=" . blobEncode($arrV->exchange) . "')\"> <i class='fa fa-print'></i> in $nama - ($nilai) </a></li>";
                    }

                    $valas .= " <li><a class='btn btn-xs btn-warning' href='javascript:void(0);' onclick=\"top.location.href='" . base_url() . "data/view/Currency'\"> <i class='fa fa-plus'></i> tambah currency </a></li>";
                    $valas .= "</ul>";
                    $valas .= "</div>";
                    $tmp["print_nvalas"] = $valas;
                }

                $tmp['next_pic'] = "-";

                // menambah background-color karena dicancel/reject/undo, atau yang dibatalkan
                $tmp['keterangan'] = "-";
                if (isset($row->trash_4) && ($row->trash_4 == 1)) {
                    $tmp['keterangan'] = "CANCELED";
                    $arrayHistory_canceled[$ii] = array(
                        "bgcolor" => "background-color:#FA8072;",
                    );
                }

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


            }
        }
        //endregion
        // arrPrint($historyFields);
        $data = array(
            "mode" => "showData",
            //            "mode" => "viewHistory",
            "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,
            "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" => base_url() . $this->modul . "/" . $this->uri->segment(2) . "/viewIncomplete/" . $this->uri->segment(4),
            "alternateLinkCaption" => "incomplete " . $this->configUi[$jenisTr]["label"] . " <span class='glyphicon glyphicon-arrow-right'></span>",
            // "addLink"              => $addLink,
            "filters" => array(
                "dates" => $this->dates,
                "date1" => $date1,
                "date2" => $date2,
            ),
            "thisPage" => MODUL_URL . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5),

            "history_canceled" => isset($arrayHistory_canceled) ? $arrayHistory_canceled : array(),
        );
        //endregion


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