<?php
require_once "Modul_Controller.php";

class ActivityReport extends Modul_Controller
{
    // private $jenisTr;


    public function __construct()
    {
        parent::__construct();
        $tmpJenis = $this->uri->segment(4);
        if (strlen($tmpJenis) > 0) {
            $this->jenisTr = $tmpJenis;
        }

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

        $this->load->library("MobileDetect");
        $this->load->model("MdlTransaksi");
        $this->load->model("Mdls/MdlEmployeeCabang");
        // $this->load->model("Mdls/MdlReport");

        $trd = new MdlTransaksi();
        $trd->addFilter("jenis_top='" . $this->jenisTr . "'");
        $this->dates = $trd->lookupDates();
        $this->dates['entries'][date("y-m-d")] = date("y-m-d");
        $this->placeId = $this->session->login['cabang_id'];

        $this->sID_alias = array(
            "oleh_id" => "olehID",
            "customers_id" => "pihakID",
            "cabang_id" => "cabangID",
            "produk_id" => "id",
            "suppliers_id" => "pihakID",
            "seller_id" => "sellerID",
        );
    }

    public function viewMonthly()
    {
        $starttime = microtime(true);
        $currYear = isset($_GET['y']) ? $_GET['y'] : date("Y");
        $currMonth = isset($_GET['m']) ? $_GET['m'] : date("m");
        // $currMonth = "9";
        $dateStr = $currYear . "-" . $currMonth;

        $steps = $this->configUi[$this->jenisTr]['steps'];
        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
        }

        $currentState = strlen($this->uri->segment(5)) > 0 ? $this->uri->segment(5) : $this->configUi[$this->jenisTr]['steps'][1]['target'];
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("transaksi.jenis_master='" . $this->jenisTr . "'");
        if (isset($currentState)) {
            $tr->addFilter("transaksi.jenis='" . $currentState . "'");
        }

        //        $this->db->like('transaksi.dtime', $dateStr, 'after');
        $this->db->where("year(transaksi.dtime)='$currYear'");
        $this->db->where("month(transaksi.dtime)='$currMonth'");
        // $this->db->limit(10);
        // $tmp = $tr->lookupJoined__()->result();
        ceklime($this->db->last_query());
        // matiHEre();
        $tmp = $tr->lookupJoined();

        //         cekBiru(sizeof($tmp));
        // // arrPrint($tmp);
        //         matiHEre(__LINE__." timer ". $val);
        //        cekbiru($this->db->last_query());
        $identifiers = $tr->fetchIdentifiers();

        // arrPrint($identifiers);
        // matiHere();
        $recaps = array();

        $dates = array();

        if (sizeof($tmp) > 0) {
            foreach ($tmp as $row) {
                if (sizeof($identifiers) > 0) {
                    $fulldate = substr($row->dtime, 0, 7);
                    $dates[$fulldate] = $fulldate;
                    $jenis = $row->jenis;
                    foreach ($identifiers as $iID => $iName) {


                        if (isset($row->$iID) && strlen($row->$iID) > 0 && strlen($row->$iName) > 0) {
                            if (!isset($names[$iID])) {
                                $names[$iID] = array();
                            }

                            $names[$iID][$row->$iID] = $row->$iName;
                            if (!isset($recaps[$jenis][$iID][$fulldate][$row->$iID])) {
                                $recaps[$jenis][$iID][$fulldate][$row->$iID] = array(
                                    "qty" => 0,
                                    "value" => 0,
                                );
                            }

                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['qty'] += $row->produk_ord_jml;
                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['value'] += ($row->produk_ord_jml * $row->produk_ord_hrg);
                        }


                    }

                }
            }
        }

        $months = array();
        for ($i = 1; $i <= 12; $i++) {
            if (strlen($i) < 2) {
                $i = "0" . $i;
            }
            $key = $currYear . "-" . $i;
            //            echo $i."<br>";
            //            $months[$i]=date("F", strtotime("Y-".$i."-d"));
            $months[$key] = $i;

        }
        //        arrprint($months);


        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;
        $selectedStep = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;

        //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 = MODUL_PATH . $createIndexes[$this->jenisTr] . "/" . $this->jenisTr;
            }
            else {
                $targetUrl = MODUL_PATH . "Create/createForm/" . $this->jenisTr;
            }
            $addLink = array(
                "link" => $targetUrl,
                "label" => "<span class='glyphicon glyphicon-plus'></span> create new " . $this->configUi[$this->jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion
        //         $endtime = microtime(true); // Bottom of page
        //         $val =$endtime-$starttime;
        // cekHitam(get_class($this));
        $data = array(
            "mode" => "recap",
            "title" => $this->configUi[$this->jenisTr]['label'] . " report",
            "subTitle" => "monthly, " . $currYear,
            "times" => $months,
            "timeLabel" => "months",
            "names" => isset($names) ? $names : array(),
            "recaps" => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => $this->configUi[$this->jenisTr]["label"],
            "availFilters" => $availFilters,
            "defaultFilter" => $defaultFilter,
            "selectedFilter" => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => MODUL_PATH . get_class($this) . "/" . $this->uri->segment(3),
            "subPage" => MODUL_PATH . get_class($this) . "/viewDaily/" . $this->jenisTr,
            "historyPage" => MODUL_PATH . "History/viewHistory/" . $this->jenisTr . "/" . $this->jenisTr,
            "stepNames" => $stepNames,
            "defaultStep" => $defaultStep,
            "selectedStep" => $selectedStep,
            "addLink" => $addLink,
        );
        $this->load->view("activityReports", $data);

    }

    public function viewWeekly()
    {
        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;


        $currYear = isset($_GET['y']) ? $_GET['y'] : date("Y");
        $currMonth = isset($_GET['m']) ? $_GET['m'] : date("m");
        $currDate = isset($_GET['d']) ? $_GET['d'] : date("d");
        $dateStr = $currYear . "-" . $currMonth;
        $stID = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;
        $sID = isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter;
        $sID = isset($this->sID_alias[$sID]) ? $this->sID_alias[$sID] : "";

        $steps = $this->configUi[$this->jenisTr]['steps'];
        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
        }

        if ($this->session->login['cabang_id'] > 0) {
            $selectedCabang = "transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'";
        }
        else {
            $selectedCabang = "transaksi.cabang_id<>-1";
        }
        $currentState = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->configUi[$this->jenisTr]['steps'][1]['target'];
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        //        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter($selectedCabang);
        $tr->addFilter("transaksi.trash_4='0'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->addFilter("jenis='" . $stID . "'");
        //        if (isset($currentState)) {
        //            $tr->addFilter("jenis='" . $currentState . "'");
        //        }
        //

        $this->db->like('transaksi.dtime', $dateStr, 'after');
        $tmp = $tr->lookupJoined()->result();

        //        cekbiru($this->db->last_query());

        $identifiers = $tr->fetchIdentifiers();

        $recaps = array();

        $dates = array();


        if (sizeof($tmp) > 0) {
            foreach ($tmp as $row) {
                if (sizeof($identifiers) > 0) {
                    //                    $fulldate = substr($row->dtime, 0, 7);
                    $fulldate = substr($row->dtime, 0, 10);
                    //                    echo "date $fulldate<br>";
                    $dates[$fulldate] = $fulldate;
                    $jenis = $row->jenis;
                    foreach ($identifiers as $iID => $iName) {


                        if (strlen($row->$iID) > 0 && strlen($row->$iName) > 0) {

                            if (!isset($names[$iID])) {
                                $names[$iID] = array();
                            }

                            $names[$iID][$row->$iID] = $row->$iName;
                            if (!isset($recaps[$jenis][$iID][$fulldate][$row->$iID])) {
                                $recaps[$jenis][$iID][$fulldate][$row->$iID] = array(
                                    "qty" => 0,
                                    "value" => 0,
                                );
                            }

                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['qty'] += $row->produk_ord_jml;
                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['value'] += ($row->produk_ord_jml * $row->produk_ord_hrg);
                        }
                    }

                }
            }
        }


        $months = array();
        for ($i = 1; $i <= 31; $i++) {
            if (strlen($i) < 2) {
                $i = "0" . $i;
            }
            $key = $currYear . "-" . $currMonth . "-" . $i;
            $months[$key] = $i;

        }

        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;
        $selectedStep = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;

        //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[$this->jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion

        $data = array(
            "jenisTr" => $this->jenisTr,
            "mode" => "recap",
            "title" => $this->configUi[$this->jenisTr]['label'] . " reports",
            "subTitle" => "daily, " . lgTranslateTime($dateStr),
            "times" => $months,
            "timeLabel" => "dates",
            "names" => isset($names) ? $names : array(),
            "recaps" => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => $this->configUi[$this->jenisTr]["label"],
            "availFilters" => $availFilters,
            "defaultFilter" => $defaultFilter,
            "selectedFilter" => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->jenisTr,
            "historyPage" => base_url() . "Transaksi/viewHistory/" . $this->jenisTr . "/" . $selectedStep,
            "stepNames" => $stepNames,
            "defaultStep" => $defaultStep,
            "selectedStep" => $selectedStep,
            "addLink" => $addLink,
        );
        $this->load->view("activityReports", $data);

    }

    public function viewDaily()
    {
        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;

        $currYear = isset($_GET['y']) ? $_GET['y'] : date("Y");
        $currMonth = isset($_GET['m']) ? $_GET['m'] : date("m");
        $currDate = isset($_GET['d']) ? $_GET['d'] : date("d");
        $dateStr = $currYear . "-" . $currMonth;
        $stID = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;
        $sID = isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter;
        //        cekHitam($sID);
        $sID = isset($this->sID_alias[$sID]) ? $this->sID_alias[$sID] : "";
        //        cekHitam($sID);
        $steps = $this->configUi[$this->jenisTr]['steps'];
        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
        }
        // if ($this->session->login['cabang_id'] > 0) {
        //     $selectedCabang = "transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'";
        // }
        // else {
        //     $selectedCabang = "transaksi.cabang_id<>-1";
        // }

        $currentState = strlen($this->uri->segment(5)) > 0 ? $this->uri->segment(5) : $this->configUi[$this->jenisTr]['steps'][1]['target'];
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        //        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("trash_4='0'");
        // $tr->addFilter("transaksi_data.trash='0'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->addFilter("jenis='" . $stID . "'");
        $tr->addFilter("month(dtime)='" . $currMonth . "'");
        $tr->addFilter("year(dtime)='" . $currYear . "'");
        $tr->addFilterJoin("trash='0'");
        $tmp = $tr->lookupJoined();

        // cekbiru($this->db->last_query());
        // arrprint($tmp);
        // matiHere($stID);
        $trIds_ = array();
        $trIdDts = array();
        //region data dari registry untuk mendapatkan nilai nett1
        foreach ($tmp as $item) {
            $trIds_[$item->transaksi_id] = 1;
            $trIdDts[$item->transaksi_id]['dtime'] = $item->dtime;
            $trIdDts[$item->transaksi_id]['olehID'] = $item->oleh_id;
            $trIdDts[$item->transaksi_id]['sellerID'] = $item->seller_id;
            $trIdDts[$item->transaksi_id]['cabangID'] = $item->cabang_id;
            $trIdDts[$item->transaksi_id]['pihakID'] = ($item->suppliers_id < 1 ? $item->customers_id : $item->suppliers_id);
        }
        // arrPrint($trIdDtimes_);
        $trIds = array_keys($trIds_);
        $idList = implode(",", $trIds);
        if (strlen($idList) > 3) {

            $tr_2 = new MdlTransaksi();
            $tr_2->setFilters(array());
            $tr_2->addFilter("transaksi_id in '(" . $idList . ")'");
            // $tr_2->addFilter("param ='items'");
            $tr_2->setJointSelectFields("items");
            // $registries = $tr_2->lookupRegistries()->result();
            $registries = $tr_2->lookupDataRegistries()->result();
            // cekHitam($this->db->last_query());
            // arrPrint($registries);
            $subNett = array();
            $subHarga = array();
            foreach ($registries as $registry) {
                // cekMerah($registry->transaksi_id);
                $trDtime = $trIdDts[$registry->transaksi_id]["dtime"];
                $trDtime_m = formatTanggal($trDtime, "Y-m");
                // cekMerah("$trDtime *** $trDtime_M");
                $regs = blobDecode($registry->items);
                // arrPrint($regs);
                // cekHijau($trDtime);
                // arrPrint($registry);

                $pihakIdDatasValues = array();
                foreach ($regs as $reg) {
                    $xsID = key_exists($sID, $trIdDts[$registry->transaksi_id]) ? $trIdDts[$registry->transaksi_id][$sID] : $reg[$sID];
                    //                    cekLime($xsID);
                    // cekLime($xsID . " $trDtime_m" );
                    // arrPrint($reg);
                    // $pihakIdDatasValues[$reg['pihakID']] += $reg['nett1'];
                    // cekHitam($reg['pihakName'] . " " . $reg['pihakID'] . " == " . $reg['nett1']);
                    if (!isset($subNett[$trDtime_m][$xsID])) {
                        $subNett[$trDtime_m][$xsID] = 0;
                    }
                    if (isset($reg['nett1'])) {
                        $subNett[$trDtime_m][$xsID] += ($reg['nett1'] * $reg['jml']);
                    }
                    elseif (isset($reg['nett'])) {
                        $subNett[$trDtime_m][$xsID] += ($reg['nett'] * $reg['jml']);

                    }
                    else {
                        $subNett[$trDtime_m][$xsID] += (0);
                    }

                    // $subNett[$reg['pihakName']] += $reg['nett1'];

                    // cekHijau($reg['nett1'] . " net" );
                }
                // $pihakIdDatas['pihakID']
            }
        }
        //endregion

        $identifiers = $tr->fetchIdentifiers();

        $recaps = array();

        $dates = array();


        if (sizeof($tmp) > 0) {
            foreach ($tmp as $row) {
                if (sizeof($identifiers) > 0) {
                    //                    $fulldate = substr($row->dtime, 0, 7);
                    $fulldate = substr($row->dtime, 0, 10);
                    //                    echo "date $fulldate<br>";
                    $dates[$fulldate] = $fulldate;
                    $jenis = $row->jenis;
                    foreach ($identifiers as $iID => $iName) {


                        if (strlen($row->$iID) > 0 && strlen($row->$iName) > 0) {

                            if (!isset($names[$iID])) {
                                $names[$iID] = array();
                            }

                            $names[$iID][$row->$iID] = $row->$iName;
                            if (!isset($recaps[$jenis][$iID][$fulldate][$row->$iID])) {
                                $recaps[$jenis][$iID][$fulldate][$row->$iID] = array(
                                    "qty" => 0,
                                    "value" => 0,
                                );
                            }

                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['qty'] += $row->produk_ord_jml;
                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['value'] += ($row->produk_ord_jml * $row->produk_ord_hrg);
                        }
                    }

                }
            }
        }


        $months = array();
        for ($i = 1; $i <= 31; $i++) {
            if (strlen($i) < 2) {
                $i = "0" . $i;
            }
            $key = $currYear . "-" . $currMonth . "-" . $i;
            $months[$key] = $i;

        }

        //        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        //        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        //        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;
        $selectedStep = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;

        //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 = MODUL_PATH . $createIndexes[$this->jenisTr] . "/" . $this->jenisTr;
            }
            else {
                $targetUrl = MODUL_PATH . "Create/createForm/" . $this->jenisTr;
            }
            $addLink = array(
                "link" => $targetUrl,
                "label" => "<span class='glyphicon glyphicon-plus'></span> create new " . $this->configUi[$this->jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion

        $data = array(
            "jenisTr" => $this->jenisTr,
            "mode" => "recap",
            "title" => $this->configUi[$this->jenisTr]['label'] . " reports",
            "subTitle" => "daily, " . lgTranslateTime($dateStr),
            "times" => $months,
            "timeLabel" => "dates",
            "names" => isset($names) ? $names : array(),
            "recaps" => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => $this->configUi[$this->jenisTr]["label"],
            "availFilters" => $availFilters,
            "defaultFilter" => $defaultFilter,
            "selectedFilter" => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => MODUL_PATH . get_class($this) . "/" . $this->uri->segment(3) . "/" . $this->jenisTr,
            "historyPage" => MODUL_PATH . "History/viewHistory/" . $this->jenisTr . "/" . $selectedStep,
            "stepNames" => $stepNames,
            "defaultStep" => $defaultStep,
            "selectedStep" => $selectedStep,
            "addLink" => $addLink,
        );
        $this->load->view("activityReports", $data);

    }

    public function viewMySettlement_blmJadi()
    {

        $jenisTr = $this->uri->segment(3);
        //
        $trIDs_allRoutes = array();
        $trIDs_mine = array();
        $trIDs_followers = array();
        $trIDs_referers = array();

        //
        $trItems = array();
        $myItems = array();
        $followerItems = array();

        //
        $trans = array();
        $trans_mine = array();
        $trans_followers = array();

        $this->jenisTrName = isset($this->configUi[$this->jenisTr]['steps'][1]['label']) ? $this->configUi[$this->jenisTr]['steps'][1]['label'] : "unnamed";

        $settlConfig = $this->config->item("heTransaksi_settlementGroups");
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

        $routeFollowers = null != ($this->config->item("heTransaksi_routeFollowers")) ? $this->config->item("heTransaksi_routeFollowers") : array();

        //region preparing ERP step labels for top link
        $steps = $this->configUi[$jenisTr]['steps'];
        $stepLabels = array(//            "0" => "all"
        );
        $stepLinks = array(//            "0" => base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3)
        );
        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['stateLabel'];
                    $stepLabels[$stepNumber] = $stepSpec['label'];
                    $stepLinks[$stepNumber] = base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $stepSpec['target'];
                }

            }

            //            $currentState = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->jenisTr;
            $currentState = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->configUi[$this->jenisTr]['steps'][1]['target'];
        }
        //endregion

        $historyFields = isset($this->config->item("heTransaksi_report")[$jenisTr]['longHistoryFields']) ? $this->config->item("heTransaksi_report")[$jenisTr]['longHistoryFields'] : array(
            "produk_nama" => "item name",
            "produk_ord_jml" => "qty",
            "produk_ord_hrg" => "@price",

            "nomer_top+nomer" => "receipt number",
            "oleh_nama+dtime" => "person",
        );
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }


        $trHeaders = array(
            "dtime" => "time",
            "nomer" => "receipt number",
            "jenis_label" => "activity",
            "transaksi_nilai" => "orig. value",
            "add_disc" => "discount",
            "grand_total" => "nett",
        );

        $trHeaders_related = array(
            "dtime" => "time",
            "nomer" => "receipt number",
            "jenis_label" => "activity",
            "transaksi_nilai" => "amount",
            //            "add_disc"=>"discount",
            //            "grand_total"=>"nett",
            "oleh_nama" => "person",
        );


        //
        //region getting trans-IDs
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->setFilters(array());

        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("gudang_id='" . $this->session->login['gudang_id'] . "'");
        if (isset($routeFollowers[$this->jenisTr]) && sizeof($routeFollowers[$this->jenisTr]) > 0) {
            $tr->addFilter("jenis_master in ('" . $this->jenisTr . "','" . $routeFollowers[$this->jenisTr] . "')");
        }
        else {
            $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        }

        //        $tr->addFilter("transaksi.oleh_id='" . $this->session->login['id'] . "'");

        $tr->addFilter("transaksi_registry.param in ('tableIn_master_values','main')");
        //        $tr->addFilter("transaksi.oleh_id='" . $uID . "'");

        //region date filter
        $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-d");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
        $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) {
            //            arrprint($addParams);
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }

        //region date filter
        $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-d");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
        $this->db->where("fulldate>='" . $date1 . "'");
        $this->db->where("fulldate<='" . $date2 . "'");
        //endregion

        $arrayHistory = array();
        $arrayHistory_ids = array();

        $trIDs = array();
        $tr0 = $tr;

        //        $trLabels=array();
        //        arrprint($tr0->getFilters());
        $this->db->order_by("transaksi.id");


        $tmpHist0 = $tr0->lookupRegistries_joined()->result();
        //        cekbiru($this->db->last_query());
        if (sizeof($tmpHist0) > 0) {
            foreach ($tmpHist0 as $row) {
                if (!in_array($row->transaksi_id, $trIDs)) {

                    if (!array_key_exists($row->jenis, $trans)) {
                        $trans[$row->jenis] = array(
                            "label" => $row->jenis_label,
                            "qty" => 0,
                            "subtotal" => 0,
                        );
                    }


                    $trans[$row->jenis]['qty']++;
                    $trans[$row->jenis]['subtotal'] += $row->transaksi_nilai;

                    $trIDs[] = $row->transaksi_id;

                    $tmpCol = array();
                    $tmpCol['oleh_nama'] = $row->oleh_nama;
                    $content = blobDecode($row->values);
                    //                    arrprint($content);
                    foreach ($trHeaders as $colName => $colLabel) {
                        if (isset($content[$colName])) {
                            $tmpCol[$colName] = $content[$colName];
                        }
                        else {
                            $tmpCol[$colName] = isset($row->$colName) ? $row->$colName : 0;
                        }
                    }

                    //====ID registrars
                    $trIDs_allRoutes[] = $row->transaksi_id;
                    if ($row->oleh_id == $this->session->login['id'] && $row->jenis == $this->jenisTr) {
                        $trIDs_mine[] = $row->transaksi_id;
                        $myItems[] = $tmpCol;
                        $trItems[] = $tmpCol;
                        if (!array_key_exists($row->jenis, $trans_mine)) {
                            $trans_mine[$row->jenis] = array(
                                "label" => $row->jenis_label,
                                "qty" => 0,
                                "subtotal" => 0,
                            );
                        }
                        $trans_mine[$row->jenis]['qty']++;
                        $trans_mine[$row->jenis]['subtotal'] += $row->transaksi_nilai;
                    }
                    if (isset($content['referenceID']) && $content['referenceID'] > 0) {
                        $trIDs_followers[] = $row->transaksi_id;
                        $followerItems[] = $tmpCol;

                        if (!array_key_exists($row->jenis, $trans_followers)) {
                            $trans_followers[$row->jenis] = array(
                                "label" => $row->jenis_label,
                                "qty" => 0,
                                "subtotal" => 0,
                            );
                        }
                        $trans_followers[$row->jenis]['qty']++;
                        $trans_followers[$row->jenis]['subtotal'] += $row->transaksi_nilai;

                    }
                    //====

                    $trItems[] = $tmpCol;
                }
            }
        }
        //endregion


        //        arrprint($trIDs_allRoutes);
        //        arrprint($trIDs_mine);
        //        arrprint($trIDs_followers);
        //        die();
        $accounts = array();
        $rels = array();
        $accountRecaps = array();

        $this->load->helper("he_mass_table");

        if (sizeof($mems) > 0) {
            foreach ($mems as $gID) {
                if (isset($settlConfig[$gID]) && sizeof($settlConfig[$gID]) > 0) {
                    foreach ($settlConfig[$gID] as $accID => $relPair) {
                        $accounts[$accID] = $accID;
                        foreach ($relPair as $comID => $comLabel) {
                            $rels[$accID][$comID] = $comLabel;
                        }
                    }
                }
            }
        }

        $names = array();
        $recaps = array();

        $columns = array();

        if (sizeof($trIDs_allRoutes) > 0) {
            if (sizeof($accounts) > 0) {
                foreach ($accounts as $accID => $rekName) {
                    if (isset($rels[$accID]) && sizeof($rels[$accID]) > 0) {
                        foreach ($rels[$accID] as $comID => $comLabel) {
                            if (!isset($names[$accID])) {
                                $names[$accID] = array();
                            }
                            if (!isset($recaps[$accID])) {
                                $recaps[$accID] = array();
                            }
                            $mdlName = "Com" . $comID;
                            $this->load->model("Coms/" . $mdlName);
                            $com = new $mdlName();

                            $com->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");

                            $defPosition = detectRekDefaultPosition($rekName);
                            $opPosition = $defPosition == "kredit" ? "debet" : "kredit";
                            $tmp = $com->fetchMovesByTransIDs($accID, $trIDs_allRoutes);

                            //                            arrprint($tmp);

                            //                            cekbiru($this->db->last_query());
                            if (sizeof($tmp) > 0) {
                                foreach ($tmp as $row) {
                                    $jenis = $row->jenis;

                                    if (!isset($columns[$accID])) {
                                        $columns[$accID] = array();
                                    }

                                    if (!isset($columns[$accID][$jenis])) {
                                        $columns[$accID][$jenis] = array(
                                            "extern_nama" => "item names",
                                        );
                                    }
                                    if (!isset($recaps[$accID][$jenis])) {
                                        $recaps[$accID][$jenis] = array();
                                    }
                                    if (!isset($recaps[$accID]["total"])) {
                                        $recaps[$accID]["total"] = array();
                                    }
                                    if (!isset($names[$accID][$jenis])) {
                                        $names[$accID][$jenis] = array();
                                    }
                                    if (!array_key_exists($row->extern_id, $names[$accID][$jenis])) {
                                        $names[$accID][$jenis][$row->extern_id] = $row->extern_nama;
                                    }
                                    if (!isset($recaps[$accID][$jenis][$row->extern_id])) {
                                        $recaps[$accID][$jenis][$row->extern_id] = array(
                                            "extern_nama" => $row->extern_nama,
                                            "qty_in" => 0,
                                            "value_in" => 0,
                                            "qty_out" => 0,
                                            "value_out" => 0,
                                            "qty_saldo" => 0,
                                            "value_saldo" => 0,
                                            "qty" => 0,
                                            "value" => 0,
                                        );
                                    }
                                    $recaps[$accID][$jenis][$row->extern_id]['value_in'] += $row->$defPosition;
                                    $recaps[$accID][$jenis][$row->extern_id]['value_out'] += $row->$opPosition;
                                    $recaps[$accID][$jenis][$row->extern_id]['value_saldo'] = $row->$opPosition . "_akhir";

                                    $qtyField = "qty_" . $defPosition;
                                    $qtyOpField = "qty_" . $opPosition;
                                    if (isset($row->$qtyField)) {
                                        $recaps[$accID][$jenis][$row->extern_id]['qty_in'] += $row->$qtyField;
                                        $recaps[$accID][$jenis][$row->extern_id]['qty_out'] += $row->$qtyOpField;
                                        $recaps[$accID][$jenis][$row->extern_id]['qty_saldo'] = $row->$qtyOpField . "_akhir";
                                    }

                                    //==identifying needed columns
                                    $srcs = array(
                                        "qty_in" => "in",
                                        "value_in" => "in (IDR)",
                                        "qty_out" => "out",
                                        "value_out" => "out (IDR)",

                                    );
                                    foreach ($srcs as $key => $label) {
                                        if (isset($recaps[$accID][$jenis][$row->extern_id][$key]) && $recaps[$accID][$jenis][$row->extern_id][$key] > 0) {
                                            $columns[$accID][$jenis][$key] = $label;
                                        }
                                    }

                                    //===total
                                    $jenis = "total";
                                    if (!isset($columns[$accID][$jenis])) {
                                        $columns[$accID][$jenis] = array(
                                            "extern_nama" => "item names",
                                        );
                                    }
                                    if (!isset($recaps[$accID][$jenis][$row->extern_id])) {
                                        $recaps[$accID][$jenis][$row->extern_id] = array(
                                            "extern_nama" => $row->extern_nama,
                                            "qty_in" => 0,
                                            "value_in" => 0,
                                            "qty_out" => 0,
                                            "value_out" => 0,
                                            "qty_saldo" => 0,
                                            "value_saldo" => 0,
                                            "qty" => 0,
                                            "value" => 0,
                                        );
                                    }
                                    $recaps[$accID][$jenis][$row->extern_id]['value_in'] += $row->$defPosition;
                                    $recaps[$accID][$jenis][$row->extern_id]['value_out'] += $row->$opPosition;
                                    $recaps[$accID][$jenis][$row->extern_id]['value_saldo'] = $row->$opPosition . "_akhir";

                                    $recaps[$accID][$jenis][$row->extern_id]['value'] = abs($recaps[$accID][$jenis][$row->extern_id]['value_in'] - $recaps[$accID][$jenis][$row->extern_id]['value_out']);

                                    $qtyField = "qty_" . $defPosition;
                                    $qtyOpField = "qty_" . $opPosition;
                                    if (isset($row->$qtyField)) {
                                        $recaps[$accID][$jenis][$row->extern_id]['qty_in'] += $row->$qtyField;
                                        $recaps[$accID][$jenis][$row->extern_id]['qty_out'] += $row->$qtyOpField;
                                        $recaps[$accID][$jenis][$row->extern_id]['qty_saldo'] = $row->$qtyOpField . "_akhir";
                                        $recaps[$accID][$jenis][$row->extern_id]['qty'] = abs($recaps[$accID][$jenis][$row->extern_id]['qty_in'] - $recaps[$accID][$jenis][$row->extern_id]['qty_out']);
                                    }

                                    //==identifying columns
                                    $srcs = array(
                                        "qty" => "qty",
                                        "value" => "value (IDR)",
                                    );
                                    foreach ($srcs as $key => $label) {
                                        if (isset($recaps[$accID][$jenis][$row->extern_id][$key]) && $recaps[$accID][$jenis][$row->extern_id][$key] > 0) {
                                            $columns[$accID][$jenis][$key] = $label;
                                        }
                                    }


                                }
                                //                                echo "ada mutasinya<br>";
                            }
                            else {
                                //                                echo "TAK ada mutasinya<br>";
                            }
                        }
                    }
                }
            }

        }

        //        arrprint($srcs);
        //        arrprint($columns);
        //        die();
        //        arrprint($recaps);
        //        die();
        //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

        //
        //region prepare params for viewer
        $subTitle = lgTranslateTime($date1) . " to " . lgTranslateTime($date2);
        if ($date1 == $date2) {
            $subTitle = lgTranslateTime($date1);
        }


        $thisTr = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->jenisTr;
        $thisTrName = isset($row->jenis_label) ? $row->jenis_label : $this->configUi[$jenisTr]["label"];
        $data = array(
            "mode" => $this->uri->segment(2),
            "isMobile" => $isMob,
            "jenisTr" => $jenisTr,
            "subJenisTr" => strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $jenisTr,
            //            "trName"               =>$this->configUi[$jenisTr]["label"],
            "trName" => $thisTrName,
            "errMsg" => $this->session->errMsg,
            "title" => (isset($subCodes) && isset($currentState) ? $subCodes[$currentState] : $this->jenisTrName) . " (" . $this->session->login['nama'] . ")",
            "subTitle" => $subTitle,
            //            "pageCount"            => $numPages,
            //            "page"                 => $page,
            //            "pages"                => $pages,
            "arrayHistoryLabels" => $historyFields,
            "arrayHistory" => $arrayHistory,
            "arrayHistoryId" => $arrayHistory_ids,

            "steps" => $steps,
            "stepLabels" => $stepLabels,
            "stepLinks" => $stepLinks,
            "addParams" => isset($_GET['addParams']) ? $_GET['addParams'] : null,
            "currentState" => isset($currentState) ? $currentState : "all states",
            "alternateLink" => base_url() . $this->uri->segment(1) . "/viewIncomplete/" . $this->uri->segment(3),
            "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" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4),
            //
            //            "availFilters"=>isset($this->config->item("heTransaksi_report")[$jenisTr]["availFilters"])?$this->config->item("heTransaksi_report")[$jenisTr]["availFilters"]:array(),"availFilters"=>isset($this->config->item("heTransaksi_report")[$jenisTr]["availFilters"])?$this->config->item("heTransaksi_report")[$jenisTr]["availFilters"]:array(),
            "availFilters" => isset($availFilters) ? $availFilters : array("oleh_id" => "person"),
            "names" => $names,
            "recaps" => $recaps,

            "trHeaders" => $trHeaders,
            "trHeaders_related" => $trHeaders_related,
            "trItems" => $trItems,
            "myItems" => $myItems,
            "followerItems" => $followerItems,


            "transLabels" => array(
                "label" => "activity name",
                "qty" => "times",
                "subtotal" => "amount",
            ),
            "trans" => $trans,
            "trans_mine" => $trans_mine,
            "trans_followers" => $trans_followers,
            //
            "columns" => $columns,

        );
        //endregion

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

    public function viewMySettlementORI()
    {
        $starttime = microtime(true);
        $jenisTr = $this->jenisTr;

        $this->jenisTrName = isset($this->configUi[$this->jenisTr]['steps'][1]['label']) ? $this->configUi[$this->jenisTr]['steps'][1]['label'] : "unnamed";

        $settlConfig = $this->config->item("heTransaksi_settlementGroups");
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();


        //region preparing ERP step labels for top link
        $steps = $this->configUi[$jenisTr]['steps'];
        $stepLabels = array(//            "0" => "all"
        );
        $stepLinks = array(//            "0" => base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3)
        );
        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['stateLabel'];
                    $stepLabels[$stepNumber] = $stepSpec['label'];
                    $stepLinks[$stepNumber] = base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $stepSpec['target'];
                }

            }

            //            $currentState = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->jenisTr;
            $currentState = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->configUi[$this->jenisTr]['steps'][1]['target'];
        }
        //endregion

        $historyFields = isset($this->config->item("heTransaksi_report")[$jenisTr]['longHistoryFields']) ? $this->config->item("heTransaksi_report")[$jenisTr]['longHistoryFields'] : array(
            "produk_nama" => "item name",
            "produk_ord_jml" => "qty",
            "produk_ord_hrg" => "@price",

            "nomer_top+nomer" => "receipt number",
            "oleh_nama+dtime" => "person",
        );
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }


        $trHeaders = isset($this->configUi[$jenisTr]['settlementHistoryFields']) ? $this->configUi[$jenisTr]['settlementHistoryFields'] : array(
            "dtime" => "time",
            "customers_nama" => "cutomer",
            "nomer" => "receipt number",
            "jenis_label" => "activity",
            "transaksi_nilai" => "orig. value",
            "add_disc" => "discount",
            "grand_total" => "nett",
        );
        $trItems = array();

        //
        //region getting trans-IDs
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->setFilters(array());

        $tr->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("gudang_id='" . $this->session->login['gudang_id'] . "'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->addFilter("link_id='0'");
        $tr->addFilter("transaksi.oleh_id='" . $this->session->login['id'] . "'");
        //        $tr->addFilter("transaksi.oleh_id='" . 205 . "'");

        //        $tr->addFilter("transaksi_registry.param='tableIn_master_values'");
        //        $tr->addFilter("transaksi.oleh_id='" . $uID . "'");

        // //region date filter
        // $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-d");
        // $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
        // $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) {
            //            arrprint($addParams);
            foreach ($addParams as $f) {
                $tr->addFilter($f);
            }
        }


        //region date filter
        $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-d");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
        $this->db->where("fulldate>='" . $date1 . "'");
        $this->db->where("fulldate<='" . $date2 . "'");
        //endregion


        $arrayHistory = array();
        $arrayHistory_ids = array();


        $trIDs = array();
        $tr0 = $tr;

        //        $this->db->order_by("transaksi.id");
        $tmpHistTrans = $tr->lookUpAll()->result();
        //        cekBiru($this->db->last_query());
        $indHis = array();
        foreach ($tmpHistTrans as $tmp_0) {
            $hist = blobdecode($tmp_0->indexing_registry);
            // $indHis[$tmp_0->id] = $hist['tableIn_master_values'];
            $indHis[] = $tmp_0->id;
        }
        //        cekHitam($this->db->last_query());
        //look up registry
        // $srcRegMain = $tr->lookupBaseRegistries($indHis)->result();
        $regData = array();
        if (sizeof($indHis) > 0) {
            $tr->setJointSelectFields("transaksi_id,tableIn_master_values");
            $srcRegMain = $tr->lookupBaseDataRegistries($indHis)->result();
            foreach ($srcRegMain as $registryData) {
                $regData[$registryData->transaksi_id] = blobDecode($registryData->tableIn_master_values);
            }
        }

        if (sizeof($tmpHistTrans) > 0) {
            foreach ($tmpHistTrans as $row) {
                if (!in_array($row->id, $trIDs)) {
                    //                    $trIDs[] = $row->transaksi_id;
                    $trIDs[] = $row->id;
                    $tmpCol = array();
                    $content = $regData[$row->id];
                    foreach ($trHeaders as $colName => $colLabel) {
                        if (isset($content[$colName])) {
                            $tmpCol[$colName] = $content[$colName];
                        }
                        else {
                            $tmpCol[$colName] = isset($row->$colName) ? $row->$colName : 0;
                        }

                    }
                    $trItems[] = $tmpCol;
                }
            }
        }
        //endregion


        //        matiHere();

        $accounts = array();
        $rels = array();
        $accountRecaps = array();

        $this->load->helper("he_mass_table");
        if (sizeof($mems) > 0) {
            foreach ($mems as $gID) {
                if (isset($settlConfig[$gID]) && sizeof($settlConfig[$gID]) > 0) {
                    foreach ($settlConfig[$gID] as $accID => $relPair) {
                        $accounts[$accID] = $accID;
                        foreach ($relPair as $comID => $comLabel) {
                            $rels[$accID][$comID] = $comLabel;
                        }
                    }
                }
            }
        }


        $names = array();
        $recaps = array();
        if (sizeof($trIDs) > 0) {
            if (sizeof($accounts) > 0) {
                foreach ($accounts as $accID => $rekName) {

                    if (isset($rels[$accID]) && sizeof($rels[$accID]) > 0) {

                        foreach ($rels[$accID] as $comID => $comLabel) {

                            if (!isset($names[$accID])) {
                                $names[$accID] = array();
                            }
                            if (!isset($recaps[$accID])) {
                                $recaps[$accID] = array();
                            }
                            $mdlName = "Com" . $comID;
                            $this->load->model("Coms/" . $mdlName);
                            $com = new $mdlName();

                            $com->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");


                            $defPosition = detectRekDefaultPosition($rekName);
                            $opPosition = $defPosition == "kredit" ? "debet" : "kredit";
                            $tmp = $com->fetchMovesByTransIDs($accID, $trIDs);

                            //                            echo $this->db->last_query();
                            if (sizeof($tmp) > 0) {
                                foreach ($tmp as $row) {
                                    if (!array_key_exists($row->extern_id, $names[$accID])) {
                                        $names[$accID][$row->extern_id] = $row->extern_nama;
                                    }
                                    if (!isset($recaps[$accID][$row->extern_id])) {
                                        $recaps[$accID][$row->extern_id] = array(
                                            "qty_in" => 0,
                                            "value_in" => 0,
                                            "qty_out" => 0,
                                            "value_out" => 0,
                                            "qty_saldo" => 0,
                                            "value_saldo" => 0,
                                        );
                                    }
                                    $recaps[$accID][$row->extern_id]['value_in'] += $row->$defPosition;
                                    $recaps[$accID][$row->extern_id]['value_out'] += $row->$opPosition;
                                    $recaps[$accID][$row->extern_id]['value_saldo'] = $row->$opPosition . "_akhir";

                                    $qtyField = "qty_" . $defPosition;
                                    $qtyOpField = "qty_" . $opPosition;
                                    if (isset($row->$qtyField)) {
                                        $recaps[$accID][$row->extern_id]['qty_in'] += $row->$qtyField;
                                        $recaps[$accID][$row->extern_id]['qty_out'] += $row->$qtyOpField;
                                        $recaps[$accID][$row->extern_id]['qty_saldo'] = $row->$qtyOpField . "_akhir";
                                    }

                                }
                                //                                echo "ada mutasinya<br>";
                            }
                            else {
                                //                                echo "TAK ada mutasinya<br>";
                            }
                        }
                    }


                }
            }

        }


        //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 = 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
        $subTitle = lgTranslateTime($date1) . " to " . lgTranslateTime($date2);
        if ($date1 == $date2) {
            $subTitle = lgTranslateTime($date1);
        }

        $accountsAlias = fetchAccountStructureAlias();
        $thisTr = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->jenisTr;
        $thisTrName = isset($row->jenis_label) ? $row->jenis_label : $this->configUi[$jenisTr]["label"];
        $data = array(
            "mode" => $this->uri->segment(3),
            "isMobile" => $isMob,
            "jenisTr" => $jenisTr,
            "subJenisTr" => strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $jenisTr,
            //            "trName"               => $this->configUi[$jenisTr]["label"],
            "trName" => $thisTrName,
            "errMsg" => $this->session->errMsg,
            "title" => (isset($subCodes) && isset($currentState) ? $subCodes[$currentState] : $this->jenisTrName) . " (" . $this->session->login['nama'] . ")",
            "subTitle" => $subTitle,
            //            "pageCount"            => $numPages,
            //            "page"                 => $page,
            //            "pages"                => $pages,
            "arrayHistoryLabels" => $historyFields,
            "arrayHistory" => $arrayHistory,
            "arrayHistoryId" => $arrayHistory_ids,

            "steps" => $steps,
            "stepLabels" => $stepLabels,
            "stepLinks" => $stepLinks,
            "addParams" => isset($_GET['addParams']) ? $_GET['addParams'] : null,
            "currentState" => isset($currentState) ? $currentState : "all states",
            "alternateLink" => MODUL_PATH . $this->uri->segment(1) . "/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_PATH . get_class($this) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4),
            //
            //            "availFilters"=>isset($this->config->item("heTransaksi_report")[$jenisTr]["availFilters"])?$this->config->item("heTransaksi_report")[$jenisTr]["availFilters"]:array(),"availFilters"=>isset($this->config->item("heTransaksi_report")[$jenisTr]["availFilters"])?$this->config->item("heTransaksi_report")[$jenisTr]["availFilters"]:array(),
            "availFilters" => isset($availFilters) ? $availFilters : array("oleh_id" => "person"),
            "names" => $names,
            "recaps" => $recaps,

            "trHeaders" => $trHeaders,
            "trItems" => $trItems,
            "accountAlias" => isset($accountsAlias) ? $accountsAlias : array(),

        );
        //endregion

        $endtime = microtime(true); // Bottom of page
        $val = $endtime - $starttime;
        //        cekHitam("execute time[ " . $val . " ] =>lanjut brooo");
        $this->load->view("history", $data);


    }

    public function viewMySettlement()
    {

//        arrPrint($this->session->login);
        // $autoconnectJenis = "759";
        $starttime = microtime(true);
        $jenisTr = $this->jenisTr;

        //region date filter

        //endregion
        $this->jenisTrName = isset($this->configUi[$this->jenisTr]['steps'][1]['label']) ? $this->configUi[$this->jenisTr]['steps'][1]['label'] : "unnamed";
        $connectedSettlement = isset($this->configUi[$this->jenisTr]["connectSettlement"]) ? $this->configUi[$this->jenisTr]["connectSettlement"] : array();
        $connectedSettlementFields = isset($this->configUi[$this->jenisTr]["settlementFields"]) ? $this->configUi[$this->jenisTr]["settlementFields"] : array();

        $settlConfig = $this->config->item("heTransaksi_settlementGroups");
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("oleh_id='" . $this->session->login['id'] . "'");
        $tr->addFilter("settlement_id='1'");
//        $tr->addFilter("settlement_id='3791'");
//        $tr->addFilter("settlement_id='3173'");
        $tr->addFilter("link_id='0'");
        $tr->addFilter("jenis='" . $jenisTr . "'");
        $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-d");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
//        $date1 = "2022-05-29";
//        $date2 = "2022-05-29";
        $this->db->where("fulldate>='" . $date1 . "'");
        $this->db->where("fulldate<='" . $date2 . "'");
        $tempTrans = $tr->lookUpAll()->result();

        //cekMErah($this->db->last_query());

        $ids = array();
        $settleData = array();
        if (sizeof($tempTrans) > 0) {
            foreach ($tempTrans as $tempData) {
                $ids[$tempData->id] = $tempData->id;
                $tNomer_top = $tempData->nomer_top;
                $cabang_id = $tempData->cabang_id;
                $oleh_id = $tempData->oleh_id;
                $tNomer = $tempData->nomer;
                $jenisTrtop = explode("-", $tNomer_top)[0];
                $jenisTrsub = explode("-", $tNomer)[0];
                // $counterjenis = "$jenisTrsub|" . $this->placeId;
                // cekMErah($jenisTrsub);
                $counterjenis = "$jenisTrsub|" . $this->placeId . "|" . $oleh_id;
                // cekHere($tNomer_top."$oleh_id");
                $arrIdHist = blobDecode($tempData->ids_his);
                $arrCounters = isset($arrIdHist[1]['counters']) ? blobDecode($arrIdHist[1]['counters']) : "";

                $counterIds_his = is_array($arrCounters) ? blobDecode(blobDecode($tempData->ids_his)[1]['counters']) : "";
                $counters = blobDecode($tempData->counters);

                // $counterGlobal = $counters['stepCode|placeID'][$counterjenis];
                $counterGlobal = $counters['stepCode|placeID|olehID'][$counterjenis];
//                 arrPrint($counters);
// cekMerah($counterGlobal);
// cekHitam("['stepCode|placeID|olehID'][$counterjenis");
// matiHere();
                $counterIds_his_global = isset($counterIds_his['stepCode|placeID|olehID']["$jenisTrtop|$cabang_id|$oleh_id"]) ? $counterIds_his['stepCode|placeID']["$jenisTrtop|$cabang_id"] : "";
                $cGlobals = digit_5($counterGlobal);
                $cGlobal_spo = digit_5($counterIds_his_global);
                // arrPrint($cGlobals);
                $settleTmpData = array();
                foreach ($connectedSettlementFields as $key => $label) {
                    if ($key == "nomer") {
                        $kolomValue_0s = formatField_he_format($key, $tempData->$key);
                        $kolomValues = str_replace("</span>", "&#x2011;" . $cGlobals, $kolomValue_0s);
                    }
                    else {
                        $kolomValues = formatField_he_format($key, $tempData->$key);
                    }
                    $settleTmpData[$key] = $kolomValues;
                }
                $settleData[] = $settleTmpData;

            }
        }

        //region history settle
        $relJenis = $connectedSettlement['target'];
        $configUiJenis = loadConfigModulJenis_he_misc("$relJenis", "coTransaksiUi");
//         arrPrint($configUiJenis);
        $tr->setFilters(array());
        $tr->addFilter("extern_id='" . $this->session->login['id'] . "'");
        $tr->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("jenis='" . $relJenis . "'");
        $tr->addFilter("target_jenis='" . $connectedSettlement["targetPayment"] . "'");

//        $this->db->where("dtime>='" . $date1 . "'");
//        $this->db->where("dtime<='" . $date2 . "'");
        $this->db->order_by("id", "desc");
        $this->db->limit(7);
        $tempPayment = $tr->lookUpPayment()->result();
//         cekMErah($this->db->last_query());
        $settlementHistoryFields = $configUiJenis["shortHistoryFields"];
        $settlementHistoryFieldsPending = $configUiJenis["shortHistoryFieldsPending"];

//        arrPrint($tempPayment);

        $arrayPending = array();
        $arrayHistory = array();
        if (sizeof($tempPayment) > 0) {
            foreach ($tempPayment as $tempHist) {
                if ($tempHist->tagihan == $tempHist->sisa ) {
                    //jadi outstanding
                    $iindexKey = "pending";
                }
                else {
                    //jadi history
                    $iindexKey = "history";
                }
                $tempPending = array();
                foreach ($settlementHistoryFields as $key => $keyLabel) {
                    $tempPending[$key] = $tempHist->$key;
                }
                if ($iindexKey == "pending") {
                    $tempPending["keterangan"] = "menunggu approval";
                }
                else {
                    $tempPending["keterangan"] = "diterima";
                }

                $arrayHistory[$iindexKey][] = $tempPending;
            }
        }
        //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 = 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
        $subTitle = lgTranslateTime($date1) . " to " . lgTranslateTime($date2);
        if ($date1 == $date2) {
            $subTitle = lgTranslateTime($date1);
        }

        // $accountsAlias = fetchAccountStructureAlias();
        $thisTr = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->jenisTr;
        $thisTrName = isset($row->jenis_label) ? $row->jenis_label : $this->configUi[$jenisTr]["label"];
        $data = array(
            "mode" => "viewSettlement",
            // "mode" =>"viewHistory",
            // "isMobile" => $isMob,
            "jenisTr" => $jenisTr,
            "subJenisTr" => strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $jenisTr,
            //            "trName"               => $this->configUi[$jenisTr]["label"],
            "trName" => $thisTrName,
            "errMsg" => $this->session->errMsg,
            "title" => "Settlement (" . $this->session->login['nama'] . ")",
            "subTitle" => $subTitle,
            //            "pageCount"            => $numPages,
            //            "page"                 => $page,
            //            "pages"                => $pages,
            "itemsLabel" => $connectedSettlementFields,
            "items" => $settleData,
            "settlementLink" => MODUL_PATH . "doSettlementPos/$jenisTr",
            "arrayHistoryLabels" => $settlementHistoryFields,
            "arrayHistoryLabelPending" => $settlementHistoryFieldsPending,
            "arrayHistory" => $arrayHistory,
            // "arrayHistoryId" => $arrayHistory_ids,
            //
            // "steps" => $steps,
            // "stepLabels" => $stepLabels,
            // "stepLinks" => $stepLinks,
            "addParams" => isset($_GET['addParams']) ? $_GET['addParams'] : null,
            "currentState" => isset($currentState) ? $currentState : "all states",
            "alternateLink" => MODUL_PATH . $this->uri->segment(1) . "/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_PATH . get_class($this) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4),
            "accountAlias" => isset($accountsAlias) ? $accountsAlias : array(),
            "preview_target" => MODUL_PATH . get_class($this) . "/previewSettlement/" . $jenisTr . "/" . $connectedSettlement["modul"] . "/" . $connectedSettlement["target"] . "?date1=$date1&date2=$date2",
            "action_target" => MODUL_PATH . get_class($this) . "/doSettlementPos/" . $jenisTr . "/" . $connectedSettlement["modul"] . "/" . $connectedSettlement["target"] . "?date1=$date1&date2=$date2",
            "action_label" => $connectedSettlement["btnLabel"],
        );
        //endregion

        $endtime = microtime(true); // Bottom of page
        $val = $endtime - $starttime;
        //        cekHitam("execute time[ " . $val . " ] =>lanjut brooo");
        $this->load->view("history", $data);

    }

    public function viewHistory2()
    {

        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;

        $currYear = isset($_GET['y']) ? $_GET['y'] : date("Y");
        $currMonth = isset($_GET['m']) ? $_GET['m'] : date("m");
        $dateStr = $currYear . "-" . $currMonth;
        $stID = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;
        $sID = isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter;
        $sID = isset($this->sID_alias[$sID]) ? $this->sID_alias[$sID] : "";
        // $subj
        // cekHitam($defaultStep . " " . $this->jenisTr);
        $steps = $this->configLayout[$this->jenisTr]['historicalReport'][$defaultStep]['tabs'];
        // arrPrint($steps);
        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
        }
        // arrPrint($stepNames);
        $currentState = strlen($this->uri->segment(4)) > 0 ? $this->uri->segment(4) : $this->configUi[$this->jenisTr]['steps'][1]['target'];
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->addFilter("jenis='" . $stID . "'");
        // if (isset($currentState)) {
        //     $tr->addFilter("jenis='" . $currentState . "'");
        // }

        //        $this->db->like('transaksi.dtime', $dateStr, 'after');
        $this->db->where("year(transaksi.dtime)='$currYear'");
        // $this->db->where("month(transaksi.dtime)='$currMonth'");
        $tmp = $tr->lookupJoined()->result();

        cekbiru($this->db->last_query());
        mati_disini();
        $trIds_ = array();
        $trIdDts = array();
        //region data dari registry untuk mendapatkan nilai nett1
        foreach ($tmp as $item) {
            $trIds_[$item->transaksi_id] = 1;
            $trIdDts[$item->transaksi_id]['dtime'] = $item->dtime;
            $trIdDts[$item->transaksi_id]['olehID'] = $item->oleh_id;
            $trIdDts[$item->transaksi_id]['cabangID'] = $item->cabang_id;
            $trIdDts[$item->transaksi_id]['pihakID'] = ($item->suppliers_id < 1 ? $item->customers_id : $item->suppliers_id);
        }
        // arrPrint($trIdDtimes_);
        $trIds = array_keys($trIds_);
        $idList = implode(",", $trIds);
        if (strlen($idList) > 3) {

            $tr_2 = new MdlTransaksi();
            $tr_2->setFilters(array());
            $tr_2->addFilter("transaksi_id in '(" . $idList . ")'");
            $tr_2->addFilter("param ='items'");
            $registries = $tr_2->lookupRegistries()->result();
            // cekHitam($this->db->last_query());
            // arrPrint($registries);
            $subNett = array();
            $subHarga = array();
            foreach ($registries as $registry) {
                // cekMerah($registry->transaksi_id);
                $trDtime = $trIdDts[$registry->transaksi_id]["dtime"];
                $trDtime_m = formatTanggal($trDtime, "Y-m");
                // cekMerah("$trDtime *** $trDtime_M");
                $regs = blobDecode($registry->values);
                // arrPrint($regs);
                // cekHijau($trDtime);
                // arrPrint($registry);

                $pihakIdDatasValues = array();
                foreach ($regs as $reg) {
                    $xsID = key_exists($sID, $trIdDts[$registry->transaksi_id]) ? $trIdDts[$registry->transaksi_id][$sID] : $reg[$sID];
                    // cekLime($xsID . " $trDtime_m" );
                    // arrPrint($reg);
                    // $pihakIdDatasValues[$reg['pihakID']] += $reg['nett1'];
                    // cekHitam($reg['pihakName'] . " " . $reg['pihakID'] . " == " . $reg['nett1']);
                    if (!isset($subNett[$trDtime_m][$xsID])) {
                        $subNett[$trDtime_m][$xsID] = 0;
                    }
                    if (isset($reg['nett1'])) {
                        $subNett[$trDtime_m][$xsID] += ($reg['nett1'] * $reg['jml']);
                    }
                    elseif (isset($reg['nett'])) {
                        $subNett[$trDtime_m][$xsID] += ($reg['nett'] * $reg['jml']);

                    }
                    else {
                        $subNett[$trDtime_m][$xsID] += (0);
                    }

                    // $subNett[$reg['pihakName']] += $reg['nett1'];

                    // cekHijau($reg['nett1'] . " net" );
                }
                // $pihakIdDatas['pihakID']
            }
        }
        //endregion

        $identifiers = $tr->fetchIdentifiers();


        $recaps = array();

        $dates = array();

        if (sizeof($tmp) > 0) {
            foreach ($tmp as $row) {
                if (sizeof($identifiers) > 0) {
                    $fulldate = substr($row->dtime, 0, 7);
                    $dates[$fulldate] = $fulldate;
                    $jenis = $row->jenis;
                    foreach ($identifiers as $iID => $iName) {


                        if (strlen($row->$iID) > 0 && strlen($row->$iName) > 0) {
                            //                            cekkuning("$iID/$iName");

                            if (!isset($names[$iID])) {
                                $names[$iID] = array();
                            }

                            $names[$iID][$row->$iID] = $row->$iName;
                            if (!isset($recaps[$jenis][$iID][$fulldate][$row->$iID])) {
                                $recaps[$jenis][$iID][$fulldate][$row->$iID] = array(
                                    "qty" => 0,
                                    "value" => 0,
                                );
                            }
                            // cekHitam($row->$iID);
                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['qty'] += $row->produk_ord_jml;
                            // $recaps[$jenis][$iID][$fulldate][$row->$iID]['value'] = ($row->produk_ord_jml * $row->produk_ord_hrg);
                            $recaps[$jenis][$iID][$fulldate][$row->$iID]['value'] = array_key_exists($row->$iID, $subNett[$fulldate]) ? $subNett[$fulldate][$row->$iID] : 0;
                        }


                    }

                }
            }
        }

        $months = array();
        for ($i = 1; $i <= 12; $i++) {
            if (strlen($i) < 2) {
                $i = "0" . $i;
            }
            $key = $currYear . "-" . $i;
            //            echo $i."<br>";
            //            $months[$i]=date("F", strtotime("Y-".$i."-d"));
            $months[$key] = $i;

        }
        //        arrprint($months);


        // $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        // $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        // $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;
        $selectedStep = isset($_GET['stID']) ? $_GET['stID'] : $defaultStep;

        //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[$this->jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion

        $data = array(
            "mode" => "recap",
            "title" => $this->configUi[$this->jenisTr]['label'] . " report",
            "subTitle" => "monthly, " . $currYear,
            "times" => $months,
            "timeLabel" => "months",
            "names" => isset($names) ? $names : array(),
            "recaps" => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => $this->configUi[$this->jenisTr]["label"],
            "availFilters" => $availFilters,
            "defaultFilter" => $defaultFilter,
            "selectedFilter" => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->jenisTr,
            "subPage" => base_url() . get_class($this) . "/viewDaily/" . $this->jenisTr,
            "historyPage" => base_url() . "Transaksi/viewHistory/" . $this->jenisTr . "?stID=" . $stID,
            "stepNames" => $stepNames,
            "defaultStep" => $defaultStep,
            "selectedStep" => $selectedStep,
            "addLink" => $addLink,
        );
        $this->load->view("activityReports", $data);

    }

    // function index(){
    //     // Load the member list view
    //     $this->load->view('activityReports');
    // }
    public function viewMonth()
    {
        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');
        }
        $reportingNetts = $this->config->item('heTransaksi_report')[$this->jenisTr]['reportingNett'];
        $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['fields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            $headers[] = array();
            $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }

        }
        $steps = $reportingNetts['tabs'];
        foreach ($steps as $step) {
            isset($step['jenis']) ? $fieldJenis[] = $step['jenis'] : "";
        }

        // arrPrint($fieldJenis);
        // arrPrint($reportingNetts['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fields);
        // arrPrint($steps);
        if ($this->session->login['cabang_id'] > 0) {
            $selectedCabang = "transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'";
        }
        else {
            $selectedCabang = "transaksi.cabang_id<>-1";
        }

        $stID = $this->uri->segment(3);
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();

        //        $defaultFilter = "year(dtime) = '$year' AND month(dtime) = '$month' AND cabang_id='" . $this->session->login['cabang_id'] . "' AND id_master>'0'";
        $defaultFilter = "year(dtime) = '$year' AND month(dtime) = '$month' AND $selectedCabang AND id_master>'0'";
        //region straight

        $tr->setFilters(array());
        $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->db->where("$defaultFilter");
        $tmps = $tr->lookupAll()->result();
        cekHijau($this->db->last_query());
        // arrPrint($fields);
        // arrPrint($fieldToshows);
        $lurusDatas = array();
        $trMainIds = array();
        if (sizeof($tmps) > 0) {
            foreach ($tmps as $tmp) {
                foreach ($fields as $kolom) {
                    $specs[$kolom] = $tmp->$kolom;
                }
                // foreach ($fieldToshows as $kolom => $fieldToshow) {
                //     $specs[$kolom] = $tmp->$kolom;
                // }

                if (in_array($tmp->jenis, $fieldJenis)) {
                    $lurusDatas[$tmp->jenis][$tmp->id] = $specs;
                    $trMainIds[] = $tmp->id;
                }

            }
        }
        //endregion

        // arrPrint($tmps);
        // arrPrint($lurusDatas);
        // mati_disini();

        // region return
        $tr->setFilters(array());
        $tr->addFilter("jenis_master ='" . $rJmaster . "'");
        $tr->addFilter("jenis ='" . $rJmaster . "'");
        $tr->db->where("$defaultFilter");
        $rTmps = $tr->lookupAll()->result();
        // cekMerah($this->db->last_query());

        $retDatas = array();
        $trRetIds = array();
        if (sizeof($rTmps) > 0) {
            foreach ($rTmps as $tmp) {
                foreach ($fields as $kolom => $fieldies) {

                }
                foreach ($fieldToshows as $kolom => $fieldToshow) {
                    $specs[$kolom] = $tmp->$kolom;
                }

                if ($tmp->jenis == $rJmaster) {
                    $retDatas[$tmp->jenis][$tmp->id] = $specs;
                    $trRetIds[] = $tmp->id;
                }
            }
        }
        // endregion return
        // arrPrint($rTmps);
        // arrPrint($retDatas);

        //region kompilasi data
        $jmlMain = sizeof($trMainIds);
        // $compDatas = array_merge($lurusDatas, $retDatas);
        $compDatas = ($lurusDatas + $retDatas);
        $jmlRet = sizeof($trRetIds);
        $jmlComp = sizeof($compDatas);
        // cekBiru("$jmlMain + $jmlRet = $jmlComp");
        //endregion kompilasi data
        // arrPrint($compDatas);

        $trIds = array_merge($trMainIds, $trRetIds);
        //region registries
        $listIds = implode("','", $trIds);
        // $tr->addFilter()
        // cekBiru($listIds);
        $tr->setFilters(array());
        $tr->addFilter("transaksi_id in ('" . $listIds . "')");
        $tr->addFilter("param ='main'");
        $regs = $tr->lookupRegistries()->result();
        // cekLime($this->db->last_query());
        // arrPrint($regs);
        $regDatas = array();
        foreach ($regs as $reg) {
            $trId = $reg->transaksi_id;
            // $refId = $reg->referenceID;
            $regValues = blobDecode($reg->values);
            // arrPrint($regValues);
            $regDatas[$trId]['nett1'] = $regValues['nett1'];
            $regDatas[$trId]['referenceID'] = isset($regValues['referenceID']) ? $regValues['referenceID'] : 0;
            // arrPrint($regValues);
        }
        //endregion
        // arrPrint($regDatas);
        /*
         * [13504] => Array
            (
                [nett1] => 16200000
            )
        */

        // mati_disini();


        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        $header['sales'] = "class='bg-info text-center'";
        $header['returns'] = "class='bg-info text-center'";
        $header['netto'] = "class='bg-info text-center'";


        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
            $headers[$num] = $header;
        }
        // endregion header
        // arrPrint($headers);

        // arrPrintWebs($fieldAttr);
        // arrPrintWebs($tmps);
        // mati_disini(__LINE__);
        // arrPrint($fieldToshows);
        // cekHitam(sizeof($compDatas));
        if (sizeof($compDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($compDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();
                foreach ($items as $transaksi_id => $item) {

                    // arrPrint($item);
                    // $step_number = $item->step_number;
                    // $tail_code = $item->tail_code;
                    // $tail_number = $item->tail_number;
                    $no++;
                    $specs['no']['value'] = $no;
                    $specs['no']['attr'] = "class='text-right'";
                    foreach ($fieldToshows as $kolom => $kolomAlias) {

                        if (isset($fieldFormat[$kolom])) {
                            $fValue = $fieldFormat[$kolom]($kolom, $item[$kolom]);
                        }
                        else {
                            $fValue = $item[$kolom];
                        }


                        if (isset($fieldLink[$kolom])) {
                            $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $item['id'] . "' > " . $fValue . "</a > ";
                        }
                        else {

                            $specs[$kolom]['value'] = $fValue;
                        }

                        $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                        $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                    }

                    $referenceID = $regDatas[$transaksi_id]['referenceID'];
                    $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                    //region builder saldo berjalan
                    $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                    //endregion

                    // region sales
                    $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                    $specs['sales']['attr'] = "class='text-right'";
                    $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                    // endregion sales

                    // region return
                    $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                    $specs['return']['attr'] = "class='text-right'";
                    $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                    // endregion return

                    // region netto berjalan
                    $specs['netto']['value'] = formatField("number", $netto);
                    $specs['netto']['attr'] = "class='text-right'";
                    // endregion netto berjalan

                    // arrPrint($specs);
                    // arrPrint($steps);
                    if ($trJenis == "982") {
                        $rSpecs[] = $specs;
                    }
                    if ($trJenis == "582spd") {
                        $spdSpecs[] = $specs;
                    }
                    // $compSpecs = array();
                    // foreach ($steps as $num => $nSpec) {
                    //     // arrPrint($nSpec);
                    //     $nJenis = $nSpec['jenis'];
                    //     if ($nJenis == $trJenis) {
                    //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                    //         if($nJenis == "582spd"){
                    //             $spdSpecs = $specs;
                    //             // arrPrint($compSpecs);
                    //             arrPrint($rSpecs);
                    //             cekHere();
                    //         }
                    //         else{
                    //             $compSpecs = $specs;
                    //         }
                    //
                    //         $compSpecs2 = $rSpecs + $spdSpecs;
                    //         $bodies[$num][] = $compSpecs2;
                    //     }
                    //     // else{
                    //     //     $bodies[$num][] = $specs;
                    //     // }
                    //     arrPrint($rSpecs);
                    // }
                }
            }
            //endregion


            foreach ($steps as $num => $nSpec) {
                $bodies[$num] = array_merge($spdSpecs, $rSpecs);
            }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";
        // arrPrint($rSpecs);
        // arrPrint($spdSpecs);
        // arrPrint($bodies);
        // arrPrint($footers);
        // cekHijau($sumNetto);
        // mati_disini();
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }


        // mati_disini();
        $data = array(
            "mode" => "reporting",
            "title" => $this->configUi[$this->jenisTr]['label'] . " report",
            "subTitle" => "",
            // "times"            => $months,
            "tblHeadings" => $headers,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            // "recaps"           => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => $this->configUi[$this->jenisTr]["label"],
            // "availFilters"     => $availFilters,
            // "defaultFilter"    => $defaultFilter,
            // "selectedFilter"   => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => base_url() . get_class($this) . " / " . $this->uri->segment(2) . " / " . $this->jenisTr,
            "subPage" => base_url() . get_class($this) . " / viewDaily / " . $this->jenisTr,
            "historyPage" => base_url() . "Transaksi / viewHistory / " . $this->jenisTr . " ? stID = " . $stID,
            "stepNames" => $stepNames,
            // "defaultStep"      => $defaultStep,
            // "selectedStep"     => $selectedStep,
            // "addLink"          => $addLink,
        );
        $this->load->view("activityReports", $data);
    }

    public function viewHistory()
    {
        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;

        $historicalReports = $this->config->item('heTransaksi_report')[$this->jenisTr]['historicalReport'][$defaultStep];

        $fields = array();
        $headers = array();
        $bodies = array();
        foreach ($historicalReports['fields'] as $field => $fChilds) {
            $headers[] = array();
            $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }
        }
        $steps = $historicalReports['tabs'];

        // arrPrint($historicalReports['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fields);
        // arrPrint($steps);


        $stID = $this->uri->segment(4);
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        // $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        // $tr->addFilter("jenis_master='" . $this->jenisTr . "'");
        $tr->setFilters(array());
        $tr->db->where("id_master>'0' AND jenis='" . $stID . "'");

        $data = $row = array();

        // Fetch member's records
        $tmps = $tr->lookupAll()->result();
        // cekHijau($this->db->last_query());

        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
            $headers[$num] = $header;
        }
        // $headers[2] = $header;
        // endregion header

        // arrPrintWebs($tmps);
        //region bodies
        $no = 0;
        foreach ($tmps as $item) {
            $step_avail = $item->step_avail;
            $step_number = $item->step_number;
            $tail_code = $item->tail_code;
            $tail_number = $item->tail_number;
            $no++;
            $specs['no']['value'] = $no;
            $specs['no']['attr'] = "class='text-right'";
            foreach ($fieldToshows as $kolom => $kolomAlias) {

                if (isset($fieldFormat[$kolom])) {
                    $fValue = $fieldFormat[$kolom]($kolom, $item->$kolom);
                }
                else {
                    $fValue = $item->$kolom;
                }


                if (isset($fieldLink[$kolom])) {
                    $specs[$kolom]['value'] = "<a href='" . base_url() . $fieldLink[$kolom] . $item->id . "'>" . $fValue . "</a>";
                }
                else {

                    $specs[$kolom]['value'] = $fValue;
                }

                $warna = (($kolom == "trash") && ($fValue == 0)) ? "text-red" : "";

                $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";
            }

            $bodies[1][] = $specs;

            /*-----------------------------------
             * transaksi yg sukses
             * ---------------------------------*/
            if (($item->step_current > 0) && ($item->step_current <= $step_avail)) {
                $bodies[2][] = $specs;
            }

            /*-----------------------------------
             * transaksi yg dihapus
             * ---------------------------------*/
            if ($step_number == 0) {
                $bodies[3][] = $specs;
            }

            /*-----------------------------------
             * transaksi yg telah selesai
             * ---------------------------------*/
            if ($item->step_current == $step_avail) {
                // if (($tail_number == $step_avail)) {
                $bodies[4][] = $specs;
            }
            /*-----------------------------------
             * transaksi yg belum selesai
            * ---------------------------------*/
            if (($item->step_current > 0) && ($tail_number == $step_avail)) {
                // if (($tail_number == $step_avail)) {
                $bodies[5][] = $specs;
            }


        }
        //endregion
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }


        // mati_disini();
        $data = array(
            "mode" => "historical",
            "title" => $this->configUi[$this->jenisTr]['label'] . " report",
            "subTitle" => "",
            // "times"            => $months,
            "tblHeadings" => $headers,
            "tblBodies" => $bodies,
            "names" => isset($names) ? $names : array(),
            // "recaps"           => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => $this->configUi[$this->jenisTr]["label"],
            // "availFilters"     => $availFilters,
            // "defaultFilter"    => $defaultFilter,
            // "selectedFilter"   => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->jenisTr,
            "subPage" => base_url() . get_class($this) . "/viewDaily/" . $this->jenisTr,
            "historyPage" => base_url() . "Transaksi/viewHistory/" . $this->jenisTr . "?stID=" . $stID,
            "stepNames" => $stepNames,
            // "defaultStep"      => $defaultStep,
            // "selectedStep"     => $selectedStep,
            // "addLink"          => $addLink,
        );
        $this->load->view("activityReports", $data);
    }

    public function viewSales()
    {
        arrPrint($this->uri->segment_array());
        $availFilters = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['availFilters'] : array();
        $defaultFilter = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultFilter'] : "oleh_id";
        $defaultStep = isset($this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep']) ? $this->config->item("heTransaksi_report")[$this->jenisTr]['defaultStep'] : $this->jenisTr;
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');
        }
        $reportingNetts = $this->config->item('report')['penjualan'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            $headers[] = array();
            $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }

        }
        // $steps = $reportingNetts['tabs'];
        // foreach ($steps as $step) {
        //     isset($step['jenis']) ? $fieldJenis[] = $step['jenis'] : "";
        // }

        // arrPrint($fieldJenis);
        // arrPrint($reportingNetts['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fieldAttrHeader);
        // arrPrint($fields);
        // arrPrint($steps);
        // matiHere(__METHOD__ . " @" . __LINE__);

        $stID = $this->uri->segment(3);
        $tr = new MdlTransaksi();
        $rp = new MdlReport();
        $db2 = $this->load->database('report', TRUE);
        // region sales

        // $rp->setDebug(true);
        // $condites = array(
        //   "periode" => "bulanan",
        // );
        // $db2->where($condites);
        $rp->setCondites(array("subject_id" => $this->session->login['id'], "th" => $year, "bl" => $month));
        $srScr = $rp->lookupSalesMonthly()->result();
        // arrPrint($srScr);

        foreach ($srScr as $dSources) {

            !isset($sumCabang) ? $sumCabang = array() : $sumCabang[$cabang_id] - +$nilai_af;
            !isset($sumSubject) ? $sumSubject = array() : $sumSubject[$subject_id] - +$nilai_af;
        }
        // endregion sales

        $compDatas = $srScr;
        // arrPrint($compDatas);
        // mati_disini();

        // arrPrintWebs($fieldToshows );
        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header
        // arrPrint($header);

        // arrPrintWebs($fieldAttr);
        // arrPrintWebs($tmps);
        // mati_disini(__LINE__);
        // arrPrint($fieldToshows);
        // cekHitam(sizeof($compDatas));
        if (sizeof($compDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($compDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                    }
                    else {
                        $fValue = $items->$kolom;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {

                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // $referenceID = $regDatas[$transaksi_id]['referenceID'];
                // $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                // //region builder saldo berjalan
                // $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                // //endregion

                // // region sales
                // $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                // $specs['sales']['attr'] = "class='text-right'";
                // $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                // // endregion sales

                // // region return
                // $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                // $specs['return']['attr'] = "class='text-right'";
                // $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                // // endregion return

                // // region netto berjalan
                // $specs['netto']['value'] = formatField("number", $netto);
                // $specs['netto']['attr'] = "class='text-right'";
                // // endregion netto berjalan

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }
                // $compSpecs = array();
                // foreach ($steps as $num => $nSpec) {
                //     // arrPrint($nSpec);
                //     $nJenis = $nSpec['jenis'];
                //     if ($nJenis == $trJenis) {
                //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                //         if($nJenis == "582spd"){
                //             $spdSpecs = $specs;
                //             // arrPrint($compSpecs);
                //             arrPrint($rSpecs);
                //             cekHere();
                //         }
                //         else{
                //             $compSpecs = $specs;
                //         }
                //
                //         $compSpecs2 = $rSpecs + $spdSpecs;
                //         $bodies[$num][] = $compSpecs2;
                //     }
                //     // else{
                $bodies[] = $specs;
                //     // }
                //     arrPrint($rSpecs);
                // }

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";
        // arrPrint($rSpecs);
        // arrPrint($spdSpecs);
        // arrPrint($bodies);
        // arrPrint($footers);
        // cekHijau($sumNetto);
        // mati_disini();
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }


        // mati_disini();
        $data = array(
            "mode" => "viewSales",
            "title" => key($this->config->item("report")),
            "subTitle" => "",
            // "times"            => $months,
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            // "recaps"           => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => "",
            // "availFilters"     => $availFilters,
            // "defaultFilter"    => $defaultFilter,
            // "selectedFilter"   => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            // "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            // "thisPage"         => base_url() . get_class($this) . " / " . $this->uri->segment(2) . " / " . $this->jenisTr,
            // "subPage"          => base_url() . get_class($this) . " / viewDaily / " . $this->jenisTr,
            // "historyPage"      => base_url() . "Transaksi / viewHistory / " . $this->jenisTr . " ? stID = " . $stID,
            // "stepNames"        => $stepNames,
            // "defaultStep"      => $defaultStep,
            // "selectedStep"     => $selectedStep,
            // "addLink"          => $addLink,
        );
        $this->load->view("activityReports", $data);
    }

    public function viewPreSalesAll()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');

            $condite = array("th" => $year, "bl" => $month);

            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }
        elseif (isset($_GET['year'])) {
            $year = $_GET['year'];

            $condite = array("th" => $year);
            $bulan = "$year-$month";
            $bulan_f = $year;
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');

            $condite = array("th" => $year, "bl" => $month);
            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }

        $reportingNetts = $this->config->item('report')['pre_penjualan'];
        $confReportCabang = $reportingSumCabang = $this->config->item('report')['pre_penjualan_cabang'];
        $confReportSubject = $reportingSumSubject = $reportingSumSeller = $this->config->item('report')['pre_penjualan_seller'];
        $confReportObject = $reportingSumObject = $reportingSumProduct = $this->config->item('report')['pre_penjualan_produk'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }

        }
        foreach ($reportingSumCabang['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $cbFields[] = $field;
            if (isset($fChilds['label'])) {
                $cbFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $cbFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $cbFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $cbFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $cbFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumSeller['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $sFields[] = $field;
            if (isset($fChilds['label'])) {
                $sFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $sFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $sFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $sFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $sFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumObject['mdlFields'] as $field => $fChilds) {
            $pFields[] = $field;
            if (isset($fChilds['label'])) {
                $pFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $pFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $pFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $pFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $pFieldFormat[$field] = $fChilds['format'];
            }
            if (isset($fChilds['sum_rows'])) {
                $pFieldSumrows[$field] = $fChilds['sum_rows'];
            }
        }
        // $steps = $reportingNetts['tabs'];
        // foreach ($steps as $step) {
        //     isset($step['jenis']) ? $fieldJenis[] = $step['jenis'] : "";
        // }

        // arrPrint($fieldJenis);
        // arrPrint($reportingNetts['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fieldAttrHeader);
        // arrPrint($fields);
        // arrPrint($steps);
        // matiHere(__METHOD__ . " @" . __LINE__);

        $stID = $this->uri->segment(3);
        $sm = new MdlEmployeeCabang();
        $tr = new MdlTransaksi();
        $rp = new MdlReport();
        // $db2 = $this->load->database('report', TRUE);
        // region sales
        $srcSm = $sm->lookupSeller();
        // showLast_query("lime");
        $sMans = $srcSm->raws->result();
        $sKoloms = $srcSm->koloms;
        $slFields = array();
        foreach ($sKoloms as $field => $fieldParams) {
            $slFields[] = $field;
        }

        foreach ($sMans as $sMan) {
            foreach ($slFields as $kolom) {
                $$kolom = $sMan->$kolom;
            }

            $sellers[$id] = $nama;
        }
        // arrPrint($srcSm);
        // arrPrint($slFields);
        // arrPrint($sellerIds);
        // arrPrint($sMans);
        // arrPrint($sellers);

        // $rp->setDebug(true);
        // $condite = array("th" => $year, "bl" => $month);
        // $condite = "th >= '$year' and bl >= '$month' ";
        // $condite = "th >= '$year' and bl >= '11' ";
        my_cabang_id() > 0 ? $condite["cabang_id"] = my_cabang_id() : "";
        // arrPrint($condite);

        $rp->setCondites($condite);
        // $rp->setDebug(true);
        $srScr = $rp->lookupPreSalesMonthly()->result();
        $cancelScr = $rp->lookupPreSalesCanceledMonthly()->result();
        // showLast_query("lime");
        // cekMerah($this->db->last_query());
        // endregion sales
        // arrPrint($srScr);
        // arrPrint($cancelScr);
        // arrPrint($sFields);
        // arrPrint($cbFields);
        // arrPrint($pFieldSumrows);
        $koloms = array_unique(array_merge($cbFields, $sFields, $pFields));
        $subjects = array();
        $cabangs = array();
        $sumSubjects = array();

        // arrPrint($dSources);
        // arrPrint($koloms);
        //region pre So
        foreach ($srScr as $dSources) {
            foreach ($koloms as $kolom) {
                $$kolom = trim($dSources->$kolom);
            }

            //region summary cabang
            if (!isset($sumCabang[$cabang_id]["nilai_in"])) {
                $sumCabang[$cabang_id]["nilai_in"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_in"] += $nilai_in;

            if (!isset($sumCabang[$cabang_id]["nilai_ot"])) {
                $sumCabang[$cabang_id]["nilai_ot"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot"] += $nilai_ot;

            if (!isset($sumCabang[$cabang_id]["nilai_af"])) {
                $sumCabang[$cabang_id]["nilai_af"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary subject
            if (!isset($sumSubject[$subject_id]["nilai_in"])) {
                $sumSubject[$subject_id]["nilai_in"] = 0;
            }
            $sumSubject[$subject_id]["nilai_in"] += $nilai_in;

            if (!isset($sumSubject[$subject_id]["nilai_ot"])) {
                $sumSubject[$subject_id]["nilai_ot"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot"] += $nilai_ot;
            if (!isset($sumSubject[$subject_id]["nilai_af"])) {
                $sumSubject[$subject_id]["nilai_af"] = 0;
            }
            $sumSubject[$subject_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary object
            foreach ($pFieldSumrows as $sumField => $sumStat) {

                if (!isset($sumObject[$object_id][$sumField])) {
                    $sumObject[$object_id][$sumField] = 0;
                }
                $sumObject[$object_id][$sumField] += $$sumField;

            }
            //endregion

            $sumCabang[$cabang_id]["cabang_nama"] = $cabang_nama;
            $sumSubject[$subject_id]["subject_nama"] = $subject_nama;
            $sumObject[$object_id]["object_kode"] = $object_kode;
            $sumObject[$object_id]["object_nama"] = $object_nama;
        }

        foreach ($sellers as $sId => $sNama) {
            $sumSubject[$sId]["subject_nama"] = $sNama;
        }
        //endregion


        $revertCancel = array(
            "unit_ot" => "unit_in",
            "unit_in" => "unit_ot",
            "nilai_in" => "nilai_ot",
            "nilai_ot" => "nilai_in",
            "nilai_af" => "nilai_afc",
            "unit_af" => "unit_afc",
        );
        // region caceled
        foreach ($cancelScr as $dSources) {
            foreach ($koloms as $kolom) {
                $$kolom = trim($dSources->$kolom);
            }

            //region summary cabang
            if (!isset($sumCabangCancel[$cabang_id]["nilai_in"])) {
                $sumCabangCancel[$cabang_id]["nilai_in"] = 0;
            }
            $sumCabangCancel[$cabang_id]["nilai_in"] += $nilai_in;

            if (!isset($sumCabangCancel[$cabang_id]["nilai_ot"])) {
                $sumCabangCancel[$cabang_id]["nilai_ot"] = 0;
            }
            $sumCabangCancel[$cabang_id]["nilai_ot"] += $nilai_ot;

            if (!isset($sumCabang[$cabang_id]["nilai_in"])) {
                $sumCabang[$cabang_id]["nilai_in"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_in"] += $nilai_ot;

            if (!isset($sumCabangCancel[$cabang_id]["nilai_af"])) {
                $sumCabangCancel[$cabang_id]["nilai_af"] = 0;
            }
            $sumCabangCancel[$cabang_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary subject
            if (!isset($sumSubjectCancel[$subject_id]["nilai_in"])) {
                $sumSubjectCancel[$subject_id]["nilai_in"] = 0;
            }
            $sumSubjectCancel[$subject_id]["nilai_in"] += $nilai_in;

            if (!isset($sumSubject[$subject_id]["nilai_in"])) {
                $sumSubject[$subject_id]["nilai_in"] = 0;
            }
            $sumSubject[$subject_id]["nilai_in"] += $nilai_ot;

            // ==================

            if (!isset($sumSubjectCancel[$subject_id]["nilai_ot"])) {
                $sumSubjectCancel[$subject_id]["nilai_ot"] = 0;
            }
            $sumSubjectCancel[$subject_id]["nilai_ot"] += $nilai_ot;

            if (!isset($sumSubject[$subject_id]["nilai_ot"])) {
                $sumSubject[$subject_id]["nilai_ot"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot"] += $nilai_in;

            // ==============

            if (!isset($sumSubjectCancel[$subject_id]["nilai_af"])) {
                $sumSubjectCancel[$subject_id]["nilai_af"] = 0;
            }
            $sumSubjectCancel[$subject_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary object
            foreach ($pFieldSumrows as $sumField_0 => $sumStat) {

                if (array_key_exists($sumField_0, $revertCancel)) {
                    $sumField = $revertCancel[$sumField_0];
                }
                else {
                    $sumField = $sumField_0;
                }

                if (!isset($sumObject_1[$object_id][$sumField])) {
                    $sumObject_1[$object_id][$sumField] = 0;
                }

                $sumObject_1[$object_id][$sumField] += $$sumField_0;

            }
            //endregion

            $sumObject_1[$cabang_id]["cabang_nama"] = $cabang_nama;
            $sumObject_1[$subject_id]["subject_nama"] = $subject_nama;
            $sumObject_1[$object_id]["object_kode"] = $object_kode;
            $sumObject_1[$object_id]["object_nama"] = $object_nama . " " . $subject_id;
        }

        foreach ($sumObject_1 as $proId => $proSpecs) {
            $sumObject[$proId] = $proSpecs;
        }
        // endregion caceled

        foreach ($sumCabang as $cbId => $cbItems) {
            $sumNett = $cbItems["nilai_ot"] - $cbItems['nilai_in'];

            // cekHitam("$sumNett = ".$cbItems["nilai_in"]." - ". $cbItems['nilai_ot']);

            $sumCabang_2[$cbId] = $cbItems;
            $sumCabang_2[$cbId]["nilai_af"] = $sumNett;
        }

        $sumSubject_2 = array();
        foreach ($sumSubject as $subjId => $subjItems) {
            $nilai_ot = isset($subjItems["nilai_ot"]) ? $subjItems["nilai_ot"] : 0;
            $nilai_in = isset($subjItems['nilai_in']) ? $subjItems['nilai_in'] : 0;

            $sumSubjNett = $nilai_ot - $nilai_in;
            // $sumSubjNett = $subjItems["nilai_ot"] - $subjItems['nilai_in'];

            // cekHitam("$sumSubjNett = $nilai_ot - $nilai_in");

            $sumSubject_2[$subjId] = $subjItems;
            $sumSubject_2[$subjId]["nilai_af"] = $sumSubjNett;
        }

        $sumObject_2 = array();
        foreach ($sumObject as $objId => $objItems) {

            $unit_ot = isset($objItems["unit_ot"]) ? $objItems["unit_ot"] : 0;
            $unit_in = isset($objItems['unit_in']) ? $objItems['unit_in'] : 0;
            $nilai_ot = isset($objItems["nilai_ot"]) ? $objItems["nilai_ot"] : 0;
            $nilai_in = isset($objItems['nilai_in']) ? $objItems['nilai_in'] : 0;

            $sumObjNett = $nilai_ot - $nilai_in;
            $sumObjUnitNett = $unit_ot - $unit_in;
            // $sumSubjNett = $subjItems["nilai_ot"] - $subjItems['nilai_in'];

            // cekHitam("$sumObjUnitNett = $unit_ot - $unit_in");

            $sumObject_2[$objId] = $objItems;
            $sumObject_2[$objId]["nilai_af"] = $sumObjNett;
            $sumObject_2[$objId]["unit_af"] = $sumObjUnitNett;
        }

        // arrPrint($sumSubject);
        // arrPrintWebs($sumObject_1);
        // arrPrintWebs($sumObject);
        // arrPrintWebs($sumCabang);
        // arrPrint($sumCabang_2);
        // arrPrint($sumObjectCancel);
        // arrPrintWebs($sumObject_2);
        // arrPrint($sumObject);
        // region headerCabang
        $cbHeader['no'] = "class='bg-info text-center'";
        foreach ($cbFieldToshows as $kolom => $kolomAlias) {
            $cbHeader[$kolomAlias] = "class='bg-info text-center'";

        }
        // endregion header

        // $summaryCabang = array(
        //   "cabangs" => $cabangs,
        //   "cabangs" => $cabangs,
        // );
        // arrPrint($cabangs);
        // arrPrint($sumCabang);
        // arrPrint($sumCabangCancel);
        // arrPrint($sumSubject);
        // matiHere(__METHOD__);
        $compDatas = $srScr;
        // arrPrint($compDatas);
        // mati_disini();

        // arrPrintWebs($fieldToshows );
        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header
        // arrPrint($header);

        // arrPrintWebs($fieldAttr);
        // arrPrintWebs($tmps);
        // mati_disini(__LINE__);
        // arrPrint($fieldToshows);
        // cekHitam(sizeof($compDatas));
        if (sizeof($compDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($compDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                    }
                    else {
                        $fValue = $items->$kolom;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {

                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // $referenceID = $regDatas[$transaksi_id]['referenceID'];
                // $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                // //region builder saldo berjalan
                // $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                // //endregion

                // // region sales
                // $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                // $specs['sales']['attr'] = "class='text-right'";
                // $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                // // endregion sales

                // // region return
                // $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                // $specs['return']['attr'] = "class='text-right'";
                // $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                // // endregion return

                // // region netto berjalan
                // $specs['netto']['value'] = formatField("number", $netto);
                // $specs['netto']['attr'] = "class='text-right'";
                // // endregion netto berjalan

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }
                // $compSpecs = array();
                // foreach ($steps as $num => $nSpec) {
                //     // arrPrint($nSpec);
                //     $nJenis = $nSpec['jenis'];
                //     if ($nJenis == $trJenis) {
                //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                //         if($nJenis == "582spd"){
                //             $spdSpecs = $specs;
                //             // arrPrint($compSpecs);
                //             arrPrint($rSpecs);
                //             cekHere();
                //         }
                //         else{
                //             $compSpecs = $specs;
                //         }
                //
                //         $compSpecs2 = $rSpecs + $spdSpecs;
                //         $bodies[$num][] = $compSpecs2;
                //     }
                //     // else{
                $bodies[] = $specs;
                //     // }
                //     arrPrint($rSpecs);
                // }

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";
        // arrPrint($rSpecs);
        // arrPrint($spdSpecs);
        // arrPrint($bodies);
        // arrPrint($footers);
        // cekHijau($sumNetto);
        // mati_disini();
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }


        // mati_disini();
        // $bulan = "$year-$month";
        // $bulan_f = formatTanggal($bulan, 'Y F');
        // cekMerah($bulan_f ." ". $bulan);
        $data = array(
            "mode" => "viewSales",
            "title" => $reportingNetts['title'],
            "subTitle" => "$bulan_f",
            "confReportCabang" => $confReportCabang,
            "confReportSubject" => $confReportSubject,
            "confReportObject" => $confReportObject,
            // "sumCabang"         => isset($sumCabang) ? $sumCabang : array(),
            "sumCabang" => isset($sumCabang_2) ? $sumCabang_2 : array(),
            // "sumSubject"        => isset($sumSubject) ? $sumSubject : array(),
            "sumSubject" => isset($sumSubject_2) ? $sumSubject_2 : array(),
            "sumObject" => isset($sumObject_2) ? array_filter($sumObject_2) : array(),
            // "sumObject"         => isset($sumObject) ? $sumObject : array(),
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            "jenisTr" => $this->jenisTr,
            "trName" => "",
        );
        $this->load->view("activityReports", $data);
    }

    public function viewSalesAll()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');

            $condite = array("th" => $year, "bl" => $month);

            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }
        elseif (isset($_GET['year'])) {
            $year = $_GET['year'];

            $condite = array("th" => $year);
            $bulan = "$year-$month";
            $bulan_f = $year;
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');

            $condite = array("th" => $year, "bl" => $month);
            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }

        $reportingNetts = $this->config->item('report')['penjualan'];
        $confReportCabang = $reportingSumCabang = $this->config->item('report')['penjualan_cabang'];
        $confReportSubject = $reportingSumSubject = $reportingSumSeller = $this->config->item('report')['penjualan_seller'];
        $confReportObject = $reportingSumObject = $reportingSumProduct = $this->config->item('report')['penjualan_produk'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }

        }
        foreach ($reportingSumCabang['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $cbFields[] = $field;
            if (isset($fChilds['label'])) {
                $cbFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $cbFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $cbFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $cbFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $cbFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumSeller['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $sFields[] = $field;
            if (isset($fChilds['label'])) {
                $sFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $sFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $sFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $sFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $sFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumObject['mdlFields'] as $field => $fChilds) {
            $pFields[] = $field;
            if (isset($fChilds['label'])) {
                $pFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $pFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $pFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $pFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $pFieldFormat[$field] = $fChilds['format'];
            }
            if (isset($fChilds['sum_rows'])) {
                $pFieldSumrows[$field] = $fChilds['sum_rows'];
            }
        }
        // $steps = $reportingNetts['tabs'];
        // foreach ($steps as $step) {
        //     isset($step['jenis']) ? $fieldJenis[] = $step['jenis'] : "";
        // }

        // arrPrint($fieldJenis);
        // arrPrint($reportingNetts['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fieldAttrHeader);
        // arrPrint($fields);
        // arrPrint($steps);
        // matiHere(__METHOD__ . " @" . __LINE__);

        $stID = $this->uri->segment(3);
        $sm = new MdlEmployeeCabang();
        $tr = new MdlTransaksi();
        $rp = new MdlReport();
        // $db2 = $this->load->database('report', TRUE);
        // region sales
        $srcSm = $sm->lookupSeller();
        // showLast_query("lime");
        $sMans = $srcSm->raws->result();
        $sKoloms = $srcSm->koloms;
        $slFields = array();
        foreach ($sKoloms as $field => $fieldParams) {
            $slFields[] = $field;
        }

        foreach ($sMans as $sMan) {
            foreach ($slFields as $kolom) {
                $$kolom = $sMan->$kolom;
            }

            $sellers[$id] = $nama;
        }
        // arrPrint($srcSm);
        // arrPrint($slFields);
        // arrPrint($sellerIds);
        // arrPrint($sMans);
        // arrPrint($sellers);

        // $rp->setDebug(true);
        // $condite = array("th" => $year, "bl" => $month);
        my_cabang_id() > 0 ? $condite["cabang_id"] = my_cabang_id() : "";
        // arrPrint($condite);

        $rp->setCondites($condite);
        $srScr = $rp->lookupSalesMonthly()->result();
        // showLast_query("lime");
        // cekMerah($this->db->last_query());
        // endregion sales
        // arrPrint($srScr);
        // arrPrint($sFields);
        // arrPrint($cbFields);
        // arrPrint($pFieldSumrows);
        $koloms = array_unique(array_merge($cbFields, $sFields, $pFields));
        $subjects = array();
        $cabangs = array();
        $sumSubjects = array();

        // arrPrint($dSources);
        // arrPrint($koloms);
        foreach ($srScr as $dSources) {
            foreach ($koloms as $kolom) {
                $$kolom = trim($dSources->$kolom);
            }

            //region summary cabang
            if (!isset($sumCabang[$cabang_id]["nilai_in"])) {
                $sumCabang[$cabang_id]["nilai_in"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_in"] += $nilai_in;

            if (!isset($sumCabang[$cabang_id]["nilai_ot"])) {
                $sumCabang[$cabang_id]["nilai_ot"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot"] += $nilai_ot;

            if (!isset($sumCabang[$cabang_id]["nilai_af"])) {
                $sumCabang[$cabang_id]["nilai_af"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary subject
            if (!isset($sumSubject[$subject_id]["nilai_in"])) {
                $sumSubject[$subject_id]["nilai_in"] = 0;
            }
            $sumSubject[$subject_id]["nilai_in"] += $nilai_in;

            if (!isset($sumSubject[$subject_id]["nilai_ot"])) {
                $sumSubject[$subject_id]["nilai_ot"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot"] += $nilai_ot;
            if (!isset($sumSubject[$subject_id]["nilai_af"])) {
                $sumSubject[$subject_id]["nilai_af"] = 0;
            }
            $sumSubject[$subject_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary object
            foreach ($pFieldSumrows as $sumField => $sumStat) {

                if (!isset($sumObject[$object_id][$sumField])) {
                    $sumObject[$object_id][$sumField] = 0;
                }
                $sumObject[$object_id][$sumField] += $$sumField;

            }
            //endregion

            $sumCabang[$cabang_id]["cabang_nama"] = $cabang_nama;
            $sumSubject[$subject_id]["subject_nama"] = $subject_nama;
            $sumObject[$object_id]["object_kode"] = $object_kode;
            $sumObject[$object_id]["object_nama"] = $object_nama;
        }

        foreach ($sellers as $sId => $sNama) {
            $sumSubject[$sId]["subject_nama"] = $sNama;
        }

        // arrPrint($sumSubject);
        // region headerCabang
        $cbHeader['no'] = "class='bg-info text-center'";
        foreach ($cbFieldToshows as $kolom => $kolomAlias) {
            $cbHeader[$kolomAlias] = "class='bg-info text-center'";

        }
        // endregion header

        // $summaryCabang = array(
        //   "cabangs" => $cabangs,
        //   "cabangs" => $cabangs,
        // );
        // arrPrint($cabangs);
        // arrPrint($sumCabang);
        // arrPrint($sumSubject);

        $compDatas = $srScr;
        // arrPrint($compDatas);
        // mati_disini();

        // arrPrintWebs($fieldToshows );
        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header
        // arrPrint($header);

        // arrPrintWebs($fieldAttr);
        // arrPrintWebs($tmps);
        // mati_disini(__LINE__);
        // arrPrint($fieldToshows);
        // cekHitam(sizeof($compDatas));
        if (sizeof($compDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($compDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                    }
                    else {
                        $fValue = $items->$kolom;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {

                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // $referenceID = $regDatas[$transaksi_id]['referenceID'];
                // $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                // //region builder saldo berjalan
                // $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                // //endregion

                // // region sales
                // $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                // $specs['sales']['attr'] = "class='text-right'";
                // $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                // // endregion sales

                // // region return
                // $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                // $specs['return']['attr'] = "class='text-right'";
                // $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                // // endregion return

                // // region netto berjalan
                // $specs['netto']['value'] = formatField("number", $netto);
                // $specs['netto']['attr'] = "class='text-right'";
                // // endregion netto berjalan

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }
                // $compSpecs = array();
                // foreach ($steps as $num => $nSpec) {
                //     // arrPrint($nSpec);
                //     $nJenis = $nSpec['jenis'];
                //     if ($nJenis == $trJenis) {
                //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                //         if($nJenis == "582spd"){
                //             $spdSpecs = $specs;
                //             // arrPrint($compSpecs);
                //             arrPrint($rSpecs);
                //             cekHere();
                //         }
                //         else{
                //             $compSpecs = $specs;
                //         }
                //
                //         $compSpecs2 = $rSpecs + $spdSpecs;
                //         $bodies[$num][] = $compSpecs2;
                //     }
                //     // else{
                $bodies[] = $specs;
                //     // }
                //     arrPrint($rSpecs);
                // }

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";
        // arrPrint($rSpecs);
        // arrPrint($spdSpecs);
        // arrPrint($bodies);
        // arrPrint($footers);
        // cekHijau($sumNetto);
        // mati_disini();
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }


        // mati_disini();
        // $bulan = "$year-$month";
        // $bulan_f = formatTanggal($bulan, 'Y F');
        // cekMerah($bulan_f ." ". $bulan);
        $data = array(
            "mode" => "viewSales",
            "title" => $reportingNetts['title'],
            "subTitle" => "$bulan_f",
            "confReportCabang" => $confReportCabang,
            "confReportSubject" => $confReportSubject,
            "confReportObject" => $confReportObject,
            "sumCabang" => $sumCabang,
            "sumSubject" => $sumSubject,
            "sumObject" => $sumObject,
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            "jenisTr" => $this->jenisTr,
            "trName" => "",
        );
        $this->load->view("activityReports", $data);
    }

    public function viewPurchasingSpAll()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');

            $condite = array("th" => $year, "bl" => $month);

            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }
        elseif (isset($_GET['year'])) {
            $year = $_GET['year'];

            $condite = array("th" => $year);
            $bulan = "$year-$month";
            $bulan_f = $year;
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');

            $condite = array("th" => $year, "bl" => $month);
            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }
        $reportingNetts = $this->config->item('report')['pembelian_supplies'];
        $confReportCabang = $reportingSumCabang = $this->config->item('report')['pembelian_cabang'];
        $confReportSubject = $reportingSumSubject = $reportingSumSeller = $this->config->item('report')['pembelian_vendor'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }

        }
        foreach ($reportingSumCabang['mdlFields'] as $field => $fChilds) {
            $cbFields[] = $field;
            if (isset($fChilds['label'])) {
                $cbFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $cbFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $cbFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $cbFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $cbFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumSeller['mdlFields'] as $field => $fChilds) {
            $sFields[] = $field;
            if (isset($fChilds['label'])) {
                $sFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $sFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $sFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $sFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $sFieldFormat[$field] = $fChilds['format'];
            }
        }
        // $steps = $reportingNetts['tabs'];
        // foreach ($steps as $step) {
        //     isset($step['jenis']) ? $fieldJenis[] = $step['jenis'] : "";
        // }

        // arrPrint($fieldJenis);
        // arrPrint($reportingNetts['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fieldAttrHeader);
        // arrPrint($fields);
        // arrPrint($steps);
        // matiHere(__METHOD__ . " @" . __LINE__);

        $stID = $this->uri->segment(3);
        $tr = new MdlTransaksi();
        $rp = new MdlReport();
        $db2 = $this->load->database('report', TRUE);
        // region sales
        // $rp->setDebug(true);
        // $rp->setCondites(array("th" => $year, "bl" => $month));
        $rp->setCondites($condite);
        $srScr = $rp->lookupPurchasingSpMonthly()->result();
        // endregion sales
        // arrPrint($srScr);
        // arrPrint($sFields);
        // arrPrint($cbFields);
        $koloms = array_unique(array_merge($cbFields, $sFields));
        if (sizeof($srScr) < 1) {
            $sumCabang = array();
            $sumSubject = array();
        }
        $subjects = array();
        $cabangs = array();
        $sumSubjects = array();
        foreach ($srScr as $dSources) {
            // arrPrint($dSources);
            foreach ($koloms as $kolom) {
                $$kolom = trim($dSources->$kolom);
            }

            //region summary cabang
            if (!isset($sumCabang[$cabang_id]["nilai_in"])) {
                $sumCabang[$cabang_id]["nilai_in"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_in"] += $nilai_in;

            if (!isset($sumCabang[$cabang_id]["nilai_ot"])) {
                $sumCabang[$cabang_id]["nilai_ot"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot"] += $nilai_ot;

            if (!isset($sumCabang[$cabang_id]["nilai_af"])) {
                $sumCabang[$cabang_id]["nilai_af"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary cabang
            if (!isset($sumSubject[$subject_id]["nilai_in"])) {
                $sumSubject[$subject_id]["nilai_in"] = 0;
            }
            $sumSubject[$subject_id]["nilai_in"] += $nilai_in;

            if (!isset($sumSubject[$subject_id]["nilai_ot"])) {
                $sumSubject[$subject_id]["nilai_ot"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot"] += $nilai_ot;
            if (!isset($sumSubject[$subject_id]["nilai_af"])) {
                $sumSubject[$subject_id]["nilai_af"] = 0;
            }
            $sumSubject[$subject_id]["nilai_af"] += $nilai_af;
            //endregion

            $sumCabang[$cabang_id]["cabang_nama"] = $cabang_nama;
            $sumSubject[$subject_id]["subject_nama"] = $subject_nama;
        }

        // region headerCabang
        $cbHeader['no'] = "class='bg-info text-center'";
        foreach ($cbFieldToshows as $kolom => $kolomAlias) {
            $cbHeader[$kolomAlias] = "class='bg-info text-center'";

        }
        // endregion header

        // $summaryCabang = array(
        //   "cabangs" => $cabangs,
        //   "cabangs" => $cabangs,
        // );
        // arrPrint($cabangs);
        // arrPrint($sumCabang);
        // arrPrint($sumSubject);

        $compDatas = $srScr;
        // arrPrint($compDatas);
        // mati_disini();

        // arrPrintWebs($fieldToshows );
        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header
        // arrPrint($header);

        // arrPrintWebs($fieldAttr);
        // arrPrintWebs($tmps);
        // mati_disini(__LINE__);
        // arrPrint($fieldToshows);
        // cekHitam(sizeof($compDatas));
        if (sizeof($compDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($compDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                    }
                    else {
                        $fValue = $items->$kolom;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {

                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // $referenceID = $regDatas[$transaksi_id]['referenceID'];
                // $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                // //region builder saldo berjalan
                // $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                // //endregion

                // // region sales
                // $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                // $specs['sales']['attr'] = "class='text-right'";
                // $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                // // endregion sales

                // // region return
                // $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                // $specs['return']['attr'] = "class='text-right'";
                // $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                // // endregion return

                // // region netto berjalan
                // $specs['netto']['value'] = formatField("number", $netto);
                // $specs['netto']['attr'] = "class='text-right'";
                // // endregion netto berjalan

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }
                // $compSpecs = array();
                // foreach ($steps as $num => $nSpec) {
                //     // arrPrint($nSpec);
                //     $nJenis = $nSpec['jenis'];
                //     if ($nJenis == $trJenis) {
                //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                //         if($nJenis == "582spd"){
                //             $spdSpecs = $specs;
                //             // arrPrint($compSpecs);
                //             arrPrint($rSpecs);
                //             cekHere();
                //         }
                //         else{
                //             $compSpecs = $specs;
                //         }
                //
                //         $compSpecs2 = $rSpecs + $spdSpecs;
                //         $bodies[$num][] = $compSpecs2;
                //     }
                //     // else{
                $bodies[] = $specs;
                //     // }
                //     arrPrint($rSpecs);
                // }

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";
        // arrPrint($rSpecs);
        // arrPrint($spdSpecs);
        // arrPrint($bodies);
        // arrPrint($footers);
        // cekHijau($sumNetto);
        // mati_disini();
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }

        // arrPrint($reportingNetts);
        // arrPrint($this->config->item("report"));
        // mati_disini();
        // $bulan = "$year-$month";
        // $bulan_f = formatTanggal($bulan, 'Y F');
        $data = array(
            "mode" => "viewSales",
            "title" => $reportingNetts['title'],
            "subTitle" => $bulan_f,
            "confReportCabang" => $confReportCabang,
            "confReportSubject" => $confReportSubject,
            "sumCabang" => $sumCabang,
            "sumSubject" => $sumSubject,
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            "jenisTr" => $this->jenisTr,
            "trName" => "",
        );
        $this->load->view("activityReports", $data);
    }

    public function viewPurchasingFgAll()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');

            $condite = array("th" => $year, "bl" => $month);

            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }
        elseif (isset($_GET['year'])) {
            $year = $_GET['year'];

            $condite = array("th" => $year);
            $bulan = "$year-$month";
            $bulan_f = $year;
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');

            $condite = array("th" => $year, "bl" => $month);
            $bulan = "$year-$month";
            $bulan_f = formatTanggal($bulan, 'Y F');
        }

        $reportingNetts = $this->config->item('report')['pembelian_produk'];
        $confReportCabang = $reportingSumCabang = $this->config->item('report')['pembelian_cabang'];
        $confReportSubject = $reportingSumSubject = $reportingSumSeller = $this->config->item('report')['pembelian_vendor'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }

        }
        foreach ($reportingSumCabang['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $cbFields[] = $field;
            if (isset($fChilds['label'])) {
                $cbFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $cbFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $cbFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $cbFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $cbFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumSeller['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $sFields[] = $field;
            if (isset($fChilds['label'])) {
                $sFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $sFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $sFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $sFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $sFieldFormat[$field] = $fChilds['format'];
            }
        }
        // $steps = $reportingNetts['tabs'];
        // foreach ($steps as $step) {
        //     isset($step['jenis']) ? $fieldJenis[] = $step['jenis'] : "";
        // }

        // arrPrint($fieldJenis);
        // arrPrint($reportingNetts['fields']);
        // arrPrint($fieldToshows);
        // arrPrint($fieldAttr);
        // arrPrint($fieldAttrHeader);
        // arrPrint($fields);
        // arrPrint($steps);
        // matiHere(__METHOD__ . " @" . __LINE__);

        $stID = $this->uri->segment(3);
        $tr = new MdlTransaksi();
        $rp = new MdlReport();
        $db2 = $this->load->database('report', TRUE);
        // region sales
        // $rp->setDebug(true);
        // $rp->setCondites(array("th" => $year, "bl" => $month));
        $rp->setCondites($condite);
        $srScr = $rp->lookupPurchasingFgMonthly()->result();
        // endregion sales
        // arrPrint($srScr);
        // arrPrint($sFields);
        // arrPrint($cbFields);
        $koloms = array_unique(array_merge($cbFields, $sFields));

        if (sizeof($srScr) < 1) {
            $sumCabang = array();
            $sumSubject = array();
        }
        $subjects = array();
        $cabangs = array();
        $sumSubjects = array();
        foreach ($srScr as $dSources) {
            // arrPrint($dSources);
            foreach ($koloms as $kolom) {
                $$kolom = trim($dSources->$kolom);
            }

            //region summary cabang
            if (!isset($sumCabang[$cabang_id]["nilai_in"])) {
                $sumCabang[$cabang_id]["nilai_in"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_in"] += $nilai_in;

            if (!isset($sumCabang[$cabang_id]["nilai_ot"])) {
                $sumCabang[$cabang_id]["nilai_ot"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot"] += $nilai_ot;

            if (!isset($sumCabang[$cabang_id]["nilai_af"])) {
                $sumCabang[$cabang_id]["nilai_af"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_af"] += $nilai_af;
            //endregion
            //region summary cabang
            if (!isset($sumSubject[$subject_id]["nilai_in"])) {
                $sumSubject[$subject_id]["nilai_in"] = 0;
            }
            $sumSubject[$subject_id]["nilai_in"] += $nilai_in;

            if (!isset($sumSubject[$subject_id]["nilai_ot"])) {
                $sumSubject[$subject_id]["nilai_ot"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot"] += $nilai_ot;
            if (!isset($sumSubject[$subject_id]["nilai_af"])) {
                $sumSubject[$subject_id]["nilai_af"] = 0;
            }
            $sumSubject[$subject_id]["nilai_af"] += $nilai_af;
            //endregion

            $sumCabang[$cabang_id]["cabang_nama"] = $cabang_nama;
            $sumSubject[$subject_id]["subject_nama"] = $subject_nama;
        }

        // region headerCabang
        $cbHeader['no'] = "class='bg-info text-center'";
        foreach ($cbFieldToshows as $kolom => $kolomAlias) {
            $cbHeader[$kolomAlias] = "class='bg-info text-center'";

        }
        // endregion header

        // $summaryCabang = array(
        //   "cabangs" => $cabangs,
        //   "cabangs" => $cabangs,
        // );
        // arrPrint($cabangs);
        // arrPrint($sumCabang);
        // arrPrint($sumSubject);

        $compDatas = $srScr;
        // arrPrint($compDatas);
        // mati_disini();

        // arrPrintWebs($fieldToshows );
        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header
        // arrPrint($header);

        // arrPrintWebs($fieldAttr);
        // arrPrintWebs($tmps);
        // mati_disini(__LINE__);
        // arrPrint($fieldToshows);
        // cekHitam(sizeof($compDatas));
        if (sizeof($compDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($compDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                    }
                    else {
                        $fValue = $items->$kolom;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {

                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // $referenceID = $regDatas[$transaksi_id]['referenceID'];
                // $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                // //region builder saldo berjalan
                // $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                // //endregion

                // // region sales
                // $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                // $specs['sales']['attr'] = "class='text-right'";
                // $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                // // endregion sales

                // // region return
                // $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                // $specs['return']['attr'] = "class='text-right'";
                // $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                // // endregion return

                // // region netto berjalan
                // $specs['netto']['value'] = formatField("number", $netto);
                // $specs['netto']['attr'] = "class='text-right'";
                // // endregion netto berjalan

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }
                // $compSpecs = array();
                // foreach ($steps as $num => $nSpec) {
                //     // arrPrint($nSpec);
                //     $nJenis = $nSpec['jenis'];
                //     if ($nJenis == $trJenis) {
                //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                //         if($nJenis == "582spd"){
                //             $spdSpecs = $specs;
                //             // arrPrint($compSpecs);
                //             arrPrint($rSpecs);
                //             cekHere();
                //         }
                //         else{
                //             $compSpecs = $specs;
                //         }
                //
                //         $compSpecs2 = $rSpecs + $spdSpecs;
                //         $bodies[$num][] = $compSpecs2;
                //     }
                //     // else{
                $bodies[] = $specs;
                //     // }
                //     arrPrint($rSpecs);
                // }

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";
        // arrPrint($rSpecs);
        // arrPrint($spdSpecs);
        // arrPrint($bodies);
        // arrPrint($footers);
        // cekHijau($sumNetto);
        // mati_disini();
        // if(sizeof($bodies[3]) < 1){
        //
        //     $bodies = array();
        // }

        // arrPrint($bodies);
        //         mati_disini();

        // arrPrint($tmps);
        // arrPrint($header);
        // arrPrint($bodies);
        // foreach ($f?? as $item) {
        //
        // }


        // mati_disini();
        // $bulan = "$year-$month";
        // $bulan_f = formatTanggal($bulan, 'Y F');
        $data = array(
            "mode" => "viewSales",
            "title" => $reportingNetts['title'],
            "subTitle" => $bulan_f,
            "confReportCabang" => $confReportCabang,
            "confReportSubject" => $confReportSubject,
            "sumCabang" => $sumCabang,
            "sumSubject" => $sumSubject,
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            "jenisTr" => $this->jenisTr,
            "trName" => "",
        );
        $this->load->view("activityReports", $data);
    }

    public function viewInvoice()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');
        }

        $reportingNetts = $this->config->item('history')['invoice'];
        $this->load->model("Mdls/MdlCurrency");
        $jenisTr = "582";
        $selectedSTep = 5;
        $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();
        $pairTransaksi = isset($this->configUi[$jenisTr]['pairTransaksi']) ? $this->configUi[$jenisTr]['pairTransaksi'] : 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();
        // arrPrint($reportingNetts['mdlFields']);
        $confReportCabang = $reportingSumCabang = $this->config->item('report')['penjualan_cabang'];
        $confReportSubject = $reportingSumSubject = $reportingSumSeller = $this->config->item('report')['penjualan_seller'];
        //        arrPrint($historyFields);

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {

            $headers[] = array();
            $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }
            if (isset($fChilds['sumrow'])) {
                $fieldSumrow[$field] = $field;
            }

        }

        $header['no'] = "class='bg-info text-center'";
        foreach ($historyFields as $kolom => $kolomAlias) {
            // cekMerah("$kolom");
            // arrPrint($kolomAlias);
            if (is_array($kolomAlias)) {

                $header[$kolomAlias["label"]] = "class='bg-info text-center'";
            }
            else {

                $header[$kolomAlias] = "class='bg-info text-center'";
            }

        }

        $stID = $this->uri->segment(3);
        $tr = new MdlTransaksi();

        $cabang_id = $this->placeId;
        $jenis = "582";

        $wheres = "month(dtime) = '$month' AND year(dtime) = '$year'";
        $this->db->where($wheres);
        if ($this->placeId != CB_ID_PUSAT) {

            $tr->addFilter("cabang_id='" . $this->placeId . "'");
        }
        $tr->addFilter("jenis='$jenis'");
        $tmpHist = $srcHi = $tr->lookupHistories(1000, 500, 1)->result();
        // showLast_query("lime");

        $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;
                }
            }
        }

        $arrayHistory = array();
        $arrayHistory_ids = 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'];
                        }
                    }
                }

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


                $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;
                        }
                    }
                }

            }

            $numb = 0;
            foreach ($tmpHist as $row) {
                // arrPrint($row->counters);
                // region ids_his
                $id_hist = blobDecode($row->ids_his);
                // $id_hist2 = blobDecode($row->ids_his)[2];
                // arrPrint($id_hist2);
                // endregion ids_his

                $thisNomer = $row->nomer;
                $cabang_id = explode(".", $thisNomer)[1];
                $counterjenis = "$jenis|$cabang_id";

                $salesName = isset($arrSalesName[$row->id_top]) ? $arrSalesName[$row->id_top] : "-";

                // arrPrintWebs(blobDecode($row->ids_his));

                //region memangil global counter
                $counterIds_his = blobDecode(blobDecode($row->ids_his)[1]['counters']);
                $counters = blobDecode($row->counters);
                // arrPrintWebs($counters);
                // cekBiru("$counterjenis");
                $counterGlobal = isset($counters['stepCode|placeID'][$counterjenis]) ? $counters['stepCode|placeID'][$counterjenis] : "9";
                // $counterIds_his_global = $counterIds_his['stepCode|placeID']["582spo|$cabang_id"];
                $cGlobals = digit_5($counterGlobal);
                // $cGlobal_spo = digit_5($counterIds_his_global);
                //endregion

                // arrPrint($counters);
                // cekHijau($row->id);
                // arrPrint($counterIds_his);

                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();
                    //                    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) {
                    // cekHijau("$fName");
                    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($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") {
                            $kolomValues = $row->$fName . "&#x2011;$cGlobals";
                        }
                        elseif ($fName == "nomer_top") {

                            $kolomValue_0s = formatField($fName, $row->$fName);
                            // $kolomValues = str_replace("</span>","-".$cGlobal_spo,$kolomValue_0s);
                            $kolomValues = showHistoriGlobalNumbers($row->ids_his, 1, true);;
                        }
                        else {
                            $kolomValues = $fName != "no" ? formatField($fName, $row->$fName) : "";
                        }
                        //endregion

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

                    if ($fName == "ids_his") {
                        // cekHitam($fName);
                        if (is_array($fLabel)) {
                            // arrPrint($fLabel);
                            $hisStep = $fLabel['step'];
                            $hisKey = $fLabel['key'];
                            // $hisLabel = $fLabel['label'];
                            // $tNomer = $id_hist[$hisStep][$hisKey];
                            // $jenisTrsub = explode(".", $tNomer)[0];
                            // $counterjenis = "$jenisTrsub|" . $this->placeId;
                            //
                            // $counters = blobDecode($id_hist[$hisStep]['counters']);
                            // // arrPrint($counterIds_his);
                            // // $counters = blobDecode($row->counters);
                            // $counterGlobal = $counters['stepCode|placeID'][$counterjenis];
                            // $cGcounter = digit_5($counterGlobal);

                            // $colValue_f = formatField($hisKey, $id_hist[$hisStep][$hisKey]);
                            // $colValue = str_replace("</span>", "-" . $cGcounter, $colValue_f);
                            $colValue = showHistoriGlobalNumbers($row->ids_his, $hisStep, true);;
                            // cekMerah("$counterjenis $placeId $jenisTrsub $cabang_id $counterGlobal");

                            $logistic = "";
                            if (isset($arrTransMainHist[$row->id][$hisStep]['main'])) {
                                $main = $arrTransMainHist[$row->id][$hisStep]['main'];
                                $logistic = $main['oleh_nama'];
                            }
                        }
                    }

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

                    $tmp['logistic'] = $logistic != null ? $logistic : 'undefined';
                    $tmp['sales_name'] = $salesName;

                    $tmp[$fName] = $colValue;

                    $tmp1["id"] = $row->id;
                }
                // arrPrint($tmp);
                //                arrPrint($arrCurrency);
                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;
                }
                $arrayHistory[] = $tmp;
                $arrayHistory_ids[] = $tmp1;
            }
            // arrPrint($sumValue);
        }
        // showLast_query("lime");

        // arrPrint($arrayHistory);
        // arrPrint($srcHi);

        if (sizeof($srcHi) > 0) {
            $no = 0;
            $specs = array();
            // foreach ($srcHi as $items) {
            foreach ($arrayHistory as $items) {
                $items = (object)$items;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($historyFields as $kolom => $kolomAlias) {
                    // arrPrint($kolomAlias);
                    if (isset($fieldFormat[$kolom])) {
                        $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                    }
                    else {
                        $fValue = $items->$kolom;
                    }
                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {
                        $specs[$kolom]['value'] = $fValue;
                    }
                    //region summary footer
                    if (in_array($kolom, $fieldSumrow)) {
                        if (!isset($sum[$kolom])) {
                            $sum[$kolom] = 0;
                        }
                        $sum[$kolom] += $fValue;
                    }
                    //endregion
                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";
                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "style='white-space: nowrap;' class='text-left $warna'";
                }

                $bodies[] = $specs;
            }
        }
        else {
            $bodies = array();
        }
        // arrPrint($bodies);
        // arrPrint($sumValue);

        $footers = array();
        // $sumNetto = $sumSale - $sumReturn;
        // $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        // $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        // $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        // $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        // $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";

        $strMonth = strtoupper(namaBulan()[$month]);
        $data = array(
            "mode" => "viewInvoice",
            "title" => key($this->config->item("history")),
            "subTitle" => $year . "-" . $strMonth,
            "confReportCabang" => $confReportCabang,
            "confReportSubject" => $confReportSubject,
            // "times"            => $months,
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "sumValue" => $sumValue,
            "historyFields" => $historyFields,
            "names" => isset($names) ? $names : array(),
            // "recaps"           => $recaps,
            "jenisTr" => $this->jenisTr,
            "trName" => "",
            // "availFilters"     => $availFilters,
            // "defaultFilter"    => $defaultFilter,
            // "selectedFilter"   => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            // "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            // "thisPage"         => base_url() . get_class($this) . " / " . $this->uri->segment(2) . " / " . $this->jenisTr,
            // "subPage"          => base_url() . get_class($this) . " / viewDaily / " . $this->jenisTr,
            // "historyPage"      => base_url() . "Transaksi / viewHistory / " . $this->jenisTr . " ? stID = " . $stID,
            // "stepNames"        => $stepNames,
            // "defaultStep"      => $defaultStep,
            // "selectedStep"     => $selectedStep,
            // "addLink"          => $addLink,
        );
        $this->load->view("activityReports", $data);
    }

    public function viewSalesRealization()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');
        }
        $reportingNetts = $this->config->item('report')['realisasi_so'];
        $confReportCabang = $reportingSumCabang = $this->config->item('report')['realisasi_so_cabang'];
        $confReportSubject = $reportingSumSubject = $reportingSumSeller = $this->config->item('report')['realisasi_so_seller'];
        $confReportObject = $reportingSumObject = $reportingSumProduct = $this->config->item('report')['realisasi_so_produk'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        foreach ($reportingNetts['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }
            if (isset($fChilds['sum_rows'])) {
                $fieldSumrows[$field] = $fChilds['sum_rows'];
            }

        }
        foreach ($reportingSumCabang['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $cbFields[] = $field;
            if (isset($fChilds['label'])) {
                $cbFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $cbFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $cbFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $cbFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $cbFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumSeller['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $sFields[] = $field;
            if (isset($fChilds['label'])) {
                $sFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $sFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $sFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $sFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $sFieldFormat[$field] = $fChilds['format'];
            }
        }
        foreach ($reportingSumObject['mdlFields'] as $field => $fChilds) {
            $pFields[] = $field;
            if (isset($fChilds['label'])) {
                $pFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $pFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $pFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $pFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $pFieldFormat[$field] = $fChilds['format'];
            }
            if (isset($fChilds['sum_rows'])) {
                $pFieldSumrows[$field] = $fChilds['sum_rows'];
            }
        }

        $stID = $this->uri->segment(3);
        $sm = new MdlEmployeeCabang();
        $tr = new MdlTransaksi();
        $rp = new MdlReport();

        //region seller datas
        $srcSm = $sm->lookupSeller();
        // showLast_query("lime");
        $sMans = $srcSm->raws->result();
        $sKoloms = $srcSm->koloms;
        $slFields = array();
        foreach ($sKoloms as $field => $fieldParams) {
            $slFields[] = $field;
        }

        foreach ($sMans as $sMan) {
            foreach ($slFields as $kolom) {
                $$kolom = $sMan->$kolom;
            }

            $sellers[$id] = $nama;
        }
        //endregion

        // $rp->setDebug(true);
        $condite = array("th" => $year, "bl" => $month);
        my_cabang_id() > 0 ? $condite["cabang_id"] = my_cabang_id() : "";
        // arrPrint($condite);

        $rp->setCondites($condite);
        $rp->setDebug(true);
        // $rp->db2->limit(2);
        // $rp->setLimit(1);
        $srScr = $rp->lookupPreSalesMonthly()->result();
        // showLast_query('merah');
        $cancelScr = $rp->lookupPreSalesCanceledMonthly()->result();
        // showLast_query('kuning');
        $saleScr = $rp->lookupSalesMonthly()->result();
        // showLast_query('hijau');

        // arrPrint($srScr);
        // arrPrint($cancelScr);
        // arrPrint($saleScr);
        //region prepare data tahp 2
        //region spo
        $replacecer = array(
            "unit_ot" => "unit_ot_spo",
            "unit_in" => "unit_in_spo",
            "unit_af" => "unit_af_spo",
            "nilai_ot" => "nilai_ot_spo",
            "nilai_in" => "nilai_in_spo",
            "nilai_af" => "nilai_af_spo",
        );
        $srScr1 = array();
        foreach ($srScr as $items) {
            $items2 = array();
            foreach ($items as $item_key => $item_value) {
                $new_key = array_key_exists($item_key, $replacecer) ? $replacecer[$item_key] : $item_key;
                $items2[$new_key] = $item_value;
            }
            $srScr1[] = (object)$items2;
        }
        //endregion

        //region cancel so
        $replacecer = array(
            "unit_ot" => "unit_ot_cl",
            "unit_in" => "unit_in_cl",
            "unit_af" => "unit_af_cl",
            "nilai_ot" => "nilai_ot_cl",
            "nilai_in" => "nilai_in_cl",
            "nilai_af" => "nilai_af_cl",
        );
        $cancelScr1 = array();
        foreach ($cancelScr as $items) {
            $items2 = array();
            foreach ($items as $item_key => $item_value) {
                $new_key = array_key_exists($item_key, $replacecer) ? $replacecer[$item_key] : $item_key;
                $items2[$new_key] = $item_value;
            }
            $cancelScr1[] = (object)$items2;
        }
        //endregion

        //region spd
        $replacecer = array(
            "unit_ot" => "unit_ot_spd",
            "unit_in" => "unit_in_spd",
            "unit_af" => "unit_af_spd",
            "nilai_ot" => "nilai_ot_spd",
            "nilai_in" => "nilai_in_spd",
            "nilai_af" => "nilai_af_spd",
        );
        $saleScr1 = array();
        foreach ($saleScr as $items) {
            $items2 = array();
            foreach ($items as $item_key => $item_value) {
                $new_key = array_key_exists($item_key, $replacecer) ? $replacecer[$item_key] : $item_key;
                $items2[$new_key] = $item_value;
            }
            $saleScr1[] = (object)$items2;
        }
        //endregion

        // arrPrintWebs($srScr1);
        // arrPrint($cancelScr1);
        // arrPrintWebs($saleScr1);
        //
        // matiHere();
        $koloms = array_unique(array_merge($cbFields, $sFields, $pFields));
        $allDatas = array_merge($srScr1, $cancelScr1, $saleScr1);

        foreach ($allDatas as $item) {

            $subjectNamas[$item->subject_id] = $item->subject_nama;
            $objects[$item->object_id] = $item->object_nama;
            $objectKodes[$item->object_id] = $item->object_kode;
            $cabangs[$item->cabang_id] = $item->cabang_nama;
        }

        // arrPrint($cbFields);
        // arrPrint($koloms);
        // arrPrint($allDatas);

        foreach ($allDatas as $dSources) {
            // arrPrintWebs($dSources);
            foreach ($koloms as $kolom) {
                $$kolom = isset($dSources->$kolom) ? trim($dSources->$kolom) : "";
            }

            //region summary cabang
            if (!isset($sumCabang[$cabang_id]["nilai_ot_spo"])) {
                $sumCabang[$cabang_id]["nilai_ot_spo"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot_spo"] += $nilai_ot_spo;

            if (!isset($sumCabang[$cabang_id]["nilai_ot_cl"])) {
                $sumCabang[$cabang_id]["nilai_ot_cl"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot_cl"] += $nilai_ot_cl;

            if (!isset($sumCabang[$cabang_id]["nilai_ot_spd"])) {
                $sumCabang[$cabang_id]["nilai_ot_spd"] = 0;
            }
            $sumCabang[$cabang_id]["nilai_ot_spd"] += $nilai_ot_spd;
            //endregion
            //region summary subject
            if (!isset($sumSubject[$subject_id]["nilai_ot_spo"])) {
                $sumSubject[$subject_id]["nilai_ot_spo"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot_spo"] += $nilai_ot_spo;

            if (!isset($sumSubject[$subject_id]["nilai_ot_cl"])) {
                $sumSubject[$subject_id]["nilai_ot_cl"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot_cl"] += $nilai_ot_cl;

            if (!isset($sumSubject[$subject_id]["nilai_ot_spd"])) {
                $sumSubject[$subject_id]["nilai_ot_spd"] = 0;
            }
            $sumSubject[$subject_id]["nilai_ot_spd"] += $nilai_ot_spd;
            //endregion
            //region summary object
            foreach ($pFieldSumrows as $sumField => $sumStat) {

                if (!isset($sumObject[$object_id][$sumField])) {
                    $sumObject[$object_id][$sumField] = 0;
                }
                $sumObject[$object_id][$sumField] += $$sumField;

            }
            //endregion

            $sumCabang[$cabang_id]["cabang_nama"] = $cabang_nama;
            $sumSubject[$subject_id]["subject_nama"] = $subject_nama;
            $sumObject[$object_id]["object_kode"] = $object_kode;
            $sumObject[$object_id]["object_nama"] = $object_nama;
        }

        // arrPrint($sumCabang);
        foreach ($sumCabang as $cbId => $cbItems) {
            $sumNettSpo = $cbItems["nilai_ot_spo"] - $cbItems['nilai_ot_cl'];
            $sumNett = $sumNettSpo - $cbItems['nilai_ot_spd'];

            // cekHitam("$sumNett = ".$cbItems["nilai_ot_spo"]." - ". $cbItems['nilai_ot_cl']." - ". $cbItems['nilai_ot_spd']);

            $sumCabang_2[$cbId] = $cbItems;
            $sumCabang_2[$cbId]["nilai_ne_spo"] = $sumNettSpo;
            $sumCabang_2[$cbId]["nilai_af_spo"] = $sumNett;
        }

        foreach ($sumSubject as $suId => $suItems) {
            $sumNettSpo = $suItems["nilai_ot_spo"] - $suItems['nilai_ot_cl'];
            $sumNett = $sumNettSpo - $suItems['nilai_ot_spd'];

            $sumSubject_2[$suId] = $suItems;
            $sumSubject_2[$suId]["nilai_ne_spo"] = $sumNettSpo;
            $sumSubject_2[$suId]["nilai_af_spo"] = $sumNett;
        }

        foreach ($sumObject as $obId => $obItems) {
            $sumNettSpo = $obItems["nilai_ot_spo"] - $obItems['nilai_ot_cl'];
            $sumNett = $sumNettSpo - $obItems['nilai_ot_spd'];

            $sumUnitNettSpo = $obItems["unit_ot_spo"] - $obItems['unit_ot_cl'];
            $sumUnitNett = $sumUnitNettSpo - $obItems['unit_ot_spd'];

            $sumObject_2[$obId] = $obItems;
            $sumObject_2[$obId]["nilai_ne_spo"] = $sumNettSpo;
            $sumObject_2[$obId]["nilai_af_spo"] = $sumNett;
            $sumObject_2[$obId]["unit_ne_spo"] = $sumUnitNettSpo;
            $sumObject_2[$obId]["unit_af_spo"] = $sumUnitNett;
        }

        // region headerCabang
        $cbHeader['no'] = "class='bg-info text-center'";
        foreach ($cbFieldToshows as $kolom => $kolomAlias) {
            $cbHeader[$kolomAlias] = "class='bg-info text-center'";

        }
        // endregion header


        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header


        if (sizeof($allDatas) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($allDatas as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        // $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                        $fValue = $fieldFormat[$kolom]($kolom, isset($items->$kolom) ? $items->$kolom : 0);
                    }
                    else {
                        $fValue = isset($items->$kolom) ? $items->$kolom : 0;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {
                        // cekHitam("$kolom");
                        if ($kolom == "unit_af_spo") {
                            $fValue = (isset($items->unit_ot_spo) ? $items->unit_ot_spo : 0) - (isset($items->unit_ot_cl) ? $items->unit_ot_cl : 0) - (isset($items->unit_ot_spd) ? $items->unit_ot_spd : 0);

                            $fValue = formatField($kolom, $fValue);
                        }
                        if ($kolom == "nilai_af_spo") {
                            $fValue = (isset($items->nilai_ot_spo) ? $items->nilai_ot_spo : 0) - (isset($items->nilai_ot_cl) ? $items->nilai_ot_cl : 0) - (isset($items->nilai_ot_spd) ? $items->nilai_ot_spd : 0);
                            $fValue = formatField($kolom, $fValue);
                        }
                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // $referenceID = $regDatas[$transaksi_id]['referenceID'];
                // $nett1 = round($regDatas[$transaksi_id]['nett1'], 0);
                // //region builder saldo berjalan
                // $referenceID == 0 ? $netto += $nett1 : $netto -= $nett1;
                // //endregion

                // // region sales
                // $specs['sales']['value'] = $referenceID == 0 ? formatField("number", $nett1) : 0;
                // $specs['sales']['attr'] = "class='text-right'";
                // $referenceID == 0 ? $sumSale += $nett1 : $sumSale = 0;
                // // endregion sales

                // // region return
                // $specs['return']['value'] = $referenceID > 0 ? formatField("number", $nett1) : 0;
                // $specs['return']['attr'] = "class='text-right'";
                // $referenceID > 0 ? $sumReturn += $nett1 : $sumReturn = 0;
                // // endregion return

                // // region netto berjalan
                // $specs['netto']['value'] = formatField("number", $netto);
                // $specs['netto']['attr'] = "class='text-right'";
                // // endregion netto berjalan

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }
                // $compSpecs = array();
                // foreach ($steps as $num => $nSpec) {
                //     // arrPrint($nSpec);
                //     $nJenis = $nSpec['jenis'];
                //     if ($nJenis == $trJenis) {
                //     // if (($nJenis == $trJenis) && ($trJenis == "582spd") || ($trJenis == "982")) {
                //         if($nJenis == "582spd"){
                //             $spdSpecs = $specs;
                //             // arrPrint($compSpecs);
                //             arrPrint($rSpecs);
                //             cekHere();
                //         }
                //         else{
                //             $compSpecs = $specs;
                //         }
                //
                //         $compSpecs2 = $rSpecs + $spdSpecs;
                //         $bodies[$num][] = $compSpecs2;
                //     }
                //     // else{
                $bodies[] = $specs;
                //     // }
                //     arrPrint($rSpecs);
                // }

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";

        // arrPrint($bodies);
        foreach ($bodies as $obId => $obItems) {
            // $sumNettSpo = $obItems["nilai_ot_spo"] - $obItems['nilai_ot_cl'];
            // $sumNett = $sumNettSpo - $obItems['nilai_ot_spd'];
            //
            // $sumUnitNettSpo = $obItems["unit_ot_spo"] - $obItems['unit_ot_cl'];
            // $sumUnitNett = $sumUnitNettSpo - $obItems['unit_ot_spd'];
            //
            // $sumObject_2[$obId] = $obItems;
            // $sumObject_2[$obId]["nilai_ne_spo"] = $sumNettSpo;
            // $sumObject_2[$obId]["nilai_af_spo"] = $sumNett;
            // $sumObject_2[$obId]["unit_ne_spo"] = $sumUnitNettSpo;
            // $sumObject_2[$obId]["unit_af_spo"] = $sumUnitNett;
        }


        $bulan = "$year-$month";
        $bulan_f = formatTanggal($bulan, 'Y F');
        // cekMerah($bulan_f ." ". $bulan);
        $data = array(
            "mode" => "viewSales",
            "title" => $reportingNetts['title'],
            "subTitle" => "$bulan_f",
            "confReportCabang" => $confReportCabang,
            "confReportSubject" => $confReportSubject,
            "confReportObject" => $confReportObject,
            "sumCabang" => isset($sumCabang_2) ? $sumCabang_2 : array(),
            "sumSubject" => isset($sumSubject_2) ? $sumSubject_2 : array(),
            "sumObject" => isset($sumObject_2) ? $sumObject_2 : array(),
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            "jenisTr" => $this->jenisTr,
            "trName" => "",
        );
        $this->load->view("activityReports", $data);
    }

    public function viewSalesRealizations()
    {
        if (isset($_GET['date'])) {
            $year = formatTanggal($_GET['date'], 'Y');
            $month = formatTanggal($_GET['date'], 'm');
        }
        else {
            $year = dtimeNow('Y');
            $month = dtimeNow('m');
        }
        // $reportingNetts = $this->config->item('report')['realisasi_so'];
        $confAllReport = $this->config->item('report')['realisasi_allso_movement'];
        $confReportSubject = $this->config->item('report')['realisasi_so_movement'];
        // $confReportObject = $reportingSumObject = $reportingSumProduct = $this->config->item('report')['realisasi_so_produk'];
        // $rJmaster = $reportingNetts["returns"]["jenis_master"];

        $fields = array();
        $headers = array();
        $bodies = array();
        $fieldJenis = array();
        // foreach ($confReportSubject['mdlFields'] as $field => $fChilds) {
        //     // arrPrint($fChilds);
        //     // $headers[] = array();
        //     // $bodies[] = array();
        //     $fields[] = $field;
        //     if (isset($fChilds['label'])) {
        //         $fieldToshows[$field] = $fChilds['label'];
        //     }
        //     isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
        //     if (isset($fChilds['attr'])) {
        //         $fieldAttr[$field] = $fChilds['attr'];
        //     }
        //     if (isset($fChilds['link'])) {
        //         $fieldLink[$field] = $fChilds['link'];
        //     }
        //     if (isset($fChilds['format'])) {
        //         $fieldFormat[$field] = $fChilds['format'];
        //     }
        //     if (isset($fChilds['sum_rows'])) {
        //         $fieldSumrows[$field] = $fChilds['sum_rows'];
        //     }
        //
        // }
        foreach ($confReportSubject['mdlFields'] as $field => $fChilds) {
            // arrPrint($fChilds);
            // $headers[] = array();
            // $bodies[] = array();
            $cbFields[] = $field;
            if (isset($fChilds['label'])) {
                $cbFieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $cbFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $cbFieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $cbFieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $cbFieldFormat[$field] = $fChilds['format'];
            }
        }
        // foreach ($reportingSumSeller['mdlFields'] as $field => $fChilds) {
        //     // arrPrint($fChilds);
        //     // $headers[] = array();
        //     // $bodies[] = array();
        //     $sFields[] = $field;
        //     if (isset($fChilds['label'])) {
        //         $sFieldToshows[$field] = $fChilds['label'];
        //     }
        //     isset($fChilds['attrHeader']) ? $sFieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
        //     if (isset($fChilds['attr'])) {
        //         $sFieldAttr[$field] = $fChilds['attr'];
        //     }
        //     if (isset($fChilds['link'])) {
        //         $sFieldLink[$field] = $fChilds['link'];
        //     }
        //     if (isset($fChilds['format'])) {
        //         $sFieldFormat[$field] = $fChilds['format'];
        //     }
        // }
        foreach ($confAllReport['mdlFields'] as $field => $fChilds) {
            $fields[] = $field;
            if (isset($fChilds['label'])) {
                $fieldToshows[$field] = $fChilds['label'];
            }
            isset($fChilds['attrHeader']) ? $fieldAttrHeader[$field] = $fChilds['attrHeader'] : "";
            if (isset($fChilds['attr'])) {
                $fieldAttr[$field] = $fChilds['attr'];
            }
            if (isset($fChilds['link'])) {
                $fieldLink[$field] = $fChilds['link'];
            }
            if (isset($fChilds['format'])) {
                $fieldFormat[$field] = $fChilds['format'];
            }
            if (isset($fChilds['sum_rows'])) {
                $fieldSumrows[$field] = $fChilds['sum_rows'];
            }
        }

        $stSubject = $this->uri->segment(3);
        $sm = new MdlEmployeeCabang();
        $tr = new MdlTransaksi();
        $rp = new MdlReport();

        //region seller datas
        $srcSm = $sm->lookupSeller();
        // showLast_query("lime");
        $sMans = $srcSm->raws->result();
        $sKoloms = $srcSm->koloms;
        $slFields = array();
        foreach ($sKoloms as $field => $fieldParams) {
            $slFields[] = $field;
        }

        foreach ($sMans as $sMan) {
            foreach ($slFields as $kolom) {
                $$kolom = $sMan->$kolom;
            }

            $sellers[$id] = $nama;
        }
        //endregion

        // $rp->setDebug(true);
        $condite = array("th" => $year, "bl" => $month);
        my_cabang_id() > 0 ? $condite["cabang_id"] = my_cabang_id() : "";
        // arrPrint($condite);

        // $rp->setCondites($condite);
        // $rp->setDebug(true);
        // $rp->db2->limit(2);
        // $rp->setLimit(1);
        // $srScr = $rp->lookupPrePenjualanMovement("cabang")->result();
        $srScr = $rp->lookupPrePenjualanMovement($stSubject)->result();
        showLast_query("lime");
        // ==========================================================

        $rp->setCondites($condite);

        $srScr2 = $rp->lookupPrePenjualanMovement($stSubject)->result();
        // arrPrintLime($srScr2);
        foreach ($srScr2 as $cbId => $cbItems) {
            // arrPrint($cbItems);
            foreach ($cbFieldToshows as $field => $flabel) {
                $$field = $cbItems->$field;

                // cekMerah("$field");
                $cbSpecs[$field] = $cbItems->$field;
            }
            // $sumNettSpo = $cbItems["nilai_ot_spo"] - $cbItems['nilai_ot_cl'];
            // $sumNett = $sumNettSpo - $cbItems['nilai_ot_spd'];

            // cekHitam("$sumNett = ".$cbItems["nilai_ot_spo"]." - ". $cbItems['nilai_ot_cl']." - ". $cbItems['nilai_ot_spd']);

            $sumCabang_2[$cbId] = $cbSpecs;
            $sumCabang_2[$cbId]["subject_nama"] = $subject_nama;
        }
        // arrPrint($sumCabang_2);
        // ==========================================================
        // region header
        $header['no'] = "class='bg-info text-center'";
        foreach ($fieldToshows as $kolom => $kolomAlias) {
            $header[$kolomAlias] = "class='bg-info text-center'";

        }
        // $header['sales'] = "class='bg-info text-center'";
        // $header['returns'] = "class='bg-info text-center'";
        // $header['netto'] = "class='bg-info text-center'";


        // foreach ($steps as $num => $nSpec) {
        //     $stepNames[$nSpec['target']] = $nSpec['label'];
        //     $headers[$num] = $header;
        // }
        // endregion header

        if (sizeof($srScr) > 0) {
            //region bodies
            $no = 0;
            $netto = 0;
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
            $rSpecs = array();
            foreach ($srScr as $trJenis => $items) {
                $step_avail = $trJenis;
                $specs = array();


                // arrPrint($item);
                // $step_number = $item->step_number;
                // $tail_code = $item->tail_code;
                // $tail_number = $item->tail_number;
                $no++;
                $specs['no']['value'] = $no;
                $specs['no']['attr'] = "class='text-right'";
                foreach ($fieldToshows as $kolom => $kolomAlias) {

                    if (isset($fieldFormat[$kolom])) {
                        // $fValue = $fieldFormat[$kolom]($kolom, $items->$kolom);
                        $fValue = $fieldFormat[$kolom]($kolom, isset($items->$kolom) ? $items->$kolom : 0);
                    }
                    else {
                        $fValue = isset($items->$kolom) ? $items->$kolom : 0;
                    }


                    if (isset($fieldLink[$kolom])) {
                        $specs[$kolom] = " < a href = '" . base_url() . $fieldLink[$kolom] . $items['id'] . "' > " . $fValue . "</a > ";
                    }
                    else {
                        // cekHitam("$kolom");
                        if ($kolom == "unit_af_spo") {
                            $fValue = (isset($items->unit_ot_spo) ? $items->unit_ot_spo : 0) - (isset($items->unit_ot_cl) ? $items->unit_ot_cl : 0) - (isset($items->unit_ot_spd) ? $items->unit_ot_spd : 0);

                            $fValue = formatField($kolom, $fValue);
                        }
                        if ($kolom == "nilai_af_spo") {
                            $fValue = (isset($items->nilai_ot_spo) ? $items->nilai_ot_spo : 0) - (isset($items->nilai_ot_cl) ? $items->nilai_ot_cl : 0) - (isset($items->nilai_ot_spd) ? $items->nilai_ot_spd : 0);
                            $fValue = formatField($kolom, $fValue);
                        }
                        $specs[$kolom]['value'] = $fValue;
                    }

                    $warna = (($kolom == "trash") && ($fValue == 0)) ? "text - red" : "";

                    $specs[$kolom]['attr'] = isset($fieldAttr[$kolom]) ? $fieldAttr[$kolom] : "class='text-left $warna'";

                }

                // arrPrint($specs);
                // arrPrint($steps);
                if ($trJenis == "982") {
                    $rSpecs[] = $specs;
                }
                if ($trJenis == "582spd") {
                    $spdSpecs[] = $specs;
                }

                $bodies[] = $specs;

            }
            //endregion


            // foreach ($steps as $num => $nSpec) {
            //     $bodies[] = array_merge($spdSpecs, $rSpecs);
            // }
        }
        else {
            $sumSale = 0;
            $sumReturn = 0;
            $bodies = array();
        }
        $footers = array();
        $sumNetto = $sumSale - $sumReturn;
        $jmlFieldToshowa = sizeof($fieldToshows) + 1;
        $footers['summary'] = "class='bg-info text-center' colspan='$jmlFieldToshowa'";
        $footers[formatField('number', $sumSale)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumReturn)] = "class='bg-info text-right'";
        $footers[formatField('number', $sumNetto . ",0")] = "class='bg-info text-right'";

        $confReport_ = "";
        $confReportObject = array();
        // $confReportSubject = array();

        $bulan = "$year-$month";
        $bulan_f = formatTanggal($bulan, 'Y F');
        // cekMerah($bulan_f ." ". $bulan);
        // arrPrintLime($confReport);
        $data = array(
            "mode" => "viewMovement",
            "title" => $confAllReport['title'],
            "subTitle" => "$bulan_f",
            "confAllReport" => $confAllReport,
            "confReportCabang" => $confReportSubject,
            "confReportSubject" => $confReportSubject,
            "confReportObject" => $confReportObject,
            "sumCabang" => isset($sumCabang_2) ? $sumCabang_2 : array(),
            "sumSubject" => isset($sumSubject_2) ? $sumSubject_2 : array(),
            "sumObject" => isset($sumObject_2) ? $sumObject_2 : array(),
            "tblHeadings" => $header,
            "tblBodies" => $bodies,
            "tblFooters" => $footers,
            "names" => isset($names) ? $names : array(),
            "jenisTr" => $this->jenisTr,
            "trName" => "",
        );
        $this->load->view("activityReports", $data);
    }

    public function index()
    {
        // cekHijau();
        $this->accessList = alowedAccess($this->session->login['id']);
        $firstSteps = array();
        if (null != $this->configUi && sizeof($this->configUi) > 0) {
            foreach ($this->configUi as $jenis => $jSpec) {
                if (isset($jSpec['steps'][1])) {
                    $firstSteps[] = "'" . $jSpec['steps'][1]['target'] . "'";
                }
            }
        }

        /* ---------------------------------------------------------------------------------------------
         * addFilternya dimatikan untuk menampilkan seluruh data recent transaksi
         * -----------------------------------------------------------------------------------------------*/

        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        if (sizeof($firstSteps) > 0) {
            // $tr->addFilter("jenis in (" . implode(",", $firstSteps) . ")");
        }
        $arrFilters = array();
        if (sizeof($this->accessList) > 0) {
            //            $arrFilters = array();
            $indsteps = "(";
            foreach ($this->accessList as $jenisMaster => $masterData) {
                foreach ($masterData as $stepNumber => $stepSpec) {
                    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'] . "'");
            }
        }
        // $reqDate = "2020-11-30";
        $reqDate = dtimeNow("Y-m-d");

        $req_dates = array(
            "date(dtime)" => $reqDate,
        );
        $this->db->where($req_dates);
        $tmpHist = $tr->lookupRecentHistories()->result();
        // cekHijau(sizeof($tmpHist));
        // showLast_query("lime");

        $arrayHistory = array();
        $unionHistoryFields = array();
        if (sizeof($tmpHist) > 0) {
            foreach ($tmpHist as $row) {
                //                arrPrint($row);
                $tmp["jenis_label"] = $row->jenis_label;
                $jenisTr = $row->jenis_master;
                $blackListHistoryFields = array(
                    "next_pic",
                    // "dtime",
                );
                $historyFields_0 = isset($this->configUi[$jenisTr]['shortHistoryFields']) ? $this->configUi[$jenisTr]['shortHistoryFields'] : array();
                $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
                $historyFields = array_diff_key($historyFields_0, array_flip($blackListHistoryFields));

                // cekBiru($pairRegistries);

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

                if (sizeof($this->accessList) > 0) {
                    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();
                        //                    cekHere($this->db->last_query());
                        //                    arrPrint($row);
                        if (sizeof($tmpReg) > 0) {
                            foreach ($tmpReg as $regRow) {
                                $param = $regRow->param;
                                $$param = blobDecode($regRow->values);
                            }
                            foreach ($pairRegistries as $eReg) {
                                foreach ($$eReg as $k => $v) {
                                    if (!isset($row->$k)) {

                                        $row->$k = $v;
                                    }
                                }
                            }
                        }
                    }
                    foreach ($historyFields as $fName => $fLabel) {
                        $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : "";

                        $ids_his = blobDecode($row->ids_his);
                        // cekHijau($fName);
                        if ($fName == "nomer_po") {
                            // cekHijau($fLabel);
                            // cekHijau($fLabel . " " . $row->id);
                            if (is_array($fLabel)) {

                                $id_hist = $ids_his;

                                $hisStep = $fLabel['step'];
                                $hisKey = $fLabel['key'];
                                $tNomer = isset($id_hist[$hisStep][$hisKey]) ? $id_hist[$hisStep][$hisKey] : "--";

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

                                // cekBiru($colValue);
                                $tmp[$fName] = $colValue;
                            }
                            else {
                                $tmp[$fName] = "--";
                            }
                        }
                        if ($fName == "nomer_grn") {
                            if (is_array($fLabel)) {
                                // cekHijau($ids_his);
                                $id_hist = $ids_his;

                                $hisStep = $fLabel['step'];
                                $hisKey = $fLabel['key'];
                                $tNomer = isset($id_hist[$hisStep][$hisKey]) ? $id_hist[$hisStep][$hisKey] : "--";

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

                                // cekBiru($colValue);
                                $tmp[$fName] = $colValue;
                            }
                            else {
                                $tmp[$fName] = "--";
                            }
                        }
                    }
                    $tmp['list'] = "<a class='' href='" . base_url() . "Transaksi/viewHistory/$jenisTr'>more <span class='fa fa-arrow-circle-right'></span></a>";
                    $unionHistoryFields = array_merge($unionHistoryFields, $historyFields);
                    $arrayHistory[] = $tmp;
                }
                else {
                    if (array_intersect($aallowedView, $mems)) {
                        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();
                            // cekHere($this->db->last_query());
                            // arrPrint($row);
                            if (sizeof($tmpReg) > 0) {
                                foreach ($tmpReg as $regRow) {
                                    $param = $regRow->param;
                                    $$param = blobDecode($regRow->values);
                                }
                                foreach ($pairRegistries as $eReg) {
                                    foreach ($$eReg as $k => $v) {
                                        if (!isset($row->$k)) {

                                            $row->$k = $v;
                                        }
                                    }
                                }
                            }
                        }
                        foreach ($historyFields as $fName => $fLabel) {
                            $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : "";
                        }

                        $tmp['list'] = "<a class='btn btn-block btn-default' href='" . base_url() . "Transaksi/viewHistory/$jenisTr'><span class='glyphicon glyphicon-th-list'></span></a>";
                        $unionHistoryFields = array_merge($unionHistoryFields, $historyFields);
                        $arrayHistory[] = $tmp;
                    }
                }
            }
        }

        $data = array(
            "mode" => "",
            "title" => "Aktifitas transaksi harian",
            "subTitle" => "$reqDate",
            // "times"            => $months,
            "timeLabel" => "months",
            "names" => isset($names) ? $names : array(),
            // "recaps"           => $recaps,
            // "jenisTr"          => $this->jenisTr,
            // "trName"           =>$this->configUi[$this->jenisTr]["label"],
            // "availFilters"     => $availFilters,
            // "defaultFilter"    => $defaultFilter,
            // "selectedFilter"   => isset($_GET['sID']) ? $_GET['sID'] : $defaultFilter,
            "identifierLabels" => $this->config->item("heTransaksi_report_identifiers"),
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->jenisTr,
            "subPage" => base_url() . get_class($this) . "/viewDaily/" . $this->jenisTr,
            // "historyPage"      => base_url() . "Transaksi/viewHistory/" . $this->jenisTr . "?stID=" . $stID,
            // "stepNames"        => $stepNames,
            // "defaultStep"      => $defaultStep,
            "arrayHistoryLabels" => $unionHistoryFields,
            "arrayHistory" => $arrayHistory,
        );
        $this->load->view("activityReports", $data);
    }

    public function viewSettlement()
    {
        $heTransaksiUi = $this->configUi;
        $jenisParams = array();
        foreach ($heTransaksiUi as $cJenis => $cParams) {
            // $jenisLabel[$cJenis] = $cParams["label"];
            $steps = $cParams['steps'];
            foreach ($steps as $cStep) {

                $jenisParams[$cStep['target']]['label'] = $cStep['label'];
                $jenisParams[$cStep['target']]['settlementMainFields'] = isset($cStep['settlementMainFields']) ? $cStep['settlementMainFields'] : array();
                $jenisParams[$cStep['target']]['settlementItemFields'] = isset($cStep['settlementItemFields']) ? $cStep['settlementItemFields'] : array();
            }
        }
        // cekBiru($jenisParams);

        // $this->load
        $tr = new MdlTransaksi();
        $srcTr = $tr->callMyTransaksi(my_id(), my_cabang_id());
        // = array_keys($srcTr);
        // showLast_query("lime");
        // cekMerah(sizeof($srcTr));
        // arrPrintPink($srcTr);
        foreach ($srcTr as $item_transaksi) {
            $id = $item_transaksi->id;
            $jenis = $item_transaksi->jenis;
            $regItems = blobDecode($item_transaksi->indexing_registry)['items'];
            $regMains = blobDecode($item_transaksi->indexing_registry)['main'];
            // cekBiru($regItems);
            $trRegMainId[$id] = $regMains;
            $trRegItemsId[$id] = $regItems;
            $trJenisId[$jenis][] = $id;
        }
        $srcRegMain = $tr->lookupBaseRegistries($trRegMainId)->result();

        $srcRegItem = $tr->lookupBaseRegistries($trRegItemsId)->result();
        // showLast_query("kuning");
        // arrPrintWebs($trRegMainId);
        // arrPrintWebs($srcReg);
        // arrPrintWebs($srcRegMain);
        // arrPrintWebs($trJenisId);

        foreach ($srcRegItem as $i => $itemReg) {
            $itrId = $itemReg->transaksi_id;
            $mainReg = $srcRegMain[$i];
            $mtrId = $mainReg->transaksi_id;
            // arrPrintPink($mainReg);
            // mati_disini();
            $itemValues = blobDecode($itemReg->values);
            $mainValues = blobDecode($mainReg->values);
            // cekLime("$itrId $mtrId");
            // cekKuning($mainValues);
            // cekPink($itemValues);
            if ($mtrId == $itrId) {

                $mainRegistries[$mtrId] = $mainValues;
                $itemRegistries[$mtrId] = $itemValues;
            }
        }

        // cekBiru($itemRegistries);
        /* ------------------------------------------------------------------------
         * menyusun data per jenis transaksi
         * ------------------------------------------------------------------------*/
        foreach ($trJenisId as $trJenis => $transaksiIds) {

        }

        // mati_disini();
        $data = array(
            "mode" => $this->uri->segment(2),
            "title" => "settlement",
            "subTitle" => "",
            "jenisParams" => $jenisParams,
            "trJenisId" => $trJenisId,
            "mainRegistries" => $mainRegistries,
            "itemRegistries" => $itemRegistries,
        );


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

    public function doSettlement()
    {
        $gmr = img_working();
        echo lgWait("Harap menunggu ...., <br>Transaksi sedang diproses <br>halaman akan refresh setelah proses selesai<br>Sangat tergantung seberapa banyak data yang diproses <img src='$gmr'>");

        arrPrint($_POST);
        $mainRegistries = blobDecode($_POST['mainRegistries']);
        $trJenisId = $_POST['trJenisId'];
        $mainTransaksiIds = array_keys($mainRegistries);
        cekBiru($mainTransaksiIds);
        cekKuning($trJenisId);
        // cekBiru($mainRegistries);
        $targetJenis = $this->uri->segment(3);
        $settlement_dtime = dtimeNow();

        $this->db->trans_begin();
        /* ------------------------------------------------
         * inset ke tb settlement
         * ------------------------------------------------*/
        $this->load->model("Mdls/MdlTransaksiSettlement");
        $st = new MdlTransaksiSettlement();
        $newDatas = array(
            // counter
            "oleh_id" => my_id(),
            "oleh_nama" => my_name(),
            "oleh_dtime" => $settlement_dtime,
            "cabang_id" => my_cabang_id(),
            "cabang_nama" => my_cabang_nama(),
            // approval_dtime
            // approval_counter
            // status
            "data_transaksi_id" => $trJenisId,
        );
        $settlement_id = $st->addData($newDatas);
        showLast_query("hijau");

        /* ------------------------------------------
         * update kol setelement transaski
         * -----------------------------------------*/
        $tr = new MdlTransaksi();
        foreach ($mainTransaksiIds as $transaksi_id) {
            $trCondites = array(
                "id" => $transaksi_id
            );
            $trUpdateDatas = array(
                "settlement_id" => $settlement_id,
                "settlement_dtime" => $settlement_dtime,
            );
            $tr->updateData($trCondites, $trUpdateDatas);
            showLast_query("merah");
        }
        // matiDisini(__LINE__ . " belom commit");
        $this->db->trans_commit();

        echo lgShowSuccess("berhasil", "settlemen berhasil dikirim");
        topReload();
        die();
        // heInitCart($targetJenis);
        //
        // $pl = new Layout();
        //
        // $var = $pl->layout_modal("gggg");
        //
        // echo $var;
        // cekHitam();
        // mati_disini();
    }

    public function doGetSettlement()
    {
        // $gmr = img_working();
        // echo lgWait("Harap menunggu ...., <br>Transaksi sedang diproses <br>halaman akan refresh setelah proses selesai<br>Sangat tergantung seberapa banyak data yang diproses <img src='$gmr'>");

        // arrPrint($_GET);
        // arrPrint($_GET);
        // arrPrint($this->uri->segment_array());
        // arrPrint($this->session->login);
        $pelaku = $this->session->login['id'];
        $div_id = $this->session->login['div_id'];
        // matiHEre($div_id);
        $this->load->model("MdlTransaksi");

        $tr = new MdlTransaksi();
        // $cCode = "_TR_" . $targetTr;
        $oldJenisTr = $this->uri->segment(4);
        $this->jenisTr = $jenisTr = $this->uri->segment(3);
        $config_ui = isset($this->configUi[$this->jenisTr]) ? $this->configUi[$this->jenisTr] : matiHere("undetected jenis transaksi");
        $curentJenis = $config_ui["steps"]["1"]["target"];
        // matiHEre($curentJenis);
        // $this->jenisTr = "589";

        $cCode = "_TR_" . $jenisTr;
        // arrPrint($this->configCore[$jenisTr]);
        $configGates = isset($this->configCore[$jenisTr]['settlementGates']) ? $this->configCore[$jenisTr]['settlementGates'] : array();

        // matiHere( $this->jenisTr);
        //region auto element


        //endregion

        //region list auto session transaksi
        //build main->summary nota
        //build item ->nota
        //build item2_sum ->pembantu kas
        //build item3_sum ->items summary
        //build item4_sum ->main transaksi yg disttlement
        //build item5_sum ->items transksi yang disettlement
        //endregion

        if (sizeof($configGates) == 0) {
            matiHEre("gagal melakukan settlement karena data tidak valid!silahkan hubungi admin anda @" . __LINE__);
        }

        if (isset($_GET['trIDS'])) {
            $listedID = blobDecode($_GET['trIDS']);
            // cekKuning($listedID);
            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "items2" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            if (!isset($_SESSION[$cCode]['items2_sum'])) {
                $_SESSION[$cCode]['items2_sum'] = array();
            }
            if (!isset($_SESSION[$cCode]['items3_sum'])) {
                $_SESSION[$cCode]['items3_sum'] = array();
            }
            if (!isset($_SESSION[$cCode]['items4_sum'])) {
                $_SESSION[$cCode]['items4_sum'] = array();
            }
            //endregion
            //reset session dulu biar bersih
            foreach ($_SESSION[$cCode] as $code => $codeData) {
                unset($_SESSION[$cCode][$code]);
                $_SESSION[$cCode][$code] = array();
            }
            // matiHEre();
            if (sizeof($listedID) > 0) {
                $tr->setFilters(array());
                $tr->addFilter("transaksi_id in '(" . implode(",", $listedID) . ")'");
                $pymData = $tr->lookUpPayment()->result();
                // arrPrintPink($pymData);

                /* --------------------------------------------------
                 * mendapakan registry dimatikan karena data sudah masuk di payment source
                 * ----------------------------------------------*/
                // $tr->addFilter("id in '(" . implode(",", $listedID) . ")'");
                // // $tr->addFilter("settlement_id='0'");
                // $tmpHist0 = $tr->lookupMainTransaksi()->result();
                // cekHitam($this->db->last_query());
                // // matiHere(sizeof($tmpHist0));
                // // arrPrint($tmpHist0);
                // $mainRegs = array();
                // $itemsRegs = array();
                // foreach ($tmpHist0 as $row) {
                //     $tr_id = $row->id;
                //     $indexing_registry = blobDecode($row->indexing_registry);
                //
                //     // arrPrintPink($indexing_registry);
                //
                //     $regIds[] = $indexing_registry['main'];
                //     $regIds[] = $indexing_registry['items'];
                //     $registries = $tr->lookupBaseRegistries($regIds)->result();
                //
                //     // arrPrint($registries);
                //
                //     foreach ($registries as $registriParams) {
                //         $rparam = $registriParams->param;
                //         $rvalues = $registriParams->values;
                //         if ($rparam == "main") {
                //             $mainRegs[$tr_id] = blobDecode($rvalues);
                //         }
                //         if ($rparam == "items") {
                //
                //             $itemsRegs[$tr_id] = blobDecode($rvalues);
                //         }
                //     }
                // }
                // arrPrint($mainRegs);
                // arrPrintWebs($itemsRegs);
                // ----------------------------------------------

                if (sizeof($pymData) > 0) {
                    $mainGate = $configGates['main'];
                    $itemsGate = $configGates['items'];
                    $items2SumGate = $configGates['items2_sum'];
                    // $items3SumGate = $configGates['items3_sum'];
                    // $items4SumGate = $configGates['items4_sum'];
                    // $items5SumGate = $configGates['items5_sum'];

                    $mainGateData = array();
                    $itemGateData = array();
                    $item2GateData = array();
                    // $item3GateData = array();
                    // $item4GateData = array();
                    // $item5GateData = array();

                    //DIVID di overwrite brooo tidak aada di paymentsource
                    $mainFields = $mainGate['fields'];
                    $mainSumFields = $mainGate['sumFields'];
                    foreach ($pymData as $row) {
                        $idsLookUpReg[] = $row->transaksi_id;
                        foreach ($mainFields as $mkey1 => $mkey2) {
                            $mainGateData[$mkey1] = $row->$mkey2;
                        }
                        foreach ($mainSumFields as $mKey => $mKey2) {

                            if (!isset($mainGateData[$mKey])) {
                                $mainGateData[$mKey] = 0;
                            }
                            $mainGateData[$mKey] += $row->$mKey2;
                        }
                        //region items
                        $itemKey = $itemsGate['index_id'];
                        $itemFields = $itemsGate['fields'];
                        foreach ($itemFields as $iKey => $iKey2) {
                            $itemGateData[$row->$itemKey][$iKey] = $row->$iKey2;

                        }
                        //endregion
                        //region item2_sum
                        $item2Key = $items2SumGate['index_id'];
                        $item2Fields = $items2SumGate['fields'];
                        $item2SumFields = $items2SumGate['sumFields'];
                        foreach ($item2Fields as $i2Key => $i2Key2) {
                            $item2GateData[$row->$item2Key][$i2Key] = $row->$i2Key2;
                            $item2GateData[$row->$item2Key]["jml"] = "1";
                        }
                        foreach ($item2SumFields as $sumKey => $sumKey2) {
                            if (!isset($item2GateData[$row->$item2Key][$sumKey])) {
                                $item2GateData[$row->$item2Key][$sumKey] = 0;
                            }
                            $item2GateData[$row->$item2Key][$sumKey] += $row->$sumKey2;
                        }
                        //endregion
                        // arrPrint($row);
                    }
                    // arrPrint($mainGateData);
                    // arrPrint($itemGateData);
                    // arrPrint($item2GateData);
                    // matiHEre($jenisTr);

                    // matiHere(__LINE__ . " ceking");
                    //region builder session
                    $_SESSION[$cCode]['main'] = $mainGateData;
                    $_SESSION[$cCode]['items'] = $itemGateData;
                    $_SESSION[$cCode]['items2_sum'] = $item2GateData;
                    // $_SESSION[$cCode]['items3_sum'] = $item3GateData;
                    // $_SESSION[$cCode]['items4_sum'] = $item4GateData;
                    // $_SESSION[$cCode]['items5_sum'] = $item5GateData;

                    //tambahan main
                    $mainInjector = array(
                        "olehID" => $this->session->login['id'],
                        "olehName" => $this->session->login['nama'],
                        "pihakID" => "-1",//tembak langsung
                        "pihakName" => "PUSAT",
                        "jenis" => $curentJenis,
                        "transaksi_jenis" => $this->jenisTr,
                        "next_step_code" => $this->jenisTr,
                        "next_group_code" => "c_finance",
                        "step_number" => "1",
                        "step_current" => "1",
                        "jenisTr" => $this->jenisTr,
                        "jenisTrMaster" => $this->jenisTr,
                        "jenisTrTop" => $this->jenisTr,
                        "jenisTrName" => "settlement",
                        "stepNumber" => "1",
                        "stepCode" => $this->jenisTr,
                        "dtime" => dtimeNow(),
                        "fulldate" => dtimeNow(),
                        "cabang2_id" => "-1",
                        "cabang2_nama" => "pusat",
                        "place2ID" => "-1",
                        "place2Name" => "pusat",
                        "divID" => $div_id,
                        "divName" => "default",
                        "nilai_bayar" => $_SESSION[$cCode]['main']['nilai_cash'],
                    );
                    //additional detil
                    $tableIn_detailTmp = array(
                        "produk_id" => "id",
                        "produk_kode" => "",
                        "produk_label" => "",
                        "produk_nama" => "nama",
                        "produk_ord_jml" => "1",
                        "produk_ord_hrg" => "harga",
                        // "hpp"            => "hpp",
                        "satuan" => "",
                        "note" => "",
                        "reference" => "",
                        "trash" => "0",
                        "produk_jenis" => $this->jenisTr,
                        "valid_qty" => "1",
                    );
                    $tableIn_detail_values = array(
                        "jml" => "1",
                        "harga" => "harga",
                        "subtotal" => "subtotal",
                        "qty" => "1",
                        "sub_harga" => "sub_harga",
                        "sub_subtotal" => "subtotal",
                        "sub_new_sisa" => "0",
                        "jual_nppn" => "harga_nppn",
                        "hpp" => "hpp",
                        "ppn" => "ppn",
                    );//baca dai session items


                    foreach ($_SESSION[$cCode]['items'] as $itsID => $itsData) {
                        $_SESSION[$cCode]['items'][$itsID]['jenisTr'] = $this->jenisTr;
                        $_SESSION[$cCode]['items'][$itsID]['jml'] = "1";
                        $_SESSION[$cCode]['items'][$itsID]['qty'] = "1";
                        foreach ($tableIn_detail_values as $col => $selectedRow) {
                            $_SESSION[$cCode]["tableIn_detail_values"][$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                        }
                        foreach ($tableIn_detailTmp as $col => $selectedRow) {
                            $_SESSION[$cCode]["tableIn_detail"][$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                        }
                    }


                    foreach ($mainInjector as $mInject => $mValues) {
                        if (!isset($_SESSION[$cCode]['main'][$mInject])) {
                            $_SESSION[$cCode]['main'][$mInject] = $mValues;
                        }
                    }


                    $_SESSION[$cCode]["tableIn_master_values"] = array(
                        "gudang" => isset($mainGateData["gudangID"]) ? $mainGateData["gudangID"] : "",
                        "harga" => $mainGateData["nilai_cash"],
                        "divID" => isset($mainGateData["divID"]) ? $mainGateData["divID"] : "",
                        "subtotal" => $mainGateData["nilai_cash"],
                        "reference" => "0",
                        "nilai_bayar" => "0",
                        "note" => "0",
                    );
                    $_SESSION[$cCode]["tableIn_master"] = array(
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "trash" => "0",
                        "jenis_master" => $this->jenisTr,
                        "jenis_top" => $this->jenisTr,
                        "jenis" => $curentJenis,
                        "jenis_label" => "settlement",
                        "div_id" => isset($_SESSION[$cCode]["main"]["divID"]) ? $_SESSION[$cCode]["main"]["divID"] : "",
                        "div_nama" => isset($_SESSION[$cCode]["main"]["divName"]) ? $_SESSION[$cCode]["main"]["divName"] : "",
                        "dtime" => dtimeNow(),
                        "fulldate" => dtimeNow(),
                        "olehID" => $this->session->login['id'],
                        "olehName" => $this->session->login['nama'],
                        "cabang_id" => $mainGateData["placeID"],
                        "cabang_nama" => $mainGateData['placeName'],
                        "cabang2_id" => "-1",
                        "gudang2_id" => "-1",
                        "gudang2_nama" => "default center warehouse",
                        "cabang2_nama" => "PUSAT",
                        "transaksi_nilai" => $mainGateData["nilai_cash"],
                        "transaksi_jenis" => $this->jenisTr,
                        "gudang_id" => isset($_SESSION[$cCode]["main"]["gudangID"]) ? $_SESSION[$cCode]["main"]["gudangID"] : "",
                        "gudang_nama" => isset($_SESSION[$cCode]["main"]['gudangName']) ? $_SESSION[$cCode]["main"]['gudangName'] : "",
                        // "gudang2_id"      => $mainGateData["gudangID"],
                        // "gudang2_nama"    => $mainGateData['gudangName'],
                        // "keterangan"      => "",
                        // "cabang2_id"      => $mainGateData["placeID"],
                        // "cabang2_nama"    => $mainGateData["placeName"],
                        "status_4" => "11",
                        "trash_4" => "0",
                    );
                    //endregion

                    //trigger builder dergang nilai
                    $this->load->helper("he_value_builder");
                    fillValues($this->jenisTr, 1, 1);
                    $link_settlement = base_url() . "ActivityReport/viewSetorKePusat/$jenisTr";
                }
                else {
                    matiHEre("gagal melakukan settlement karena data tidak valid!silahkan hubungi admin anda @" . __LINE__);
                }
                // arrPrint($temp);

            }
        }

        // matiHEre(__LINE__);
        // $arrAlert = array(
        //     "type"              => "success",
        //     "title"             => "Transaction saved",
        //     //                        "html" => "your order has been saved and ready to process",
        //     "html"              => $this->session->errMsg,
        //     "timer"             => "1500",
        //     "showConfirmButton" => false,
        //     "allowOutsideClick" => false,
        // );
        // echo swalAlert($arrAlert);
        // echo topReload();
        //
        // unset($this->session->errMsg);
    }

    public function viewSetorKePusat()
    {
        // arrPrint($_GET);
        // arrPrint($this->uri->segment_array());
        $this->jenisTr = $jenisTr = $this->uri->segment(3);
        $cCode = "_TR_" . $jenisTr;

        $this->doGetSettlement();
        // unset($_SESSION['_TR_589']);
        // unset($_SESSION['_TR_759']);
        $sesTr = $_SESSION[$cCode];
        $sesTrItems = $sesTr['items'];
        $sesTrMains = $sesTr['main'];


        // cekBiru($cCode);
        // arrPrintPink($_SESSION[$cCode]);
        // arrPrint($sesTrItems);
        // arrPrint($sesTrMains);

        $tgl = date("Y-m-d H:i");
        $tgl_f = formatTanggal($tgl, 'Y-M-d');

        $strMain = "<div class='text-bold margin-bottom-10'>";
        $strMain .= $sesTrMains['cabangName'] . " $tgl_f";
        $strMain .= "</div>";

        $settlementHistoryFields = isset($this->configUi[$jenisTr]['settlementHistoryFields']) ? $this->configUi[$jenisTr]['settlementHistoryFields'] : array();
        // arrPrint($settlementHistoryFields);

        $bodies = "";
        $bodies = array();
        $bodd = array();
        foreach ($sesTrItems as $sesTrItem) {

            $accountId = $sesTrItem['srcAccountID'];
            $accountName = $sesTrItem['srcAccountName'];
            /* ---------------------------------------------
             * jml per account (tunai/non tunai/bank dll
             * ---------------------------------------------*/
            if (!isset($summAccountID[$accountId])) {
                $summAccountID[$accountId] = 0;
            }
            $summAccountID[$accountId] += $sesTrItem['nilai_bayar'];
            $srcAccountNames[$accountId] = $accountName;

            if (!isset($bodies[$accountId])) {
                $bodies[$accountId] = "";
            }

            $bodies[$accountId] .= "<tr>";
            foreach ($settlementHistoryFields as $settlementHistoryField => $settlementHistoryFieldAlias) {
                $nilai = isset($sesTrItem[$settlementHistoryField]) ? $sesTrItem[$settlementHistoryField] : "";
                $nilai_f = formatField($settlementHistoryField, $nilai);

                $bodies[$accountId] .= "<td>$nilai_f</td>";
            }
            $bodies[$accountId] .= "</tr>";

            if (!isset($sumBodies[$accountId])) {
                $sumBodies[$accountId] = 0;
            }
            $sumBodies[$accountId] += $nilai;

        }

        // cekBiru($sumBodies);

        $colSpan = sizeof($settlementHistoryFields) - 1;
        $footers = array();
        foreach ($srcAccountNames as $accId => $srcAccountName) {

            if (!isset($heads[$accId])) {
                $heads[$accId] = "";
            }
            $heads[$accId] .= "<tr class='bg-grey-1'>";
            foreach ($settlementHistoryFields as $settlementHistoryField => $settlementHistoryFieldAlias) {
                $heads[$accId] .= "<th>$settlementHistoryFieldAlias</th>";
            }
            $heads[$accId] .= "</tr>";


            if (!isset($footers[$accId])) {
                $footers[$accId] = "";
            }
            $footers[$accId] .= "<tr class='bg-grey-1'>";
            // foreach ($settlementHistoryFields as $settlementHistoryField => $settlementHistoryFieldAlias) {
            $nilai = $sumBodies[$accId];
            $nilai_f = formatField("harga", $nilai);

            $footers[$accId] .= "<th colspan='$colSpan'>total</th>";
            $footers[$accId] .= "<th>$nilai_f</th>";
            // }
            $footers[$accId] .= "</tr>";
        }

        // cekBiru($summAccountID);;
        // cekBiru($bodies);

        $tbls = "";
        foreach ($srcAccountNames as $accId => $srcAccountName) {

            $tbls .= "<div class='text-uppercase margin-top-20' >$srcAccountName</div>";
            $tbls .= "<table class='table table-bordered table-condensed no-padding no-margin'>";
            $tbls .= $heads[$accId];
            $tbls .= $bodies[$accId];
            $tbls .= $footers[$accId];
            $tbls .= "</table>";
        }

        /* ---------------------------------------
         * per account cash
         * ---------------------------------------*/
        $accBodies = "";
        $accBodies .= "<tr class='bg-grey-0 text-uppercase'>";
        $accBodies .= "<th>nama akun</th>";
        $accBodies .= "<th class='text-right'>nilai</th>";
        $accBodies .= "</tr>";

        $sumNilai = 0;
        foreach ($srcAccountNames as $accId => $srcAccountName) {
            $accBodies .= "<tr>";
            // foreach ($settlementHistoryFields as $settlementHistoryField => $settlementHistoryFieldAlias) {

            $nilai = isset($summAccountID[$accId]) ? $summAccountID[$accId] : "0";
            $nilai_f = formatField("harga", $nilai);

            $sumNilai += $nilai;

            $accBodies .= "<td>$srcAccountName</td>";
            $accBodies .= "<td>$nilai_f</td>";
            // }
            $accBodies .= "</tr>";
        }

        $accBodies .= "<tr class='bg-grey-0'>";
        $sumNilai_f = formatField("harga", $sumNilai);
        $accBodies .= "<th class='text-right text-renggang-10'>TOTAL</th>";
        $accBodies .= "<th>$sumNilai_f</th>";
        $accBodies .= "</tr>";

        $accTbls = "";
        $accTbls .= "<table class='table table-bordered table-condensed no-margin'>";
        $accTbls .= $accBodies;
        $accTbls .= "</table>";

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

        echo $strMain;
        echo $accTbls;
        echo $tbls;

        $link_exce = base_url() . "Transaksi/save/$jenisTr";
        echo "<div class='margin-top-20'>";
        echo "<button type='button' class='btn btn-primary text-uppercase btn-block text-renggang-10' onclick=\"confirm_alert_result('Kirim settlement','ini yakin ya " . number_format($sumNilai) . " akan disetor','$link_exce')\">settlement</button>";
        echo "</div>";
    }

    public function viewPenjualan()
    {
        $getDate = isset($_GET['date']) ? $_GET['date'] : dtimeNow('Y-m');
        $reg_bl = formatTanggal($getDate, 'm');
        $reg_th = formatTanggal($getDate, 'Y');


        $this->load->model("Mdls/MdlCustomer");
        $vd = new MdlCustomer();
        $koloms = array(
            "id",
            "nama",
        );


        $this->db->select($koloms);
        $this->db->order_by('nama', 'asc');
        if (ipadd() == "202.65.117.72") {
            // $this->db->limit(20);
        }
        $src_vendor_0 = $vd->lookupAll()->result();
        // showLast_query("kuning");
        // arrPrint($src_vendor);

        $src_vendor_incative = $vd->lookupAllInactive()->result();
        // showLast_query("kuning");
        // arrPrint($src_vendor_incative);

        // $report_mode = "on_the_fly";
        // if (ipadd() == "202.65.117.72") {
        $report_mode = "db_report";
        // }
        switch ($report_mode) {
            case "on_the_fly":
                /* ----------------------------------------------------
                 * report on the fly
                 * ----------------------------------------------------*/
                $this->load->model("Mdls/MdlReportSql");
                $rp = new MdlReportSql();

                $dStart = "$reg_th-01-01";
                $dStop = $reg_th != dtimeNow('Y') ? "$reg_th-12-31" : $reg_th . dtimeNow('-m-d');
                $jml_bln = $reg_th != dtimeNow('Y') ? 12 : dtimeNow('m');
                $condites = array(
                    'date(dtime) >=' => $dStart,
                    "date(dtime) <=" => $dStop,
                );
                $this->db->where($condites);
                $src_pembelian = $rp->callPembelianVendor();
                // showLast_query("lime");
                $this->db->where($condites);
                $src_pembelian_return = $rp->callPembelianVendorReturn();
                // showLast_query("lime");
                // cekKuning(sizeof($src_pembelian));

                // arrPrintPink($src_pembelian);
                // arrPrintPink($src_pembelian_return);
                foreach ($src_pembelian as $item) {
                    $thn = $item->th;
                    $bln = $item->bl;
                    $ext_id = $item->extern_id;
                    $src_pembelians[$ext_id][$thn][$bln] = $item;
                }

                foreach ($src_pembelian_return as $item) {
                    $thn = $item->th;
                    $bln = $item->bl;
                    $ext_id = $item->extern_id;
                    $src_pembelian_returns[$ext_id][$thn][$bln] = $item;
                }
                // arrPrint($src_pembelians);
                // arrPrint($src_pembelian_returns);

                /* ----------------------------------------------
                 * mendapatkan data vendor yg dinonativkan tapi sudah pernah ada transaksi
                 * ----------------------------------------------*/
                $suppPembelian = array_keys($src_pembelians);
                $suppPembelianReturn = array_keys($src_pembelian_returns);
                $suppPembelianNetto = array_merge($suppPembelianReturn, $suppPembelian);

                // cekHijau(sizeof($suppPembelian));
                // cekHijau(sizeof($suppPembelianReturn));
                break;
            case "db_report":
                /* ----------------------------------------------------
                 * report on db_report
                 * ----------------------------------------------------*/
                $this->db2 = $this->load->database('report', TRUE);
                $this->load->model("Mdls/MdlReport");
                $rp = new MdlReport();

                $dStart = "$reg_th-01-01";
                $dStop = $reg_th != dtimeNow('Y') ? "$reg_th-12-31" : $reg_th . dtimeNow('-m-d');
                $jml_bln = $reg_th != dtimeNow('Y') ? 12 : dtimeNow('m');

                // $rp->setDebug(true);
                $rp->setPeriode("bulanan");
                // $condites = array(
                //     'th' => $reg_th,
                // );
                // $this->db2->where($condites);
                $rp->setTahun($reg_th);
                $src_pembelian = $rp->callPenjualanCustomer();
                // cekKuning($this->db2->last_query());
                // cekHijau($src_pembelian);
                $src_pembelians_netto = array();
                foreach ($src_pembelian as $item) {
                    $thn = $item->th;
                    $bln = $item->bl;
                    $ext_id = $item->subject_id;
                    $src_pembelians_netto[$ext_id][$thn][$bln] = $item;
                }

                // cekPink($src_pembelians_netto);
                $src_pembelians = $src_pembelians_netto;
                $src_pembelian_returns = array();

                $suppPembelianNetto = array_keys($src_pembelians_netto);
                // $suppPembelianReturn = array_keys($src_pembelian_returns);
                // $suppPembelianNetto = array_merge($suppPembelianReturn, $suppPembelian);
                break;
            default:
                matiHere("report mode harap ditentukan");
                break;
        }

        // cekBiru($suppPembelianNetto);

        $iniIkut = array();
        foreach ($src_vendor_incative as $item) {
            $suppInactiveId = $item->id;
            if (in_array($suppInactiveId, $suppPembelianNetto)) {
                $iniIkut[] = $item;
            }
        }
        // cekPink($iniIkut);
        $src_vendor = array_merge($src_vendor_0, $iniIkut);

        $paramDatas = array(
            "kolom" => "customes_id",
            "trJenis" => "582",
            "kolomNilai" => "nilai_ot",
            "trJenisContra" => "982",
            "kolomNilaiContra" => "nilai_in",
        );

        $data = array(
            // "mode"                  => $this->uri->segment(2),
            "mode" => "viewPembelian",
            "title" => "Penjualan per customer",
            "subTitle" => "",
            "src_vendor" => $src_vendor,
            "src_pembelians" => $src_pembelians,
            "src_pembelian_returns" => $src_pembelian_returns,
            "getDate" => $getDate,
            "jml_bln" => $jml_bln,
            "thn" => $reg_th,
            "report_mode" => $report_mode,
            "kolom" => "customers_id",
            // "trJenis"               => str_replace("=","", blobEncode(array("582","580"))),
            "trJenis" => array("582", "580"),
            "kolomNilai" => "nilai_ot",
            "trJenisContra" => "982",
            "kolomNilaiContra" => "nilai_in",
        );

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

    public function viewPembelian()
    {
        $getDate = isset($_GET['date']) ? $_GET['date'] : dtimeNow('Y-m');
        $reg_bl = formatTanggal($getDate, 'm');
        $reg_th = formatTanggal($getDate, 'Y');


        $this->load->model("Mdls/MdlSupplier");
        $vd = new MdlSupplier();
        $koloms = array(
            "id",
            "nama",
        );


        $this->db->select($koloms);
        $this->db->order_by('nama', 'asc');
        if (ipadd() == "202.65.117.72") {
            // $this->db->limit(10);
        }
        $src_vendor_0 = $vd->lookupAll()->result();
        // showLast_query("kuning");
        // arrPrint($src_vendor);

        $src_vendor_incative = $vd->lookupAllInactive()->result();
        // showLast_query("kuning");
        // arrPrint($src_vendor_incative);

        $report_mode = "on_the_fly";
        if (ipadd() == "202.65.117.72") {
            $report_mode = "db_report";
        }
        switch ($report_mode) {
            case "on_the_fly":
                /* ----------------------------------------------------
                 * report on the fly
                 * ----------------------------------------------------*/
                $this->load->model("Mdls/MdlReportSql");
                $rp = new MdlReportSql();

                $dStart = "$reg_th-01-01";
                $dStop = $reg_th != dtimeNow('Y') ? "$reg_th-12-31" : $reg_th . dtimeNow('-m-d');
                $jml_bln = $reg_th != dtimeNow('Y') ? 12 : dtimeNow('m');
                $condites = array(
                    'date(dtime) >=' => $dStart,
                    "date(dtime) <=" => $dStop,
                );
                $this->db->where($condites);
                $src_pembelian = $rp->callPembelianVendor();
                // showLast_query("lime");
                $this->db->where($condites);
                $src_pembelian_return = $rp->callPembelianVendorReturn();
                // showLast_query("lime");
                // cekKuning(sizeof($src_pembelian));

                // arrPrintPink($src_pembelian);
                // arrPrintPink($src_pembelian_return);
                foreach ($src_pembelian as $item) {
                    $thn = $item->th;
                    $bln = $item->bl;
                    $ext_id = $item->extern_id;
                    $src_pembelians[$ext_id][$thn][$bln] = $item;
                }

                foreach ($src_pembelian_return as $item) {
                    $thn = $item->th;
                    $bln = $item->bl;
                    $ext_id = $item->extern_id;
                    $src_pembelian_returns[$ext_id][$thn][$bln] = $item;
                }
                // arrPrint($src_pembelians);
                // arrPrint($src_pembelian_returns);

                /* ----------------------------------------------
                 * mendapatkan data vendor yg dinonativkan tapi sudah pernah ada transaksi
                 * ----------------------------------------------*/
                $suppPembelian = array_keys($src_pembelians);
                $suppPembelianReturn = array_keys($src_pembelian_returns);
                $suppPembelianNetto = array_merge($suppPembelianReturn, $suppPembelian);

                // cekHijau(sizeof($suppPembelian));
                // cekHijau(sizeof($suppPembelianReturn));
                break;
            case "db_report":
                /* ----------------------------------------------------
                 * report on db_report
                 * ----------------------------------------------------*/
                $this->db2 = $this->load->database('report', TRUE);
                $this->load->model("Mdls/MdlReport");
                $rp = new MdlReport();

                $dStart = "$reg_th-01-01";
                $dStop = $reg_th != dtimeNow('Y') ? "$reg_th-12-31" : $reg_th . dtimeNow('-m-d');
                $jml_bln = $reg_th != dtimeNow('Y') ? 12 : dtimeNow('m');

                // $rp->setDebug(true);
                $rp->setPeriode("bulanan");
                // $condites = array(
                //     'th' => $reg_th,
                // );
                // $this->db2->where($condites);
                $rp->setTahun($reg_th);
                $src_pembelian = $rp->callPembelianVendor();
                // cekKuning($this->db2->last_query());
                // cekHijau($src_pembelian);
                $src_pembelians_netto = array();
                foreach ($src_pembelian as $item) {
                    $thn = $item->th;
                    $bln = $item->bl;
                    $ext_id = $item->subject_id;
                    $src_pembelians_netto[$ext_id][$thn][$bln] = $item;
                }

                // cekPink($src_pembelians_netto);
                $src_pembelians = $src_pembelians_netto;
                $src_pembelian_returns = array();

                $suppPembelianNetto = array_keys($src_pembelians_netto);
                // $suppPembelianReturn = array_keys($src_pembelian_returns);
                // $suppPembelianNetto = array_merge($suppPembelianReturn, $suppPembelian);
                break;
            default:
                matiHere("report mode harap ditentukan");
                break;
        }

        // cekBiru($suppPembelianNetto);

        $iniIkut = array();
        foreach ($src_vendor_incative as $item) {
            $suppInactiveId = $item->id;
            if (in_array($suppInactiveId, $suppPembelianNetto)) {
                $iniIkut[] = $item;
            }
        }
        // cekPink($iniIkut);
        $src_vendor = array_merge($src_vendor_0, $iniIkut);

        $data = array(
            "mode" => $this->uri->segment(2),
            "title" => "Pembelian per vendor",
            "subTitle" => "",
            "src_vendor" => $src_vendor,
            "src_pembelians" => $src_pembelians,
            "src_pembelian_returns" => $src_pembelian_returns,
            "getDate" => $getDate,
            "jml_bln" => $jml_bln,
            "thn" => $reg_th,
            "report_mode" => $report_mode,
            "kolom" => "suppliers_id",
            "trJenis" => "467",
            "kolomNilai" => "nilai_in",
            "trJenisContra" => "967",
            "kolomNilaiContra" => "nilai_ot",
        );

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

    public function viewDetile()
    {
        $p = New Layout("jdl", "subJdl", "application/template/settlement.html");
        // $mainId = $this->uri->segment(3);
        $kolom = $this->uri->segment(3);
        $$kolom = $this->uri->segment(4);
        $trJenis = blobDecode($this->uri->segment(5));
        // $expTrJenis = explode(",", $trJenis_0);
        // $trJenis= $expTrJenis;
        // cekBiru($trJenis);
        // matiHere(__LINE__);
        $thn = $this->uri->segment(6);
        $bln = $this->uri->segment(7);

        $heTransaksiUi = $this->configUi;
        $jenisParams = array();
        foreach ($heTransaksiUi as $cJenis => $cParams) {
            // $jenisLabel[$cJenis] = $cParams["label"];
            $steps = $cParams['steps'];
            foreach ($steps as $cStep) {

                $jenisParams[$cStep['target']]['label'] = $cStep['label'];
                $jenisParams[$cStep['target']]['settlementMainFields'] = isset($cStep['settlementMainFields']) ? $cStep['settlementMainFields'] : array();
                $jenisParams[$cStep['target']]['settlementItemFields'] = isset($cStep['settlementItemFields']) ? $cStep['settlementItemFields'] : array();
            }
        }

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

        // cekBiru($trJenis);
        $condites = array(
            "$kolom" => $$kolom,
            // "jenis"        => $trJenis,
            "year(dtime)" => $thn,
            "month(dtime)" => $bln,
        );
        if (is_array($trJenis)) {
            // cekBiru($trJenis);
            $this->db->where_in("jenis", $trJenis);
        }
        else {
            $this->db->where("jenis", $trJenis);
        }
        $srcTr = $tr->lookupByCondition($condites)->result();
        // showLast_query("lime");
        // matiHere(__LINE__);
        $trRegMainId = array();
        $trRegItemsId = array();
        foreach ($srcTr as $item_transaksi) {
            $id = $item_transaksi->id;
            $jenis = $item_transaksi->jenis;
            $ids_his = $item_transaksi->ids_his;
            $step_current = $item_transaksi->step_number;
            $regItems = blobDecode($item_transaksi->indexing_registry)['items'];
            $regMains = blobDecode($item_transaksi->indexing_registry)['main'];
            // cekBiru($regItems);
            $noGlobal = showHistoriCounterNumbers($ids_his, $step_current, $oleh_id, true);
            $trIdsHis[$id] = $ids_his;
            $trNoGlobals[$id] = $noGlobal;
            $trRegMainId[$id] = $regMains;
            $trRegItemsId[$id] = $regItems;
            $trJenisId[$jenis][] = $id;
        }
        $srcRegMain = $tr->lookupBaseRegistries($trRegMainId)->result();

        $srcRegItem = $tr->lookupBaseRegistries($trRegItemsId)->result();
        // showLast_query("kuning");
        // arrPrintWebs($trRegMainId);
        // arrPrintWebs($srcReg);
        // arrPrintWebs($srcRegMain);
        // arrPrintWebs($trJenisId);

        foreach ($srcRegItem as $i => $itemReg) {
            $itrId = $itemReg->transaksi_id;
            $mainReg = $srcRegMain[$i];
            $mtrId = $mainReg->transaksi_id;
            $noGlob = $trNoGlobals[$mtrId];
            // arrPrintPink($mainReg);
            // mati_disini();
            $itemValues = blobDecode($itemReg->values);
            $mainValues = blobDecode($mainReg->values) + array("no_global" => $noGlob);
            // cekLime("$itrId $mtrId");
            // cekKuning($mainValues);
            // cekPink($itemValues);
            if ($mtrId == $itrId) {

                $mainRegistries[$mtrId] = $mainValues;
                $itemRegistries[$mtrId] = $itemValues;
            }
        }

        $conten_str = "";
        $strData = "";
        foreach ($trJenisId as $trJenis => $transaksiIds) {

            $trJenis_fields = isset($jenisParams[$trJenis]["settlementMainFields"]) ? $jenisParams[$trJenis]["settlementMainFields"] : array();
            $trJenis_items = isset($jenisParams[$trJenis]["settlementItemFields"]) ? $jenisParams[$trJenis]["settlementItemFields"] : array();
            $jmlKolomItem = sizeof($trJenis_items);

            /* --------------------------------------------------
             * header
             * --------------------------------------------------*/
            $tbHead = "";
            $sumBawah = array();
            if (sizeof($trJenis_fields) > 0) {
                $tbHead .= "<tr class='text-uppercase'>";
                $tbHead .= "<th class='text-center bg-info' rowspan='2'>no</th>";
                foreach ($trJenis_fields as $trField => $trFieldAttr) {
                    $hLabel = $trFieldAttr['label'];
                    $tbHead .= "<th class='text-center bg-info' rowspan='2'>$hLabel</thclas>";

                    $sumBawah[$trJenis] = isset($trFieldAttr['format']) ? 1 : 0;
                }
                if (sizeof($trJenis_items) > 0) {

                    // foreach ($trJenis_items as $trField => $trFieldAttr) {
                    //     $hLabel = $trFieldAttr['label'];
                    $tbHead .= "<th class='text-center bg-info' colspan='$jmlKolomItem'>rincian</th>";
                    // }
                }
                $tbHead .= "</tr>";

                $tbHead .= "<tr class='bg-info text-uppercase'>";
                foreach ($trJenis_items as $trJenis_item) {
                    $label = $trJenis_item['label'];
                    $attr = isset($trJenis_item['attr']) ? $trJenis_item['attr'] : "";

                    $tbHead .= "<th $attr>$label</th>";
                }
                $tbHead .= "</tr>";

            }
            // cekPink($sumBawah);
            /* --------------------------------------------------
             * body
             * --------------------------------------------------*/
            $tbBodi = "";
            $no = 0;
            $sumFields = array();
            foreach ($transaksiIds as $transaksiId) {
                $no++;
                $mainSpeks = $mainRegistries[$transaksiId];
                $trItems = $itemRegistries[$transaksiId];
                $tbBodi .= "<tr>";
                if (sizeof($trJenis_fields) > 0) {
                    $tbBodi .= "<td class='text-right' title='$transaksiId'>$no</td>";
                }
                /* ------------------------------------------------
                 * main
                 * ------------------------------------------------*/
                foreach ($trJenis_fields as $trField => $trFieldAttr) {
                    $mainValue = isset($mainSpeks[$trField]) ? $mainSpeks[$trField] : null;
                    $mainValue_f = isset($trFieldAttr['format']) ? $trFieldAttr['format']($trField, $mainValue) : $mainValue;
                    $attr = isset($trFieldAttr['attr']) ? $trFieldAttr['attr'] : "";

                    $tbBodi .= "<td $attr>$mainValue_f</td>";

                    if (isset($trFieldAttr['sumFields'])) {
                        if (!isset($sumFields[$trField])) {
                            $sumFields[$trField] = 0;
                        }
                        $sumFields[$trField] += $mainValue;
                    }
                    // sumFields
                }

                /* ------------------------------------------------
                 * items
                 * ------------------------------------------------*/
                $tbBodi .= "<td colspan='$jmlKolomItem'>";
                if (sizeof($trJenis_fields) > 0) {
                    $tbBodi .= "<table class='table table-condensed table-striped no-margin'>";
                    /* ------------------------------------------------
                     * items-body
                     * ------------------------------------------------*/
                    foreach ($trItems as $iKey => $trItem) {
                        if (sizeof($trJenis_items) > 0) {
                            $tbBodi .= "<tr>";
                            foreach ($trJenis_items as $trField => $trFieldAttr) {
                                $itemValue = isset($trItem[$trField]) ? $trItem[$trField] : 0;
                                $attr = isset($trFieldAttr['attr']) ? $trFieldAttr['attr'] : "";
                                // cekBiru($trFieldAttr['format'] . " $trField");
                                $itemValue_f = isset($trFieldAttr['format']) ? $trFieldAttr['format']($trField, $itemValue) : $itemValue;
                                // $itemValue_f = isset($trFieldAttr['format']) ? $trFieldAttr['format']($trField,$fValue) : $fValue;

                                $tbBodi .= "<td $attr>$itemValue_f</td>";
                            }
                            $tbBodi .= "</tr>";
                        }
                    }
                    $tbBodi .= "</table>";
                }
                else {
                    $tbBodi .= sizeof($trItems) . " <i> config ui $trJenis belum terdefinisi</i>";
                }
                $tbBodi .= "</td>";

                $tbBodi .= "</tr>";
            }
            // arrPrint($sumFields);
            /* ------------------------------------------------
             * items-footer
             * ------------------------------------------------*/
            $tbFooter = "";
            if (isset($sumBawah[$trJenis]) && ($sumBawah[$trJenis] > 0)) {
                $tbFooter .= "<tr>";
                $tbFooter .= "<th>-</th>";
                foreach ($trJenis_fields as $trField => $trFieldAttr) {
                    $fValue = isset($sumFields[$trField]) ? $sumFields[$trField] : "";

                    $fValue_f = isset($trFieldAttr['format']) && !isset($trFieldAttr['format_footer']) ? $trFieldAttr['format']($trField, $fValue) : $fValue;

                    $tbFooter .= "<th>$fValue_f</th>";
                }
                $tbFooter .= "<th colspan='$jmlKolomItem'>-</th>";
                $tbFooter .= "</tr>";
            }

            $tbInduk = "<table class='table table-condensed table-striped no-margin table-bordered'>";
            $tbInduk .= $tbHead;
            $tbInduk .= $tbBodi;
            $tbInduk .= $tbFooter;
            $tbInduk .= "</table>";

            // $link_cetak = base_url() . "Printing/settlement/$mainId/$trJenis";
            $btn_box = "<button type='button' class='btn btn-sm pull-right' data-widget='collapse' data-toggle='tooltip' title='' style='margin-right: 5px;' data-original-title='Collapse'><i class='fa fa-minus'></i></button>";
            // $btn_box .= "<button type='button' class='btn btn-sm pull-right' data-toggle='tooltip' title='cetak' style='margin-right: 5px;' data-original-title='cetak' onclick=\"window.open('$link_cetak','status=1,width=600');\"><i class='fa fa-print'></i></button>";
            $trJenis_label = isset($jenisParams[$trJenis]["label"]) ? $jenisParams[$trJenis]["label"] : $trJenis;
            $trJenis_debug = show_debuger() == 1 ? " :: $trJenis" : "";
            $p->setLayoutBoxHeadingProperty("title='$trJenis'");
            $p->setLayoutBoxHeadingCss("text-uppercase");
            $p->setLayoutBoxHeading($trJenis_label . $trJenis_debug, $btn_box);
            $p->setLayoutBoxCss("box-info");
            $p->setLayoutBoxBody(true);
            $p->setLayoutBoxBodyCss("no-padding");
            $strData .= $p->layout_box($tbInduk);
        }

        echo $strData;
    }

    /*
     * excel pembelian per produk
     * */
    public function viewPembelianProduk()
    {
        $getDate = isset($_GET['date']) ? $_GET['date'] : dtimeNow('Y-m');
        $reg_bl = formatTanggal($getDate, 'm');
        $reg_th = formatTanggal($getDate, 'Y');


        $this->load->model("Mdls/MdlProduk");
        $vd = new MdlProduk();
        $koloms = array(
            "id",
            "kode",
            "nama",
        );

        $this->db->select($koloms);
        $this->db->order_by('kode', 'asc');
        if (ipadd() == "202.65.117.72") {
            // $this->db->limit(6000);
        }
        $src_vendor = $vd->lookupAll()->result();
        // showLast_query("lime");
        // arrPrint($src_vendor);
        // matiHere(__LINE__);

        $this->load->model("Mdls/MdlReport");
        $rp = new MdlReport();

        $dStart = "$reg_th-01-01";
        $dStop = $reg_th != dtimeNow('Y') ? "$reg_th-12-31" : $reg_th . dtimeNow('-m-d');
        $jml_bln = $reg_th != dtimeNow('Y') ? 12 : dtimeNow('m');
        $condites = array(
            'date(dtime) >=' => $dStart,
            "date(dtime) <=" => $dStop,
        );
        $rp->setCondites($condites);
        // $rp->setDebug(true);
        $rp->setPeriode("bulanan");
        $src_pembelian = $rp->lookupPembelianProdukAll()->result();
        // $this->db->where($condites);
        // $src_pembelian_return = $rp->callPembelianVendorReturn();


        // showLast_query("lime");
        // cekKuning(sizeof($src_pembelian));
        // arrPrintPink($src_pembelian);
        // arrPrintPink($src_pembelian_return);

        // matiHere(__LINE__);
        $src_pembelians = array();
        $src_pembelian_datas = array();
        foreach ($src_pembelian as $item) {
            $thn = $item->th;
            $bln = $item->bl;
            $ext_id = $item->subject_id;
            $src_pembelians[$ext_id][$thn][$bln] = $item;
            $src_pembelian_datas[$ext_id] = $item;
        }

        // foreach ($src_pembelian_return as $item) {
        //     $thn = $item->th;
        //     $bln = $item->bl;
        //     $ext_id = $item->extern_id;
        //     $src_pembelian_returns[$ext_id][$thn][$bln] = $item;
        // }
        // arrPrint($src_pembelians);
        // arrPrint($src_pembelian_returns);

        $data = array(
            "mode" => $this->uri->segment(2),
            "title" => "Pembelian per vendor",
            "subTitle" => "",
            "src_vendor" => $src_vendor,
            "src_pembelians" => $src_pembelians,
            // "src_pembelian_returns" => $src_pembelian_returns,
            "getDate" => $getDate,
            "jml_bln" => $jml_bln,
            "thn" => $reg_th,
        );

        // $this->load->view("activityReports", $data);
        // cekBiru($src_pembelians);
        // excelllll----------------
        $this->load->library('Excel');
        $ex = new Excel();

        $kolom_datas = array(
            "unit_in" => "qty beli",
            "unit_ot" => "qty return",
            "unit_af" => "qty net",
            "nilai_in" => "nilai beli",
            "nilai_ot" => "nilai return",
            "nilai_af" => "nilai nett",
        );
        $this->file = $_SERVER['SERVER_NAME'] . " pemelian produk bulanan tahun $reg_th";
        // region pairing data
        // $xLabels = $this->x['entries'];
        // $yLabels = $this->y['entries'];
        // $zLabels = $this->z['entries'];
        // arrPrint($zLabels);
        $number = 0;
        $datas = array();
        // $this->ix = "cabang";
        // $this->iy = "produk";
        // $this->iz = "hargaProduk";
        $dataSpec = array();
        foreach ($src_vendor as $item) {
            // foreach ($src_pembelians as $item) {
            $pId = $item->id;
            $pNama = $item->nama;
            $pKode = $item->kode;
            // $yId =>
            $yNames = $pNama;
            $number++;
            // cekHijau("$yNames");
            $yNames_f = trim($pKode . " " . html_entity_decode($yNames));
            $dataSpec['nama'] = "$yNames_f";

            // $arrHeaderRel = array();
            for ($i = 1; $i <= $jml_bln; $i++) {
                foreach ($kolom_datas as $kolom_data => $labeling) {
                    $lbl = "$labeling $reg_th-$i";
                    $key = "$kolom_data-$reg_th-$i";

                    $dataSpec[$key] = 0;

                    $arrHeaderRel[$key] = array(
                        "label" => $lbl,
                        "type" => "integer",
                    );
                }
            }
            if (isset($src_pembelians[$pId])) {
                foreach ($src_pembelians[$pId] as $tahun => $src_pembelian_bl) {
                    foreach ($src_pembelian_bl as $bulan => $item) {
                        foreach ($kolom_datas as $kolom_data => $labeling) {

                            $lbl = "$labeling $tahun-$bulan";
                            $key = "$kolom_data-$tahun-$bulan";

                            $dataSpec[$key] = isset($item->$kolom_data) ? $item->$kolom_data : 0;

                            // $arrHeaderRel[$key] = array(
                            //     "label" => $lbl,
                            //     "type"  => "integer",
                            // );
                        }
                    }

                }
            }
            else {
                //    kosong
            }


            $datas[] = (object)$dataSpec;
        }
        // endregion pairing data

        // cekBiru($arrHeaderRel);
        // arrPrint($datas);
        // matiHere(__LINE__);

        // $this->load->model('MdlEmployee');
        // $tm = new MdlEmployee();
        // $datasX = $tmpX = $tm->lookupAll()->result();
        // arrPrint($datasX);
        // matiHere(__LINE__);
        // ksort($arrHeaderRel);
        $headers = (array(
                "nama" => array(
                    "label" => "Nama Produk",
                    "type" => "string",
                ),

            ) + $arrHeaderRel);
        // arrPrint($datas);
        // arrPrint($headers);
        // matiHere();
        $ex->setTitleFile($this->file);
        $ex->setDatas($datas);
        $ex->setHeaders($headers);

        return $ex->writer();
        // excelllll----------------
        echo lgShowSuccess("ok", "boss");
    }

    public function debug()
    {
        // cekHijau($ipadd);
        if (isset($_GET['r']) && $_GET['r'] > 0) {
            header("refresh:" . $_GET['r']);
        }
        $key = isset($_GET['key']) ? $_GET['key'] : "";
        $this->jenisTr = $this->uri->segment(3);
        $cCode = "_TR_" . $this->jenisTr;
        cekBiru($cCode);
        if (isset($_SESSION[$cCode])) {
            cekKuning("shopping-cart (creator)");
            if (strlen($key) > 0) {
                if (isset($_SESSION[$cCode][$key])) {
                    arrPrintPink($_SESSION[$cCode][$key]);
                }
                else {
                    arrPrintPink($key . " :: NULL");
                }
            }
            arrprint($_SESSION[$cCode]);
        }
        else {
            die("the gate index you want to debug has not been formed yet!");
        }
    }


    /*
     * settlemet pos
     */
    public function doSettlementPos_sebelum_update()
    {

        $selectedRegistries = array("main", "items");
        $currentTr = $this->uri->segment(4);
        $targetModul = $this->uri->segment(5);
        $targetJenis = $this->uri->segment(6);

        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("oleh_id='" . $this->session->login['id'] . "'");
        $tr->addFilter("settlement_id='1'");
        $tr->addFilter("link_id='0'");
        $tr->addFilter("jenis='" . $currentTr . "'");
        $date1 = isset($_GET['date1']) ? $_GET['date1'] : mati_disini("Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : mati_disini("Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.");
        $this->db->where("fulldate>='" . $date1 . "'");
        $this->db->where("fulldate<='" . $date2 . "'");
        $tempTrans = $tr->lookUpAll()->result();

        $ids = array();
        $idsCancel = array();
        $idsNett = array();
        if (sizeof($tempTrans) > 0) {
            foreach ($tempTrans as $temp) {
                cekHere("TrID: ".$temp->id." | nomer: ".$temp->nomer." | trjenis: ".$temp->jenis." | trash_4: ".$temp->trash_4);
                $ids[$temp->id] = $temp->id;
                if($temp->trash_4==1){
                    $idsCancel[$temp->id] = $temp->id;
                }
                else{
                    $idsNett[$temp->id] = $temp->id;
                }
            }

            //panggil library curl untuk koneksi ke API server UTAMA
            $this->load->library("Curl");
            $curl = New Curl();

            //ambil register
            $tr->setFilters(array());
//            $this->db->limit(1);
            $tempReg = $tr->lookupBaseDataRegistries($ids)->result();
            $newItems = array();
            $tempItems = array();
            $sumProduk = array();
            $itemsTrans = array();
            $totalCash = 0;
            $addDiskon = 0;
            $diskonProduk = 0;
            $diskonCust = 0;
            $totalHargaJual = 0;
            $totalDppPPn = 0;
            $totalPPn = 0;
            $totalNonDpp = 0;
            $totalCukai = 0;
            $totalCancel = 0;
            $preInjectTrData = array();
            if (sizeof($tempReg) > 0) {
                foreach ($tempReg as $regData) {
                    $trID = $regData->transaksi_id;
                    if(!isset($idsCancel[$trID])){
                        $main = blobdecode($regData->main);
                        $items = blobdecode($regData->items);

                        $preInjectTrData[$trID] = $main["nomer"];
                        $itemsbase64 = base64_encode(json_encode($items));
                        $tempItems = $main + array("produk" => $itemsbase64, "nomor" => $main["nomer"]);
                        $newItems["items"][] = (object)$tempItems;
                        $itemsTrans[$trID] = $tempItems;
                        foreach ($items as $itemDataTmp) {
                            $itemDataTmp['cukai_produk'] = 0;
                            $tmpSumItems = array(
                                "id" => $itemDataTmp['id'],
                                "nama" => $itemDataTmp['nama'],
                                "jml" => $itemDataTmp['jml'],
                                "qty_unit" => $itemDataTmp['qty_unit'],
                                "harga_list" => $itemDataTmp['harga_list'],
                                "harga_jual" => $itemDataTmp['harga_jual'],
                                "discNilai" => $itemDataTmp['discNilai'],
                                "discPersen" => $itemDataTmp['discPersen'],
                                "harga" => $itemDataTmp['harga'],
                                "subtotal" => $itemDataTmp['subtotal'],
                                "ppn_produk" => $itemDataTmp['ppn_produk'],
                                "ppnFactor" => $itemDataTmp['ppnFactor'],
                                "ppn" => $itemDataTmp['ppn'],
                                "sub_ppn" => $itemDataTmp['sub_ppn'],
                                "satuan" => $itemDataTmp['satuan'],
                                "satuan_id" => $itemDataTmp['satuan_id'],
                                "satuan_factor_qty" => $itemDataTmp['satuan_factor_qty'],
                                "satuan_factor_id" => $itemDataTmp['satuan_factor_id'],
                                "satuan_factor_nama" => $itemDataTmp['satuan_factor_nama'],
                            );

                            $sumProduk[$itemDataTmp["id"]][] = $tmpSumItems;
//                        $sumProduk[$itemDataTmp["id"]][] = $itemDataTmp; //aslinya

                            $diskonProduk += $itemDataTmp['discNilai']*1>0 ? $itemDataTmp['discNilai']*$itemDataTmp['jml'] : 0;
                            $totalHargaJual += $itemDataTmp['harga_jual']*1>0 ? $itemDataTmp['harga_jual']*$itemDataTmp['jml'] : 0;
                            $totalDppPPn += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;
                            $totalPPn += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['sub_ppn'] : 0;
                            $totalNonDpp += $itemDataTmp['ppn_produk']*1==0 ? $itemDataTmp['subtotal'] : 0;
                            $totalCukai += $itemDataTmp['cukai_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;

                        }
                        $totalCash += $main["grand_total"];
                        $diskonCust += $main["disc"];
                        $addDiskon += $main["add_disc"];

                        cekUngu("transaksi_nilai: ". $main["grand_total"]);
                    }
                    else{
                        $totalCancel += isset($idsCancel[$trID]) ? $main["grand_total"] : 0;
                    }

                }
            }
            else {
                matiHEre("no data to execute. silahkan relogin untuk membersihkan sesi");
            }

            echo "total Harga Jual: $totalHargaJual <br>";
            echo "diskon Produk: $diskonProduk <br>";
            echo "total Hrg Jual - diskon Produk: ($totalHargaJual-$diskonProduk) = ".($totalHargaJual-$diskonProduk)." <br>";

            echo "total Diskon Customer: $diskonCust <br>";
            echo "total Diskon Tambahan: $addDiskon <br>";
            echo "total Diskon Customer+Diskon Tambahan ($diskonCust+$addDiskon) = ".($diskonCust+$addDiskon)." <br>";

            echo "total Cash: $totalCash  = ".(($totalHargaJual-($diskonProduk+$diskonCust+$addDiskon)))."<br>";
            echo "total Dpp PPn: $totalDppPPn <br>";
            echo "total PPn: $totalPPn <br>";
            echo "total Non PPn: $totalNonDpp <br>";
            echo "total Cukai: $totalCukai <br><br>";

            echo "total Cancel: $totalCancel <br>";
            arrPrint($newItems);
            matiHere();

            //ambil trData
            $tr->setFilters(array());
            $tr->addFilter("transaksi_id in (" . implode(",", $idsNett) . ")");
            $trData = $tr->lookupTransaksiData()->result();
            $newTrData = array();
            if (sizeof($trData) > 0) {
                $newNr = array();
                foreach ($trData as $iix => $trDataTmp) {
                    $trNr = (array)$trDataTmp + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                    $newNr[$iix] = (object)$trNr;
                }
                $newTrData["trData"] = $newNr;
            }

//                "data" => $tempTrans, //coba untuk tidak di ikutkan pengiriman API
            $doSendApi = array(
                "row" => count($tempTrans),
                "currentTr" => $currentTr,
                "targetJenis" => $targetJenis,
                "login" => $this->session->login,

                "newItems" => $newItems,
                "sumProduk" => $sumProduk,
                "itemsTrans" => $itemsTrans,
                "totalCash" => $totalCash,
                "newTrData" => $newTrData,
                "ids" => $ids,
            );


            $dataEncoded = array(
                "data" => blobEncode($doSendApi)
            );

            $sendToMainServer = $curl->_simple_call("post", ADM_DOMAIN ."/penjualan/ActivityReportApi/doSettlementPosAPI", $dataEncoded);


            $status = json_decode($sendToMainServer, true)["status"];

            if(!$status){
                $result = json_decode($sendToMainServer, true);
                echo json_encode($result);
                matiHere('mati dulu di POS');
            }
        }

        $this->db->trans_begin();
        $ids = array();
        if (sizeof($tempTrans) > 0) {
            foreach ($tempTrans as $temp) {
                $ids[$temp->id] = $temp->id;
            }

            //region buka registry

            //endregion
            //region build items dari main ke gerbang items
            $tr->setFilters(array());
            $tempReg = $tr->lookupBaseDataRegistries($ids)->result();
            // arrPrint($tempReg);
            $newItems = array();
            $tempItems = array();
            $sumProduk = array();
            $itemsTrans = array();
            $totalCash = 0;
            $preInjectTrData = array();
            if (sizeof($tempReg) > 0) {
                foreach ($tempReg as $regData) {
                    $trID = $regData->transaksi_id;
                    $main = blobdecode($regData->main);
                    $items = blobdecode($regData->items);
                    $preInjectTrData[$trID] = $main["nomer"];
                    $itemsbase64 = base64_encode(json_encode($items));
                    $tempItems = $main + array("produk" => $itemsbase64, "nomor" => $main["nomer"]);
                    $newItems["items"][] = (object)$tempItems;
                    $itemsTrans[$trID] = $tempItems;
                    foreach ($items as $itemDataTmp) {
                        $sumProduk[$itemDataTmp["id"]][] = $itemDataTmp;
                    }
                    $totalCash += $main["tagihan"];
                }
            }
            else {
                matiHEre("no data to execute. silahkan relogin untuk membersihkan sesi");
            }
            //endregion
            //region build trData
            $tr->setFilters(array());
            $tr->addFilter("transaksi_id in (" . implode(",", $ids) . ")");
            $trData = $tr->lookupTransaksiData()->result();
            $newTrData = array();
            if (sizeof($trData) > 0) {
                $newNr = array();
                foreach ($trData as $iix => $trDataTmp) {
                    $trNr = (array)$trDataTmp + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                    $newNr[$iix] = (object)$trNr;
                }
                $newTrData["trData"] = $newNr;
            }
            //endregion

            $fildsSumItems = array(
                "id" => "id",
                "nama" => "nama",
                "no_part" => "no_part",
                "satuan" => "satuan",
                "harga" => "harga",
                "subtotal" => "subtotal",
                "jml" => "jml",
                "qty" => "qty",
                "produk_qty" => "produk_qty",
                "placeID" => "placeID",
                "cabangID" => "cabangID",
            );
            $sumProdukNew = array();
            if (sizeof($sumProduk) > 0) {
                foreach ($sumProduk as $ii => $data) {
                    $sumSubtotal = 0;
                    $sumJml = 0;
                    foreach ($data as $itemsdetail) {
                        $sumProdukNew["sumProduk"][$ii] = $itemsdetail;
                        $sumSubtotal += $itemsdetail["subtotal"];
                        $sumJml += $itemsdetail["jml"];
                    }
                    $sumProdukNew["sumProduk"][$ii]["subtotal"] = $sumSubtotal;
                    $sumProdukNew["sumProduk"][$ii]["jml"] = $sumJml;
                    $sumProdukNew["sumProduk"][$ii]["qty"] = $sumJml;
                }
            }
            $data = $newItems + $newTrData + $sumProdukNew;

            $toInsertBlob = blobEncode($data);

            //region array builder transaction
            $itemsTmp = array(
                "handler" => "Selectors/_processSelectBiaya",
                "id" => "transaksi_id",
                "harga" => "harga",
                "subtotal" => "subtotal",
                "nama" => "nama",
                "label" => "",
                "reference" => "",
                "qty" => "1",
                "name" => "name",
                "sub_harga" => "sub_harga",
                "sub_subtotal" => "sub_total",
                "olehID" => "olehID",
                "olehName" => "olehName",
                "placeID" => "placeID",
                "placeName" => "cabang_nama",
                "cabangID" => "cabangID",
                "cabangName" => "cabangName",
                "gudangID" => "gudangID",
                "gudangName" => "gudangName",
                "gudang2ID" => "-1",
                "gudang2Name" => "default center warehouse",
                "jenisTr" => $targetJenis,
                "next_substep_code" => $targetJenis,
                "next_subgroup_code" => "o_finance",
                "sub_step_number" => "1",
                "sub_step_current" => "1",
                "nilai_bayar" => "",
                "new_sisa" => "0",
                "sub_new_sisa" => "0",
                "note" => "",
                "pihakID" => "-1",
                "pihakName" => "PUSAT",
            );
            $items2 = array();
            $items2_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $tableIn_masterTmp = array(
                "trash" => "0",
                "jenis_master" => $targetJenis,
                "jenis_top" => $targetJenis,
                "jenis" => $targetJenis,
                "jenis_label" => "request depresiasi",
                "div_id" => "2",
                "div_nama" => "default",
                "oleh_id" => "olehID",
                "oleh_nama" => "olehName",
                "cabang_id" => "cabangID",
                "cabang_nama" => "cabangName",
                "transaksi_nilai" => "sub_total",
                "transaksi_jenis" => $targetJenis,
                "gudang_id" => "gudangID",
                "gudang_nama" => "gudangName",
                "gudang2_id" => "-1",
                "gudang2_nama" => "default center warehouse",
                "keterangan" => "",
                "cabang2_id" => "-1",
                "cabang2_nama" => "PUSAT",
                "pihakMainName" => "",
                "pihakMainID" => "",
            );
            $tableIn_detailTmp = array(
                "produk_id" => "transaksi_id",
                "produk_kode" => "",
                "produk_label" => "",
                "produk_nama" => "nomer",
                "produk_ord_jml" => "1",
                "produk_ord_hrg" => "nilai_cash",
                "hpp" => "nilai_cash",
                "satuan" => "",
                "note" => "",
                "reference" => "",
                "trash" => "0",
                "produk_jenis" => "invoice",
                "valid_qty" => "1",
            );
            $tableIn_detail2_sum = array();
            $tableIn_detail_rsltItems = array();
            $tableIn_detail_rsltItems2 = array();
            $tableIn_master_valuesTmp = array(
                "gudang2" => "-1",
                "harga" => "harga",
                "divID" => "2",
                "subtotal" => "subtotal",
                "reference" => "0",
                "nilai_bayar" => "0",
                "note" => "0",
            );
            $tableIn_detail_valuesTmp = array(
                "jml" => "1",
                "harga" => "nilai_cash",
                "subtotal" => "nilai_cash",
                "qty" => "1",
                "sub_harga" => "nilai_cash",
                "sub_subtotal" => "nilai_cash",
                "sub_new_sisa" => "0",
            );
            $tableIn_detail_values_rsltItemsTmp = array();
            $tableIn_detail_values_rsltItems2Tmp = array();
            $tableIn_detail_values2_sumTmp = array();
            $tableIn_detail2 = array();
            $main_add_values = array();
            $main_add_fields = array();
            $main_elements = array(
                "gudang2" => Array
                (
                    "elementType" => "dataModel",
                    "name" => "gudang2",
                    "key" => "-1",
                    "labelSrc" => "name",
                    "label" => "gudang dc",
                    "labelValue" => "default center warehouse",
                    "mdl_name" => "MdlGudangDefault_center",
                    "contents" => "YToxOntzOjQ6Im5hbWEiO3M6MDoiIjt9",
                    "contents_intext" => print_r(array("nama" => ""),true),
                ),
            );
            $main_inputs = array();
            $main_inputs_orig = array();
            $receiptDetailFieldsTmp = array(
                "produk_nama" => "nomer",
            );
            $receiptSumFieldsTmp = array(
                "harga" => "total amount",
            );
            $receiptDetailFields2 = array();
            $receiptSumFields2 = array();
            $tableIn_detail_values2_sum = array();
            $items3 = array();
            $items3_sum = array();
            $tableIn_detail_values_rsltItems = array();
            $tableIn_detail_values_rsltItems2 = array();
            //endregion
            //region builder mian
            $main = array(
                "olehID" => $this->session->login["id"],
                "olehName" => $this->session->login["nama"],
                "placeID" => $this->session->login["cabang_id"],
                "placeName" => $this->session->login["cabang_nama"],
                "cabangID" => $this->session->login["cabang_id"],
                "cabangName" => $this->session->login["cabang_nama"],
                "gudangID" => $this->session->login["gudang_id"],
                "gudangName" => $this->session->login["gudang_nama"],
                "tokoID" => $this->session->login["toko_id"],
                "jenisTr" => $targetJenis,
                "jenisTrMaster" => $targetJenis,
                "jenisTrTop" => $targetJenis,
                "jenisTrName" => "settlement",
                "stepNumber" => "1",
                "stepCode" => $targetJenis,
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "harga" => $totalCash,
                "divID" => "2",
                "divName" => $this->session->login["div_nama"],
                "subtotal" => $totalCash,
                "harga" => $totalCash,
                "nilai_cash" => $totalCash,
                "reference" => "0",
                "jenis" => $targetJenis,
                "transaksi_jenis" => $targetJenis,
                "next_step_code" => $targetJenis,
                "next_group_code" => "c_finance",
                "step_number" => "1",
                "step_current" => "1",
                "longitude" => "",
                "lattitude" => "",
                "accuracy" => "",
                "nilai_bayar" => "0",
                "new_sisa" => "0",
                "note" => "0",
                "description" => "",
                "pihakDisc" => "",
                "pihakName" => $this->session->login["nama"],
                "pihakID" => $this->session->login["id"],

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

            //region builder tabel in master
            $tableIn_master = array(
                "trash" => "0",
                "jenis_master" => $targetJenis,
                "jenis_top" => $targetJenis,
                "jenis" => $targetJenis,
                "jenis_label" => "settlement",
                "div_id" => "2",
                "div_nama" => "default",
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "oleh_id" => $this->session->login["id"],
                "oleh_nama" => $this->session->login["nama"],
                "cabang_id" => $this->session->login["cabang_id"],
                "cabang_nama" => $this->session->login["cabang_nama"],
                "transaksi_nilai" => $totalCash,
                "transaksi_jenis" => $targetJenis,
                "gudang_id" => $this->session->login["gudang_id"],
                "gudang_nama" => $this->session->login['gudang_nama'],
                "pihakMainName" => $this->session->login["id"],
                "pihakMainID" => $this->session->login["nama"],
            );

            //endregion
            //region builder table in detil
            $tableIn_detail = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($tableIn_detailTmp as $col => $selectedRow) {
                    $tableIn_detail[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            // arrPrintPink($tableIn_detail);
            //endregion builder table in detil
            //region table in master values
            $tableIn_master_values = array(
                "gudang" => $this->session->login["gudang_id"],
                "harga" => $totalCash,
                "divID" => "2",
                "subtotal" => $totalCash,
                "reference" => "0",
                "nilai_bayar" => "0",
                "note" => "0",
            );
            //endregion table in master values
            //region build table in detil values
            $tableIn_detail_values = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($tableIn_detail_valuesTmp as $col => $selectedRow) {
                    $tableIn_detail_values[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }

//            arrPrintWebs($tableIn_detail_values);
            //endregion build table in detil values
            //region build table receipDetailFields
            $receiptDetailFields = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($receiptDetailFieldsTmp as $col => $selectedRow) {
                    $receiptDetailFields[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion
            //region receiptSumFields
            $receiptSumFields = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($receiptSumFieldsTmp as $col => $selectedRow) {
                    $receiptSumFields[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion

            $configUi       = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiUi');
            $configLayout   = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiLayout');
            $configCore     = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiCore');
            $configValues   = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiValues');

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

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

                //region penomoran receipt NEW
                //region penomoran receipt
                $this->load->model("CustomCounter");

                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $configCustomParams = $configValues['counters'];

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

                        $cContent[$cRawParams][$cRawValues] = $paramSpec["value"];
                        switch ($paramSpec["id"]) {
                            case 0: //===counter type is new
                                $addData = array(
                                    "toko_id" => my_toko_id(),
                                    "toko_nama" => my_toko_nama(),
                                );
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                break;
                            default: //===counter to be updated
                                $cn->updateCount($paramSpec["id"], $paramSpec["value"]);
                                break;
                        }
                    }
                }
                cekMerah( $this->db->last_query() );
                arrPrint($cContent);
                $appliedCounters = base64_encode(serialize($cContent));
                $appliedCounters_inText = print_r($cContent, true);

                //region NUMBERING

                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");

                $counterForNumber = array($configValues['formatNota']);
                foreach ($counterForNumber as $i => $c0RawParams) {
                    $c0Params = explode(",", $c0RawParams);
                    foreach($c0Params as $k=>$cRawParams){
                        $dParams = explode("|", $cRawParams);

                        if(count($dParams)>1){
                            if (!in_array($cRawParams, $configValues['counters'])) {
                                die(__LINE__ . "( $cRawParams ) Used number should be registered in counters config as well");
                            }
                        }
                    }
                }

                $tmpNomorNota="";
                $arrNomorNota=array();
                foreach ($counterForNumber as $i => $c0RawParams) {
                    $c0Params = explode(",", $c0RawParams);
                    $c0Values = array();
                    foreach($c0Params as $k=>$cRawParams){
                        $arrRawParams = explode("|", $cRawParams);
                        if(sizeof($arrRawParams)>1){
                            $cRawParamsValues = array();
                            foreach($arrRawParams as $key){
                                $cRawParamsValues[$key] = $main[$key];
                            }
                            $cRawParamsValuesK = implode("|", array_keys($cRawParamsValues));
                            $cRawParamsValuesV = implode("|", $cRawParamsValues);
                            $arrNomorNota[] = digit_4($cContent[$cRawParamsValuesK][$cRawParamsValuesV]);
                        }
                        else{
                            $cRawParamsValuesK = $arrRawParams[0];
                            $cRawParamsValuesV = $main[$arrRawParams[0]];
                            if($arrRawParams[0]=="fulldate"){
                                $arrNomorNota[] = $arrRawParams[0]."|".date("mY", strtotime($cRawParamsValuesV));
                            }
                            elseif($arrRawParams[0]=="stepCode"){
                                $arrNomorNota[] = $cRawParamsValuesV;
                            }
                            elseif($arrRawParams[0]=="placeID"){
                                $arrNomorNota[] = digit_4($cRawParamsValuesV);
                            }
                            elseif($arrRawParams[0]=="customerID"){
                                $arrNomorNota[] = digit_4($cRawParamsValuesV);
                            }
                            elseif($arrRawParams[0]=="olehID"){
                                $arrNomorNota[] = digit_4($cRawParamsValuesV);
                            }
                            else{
                                $arrNomorNota[] = digit_4($cContent[$cRawParamsValuesK][$cRawParamsValuesV]);
                            }
                        }
                    }
                }

                $stepNumber = 1;
                $tmpNomorNota = implode("-", $arrNomorNota);

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

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

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

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

                    $tr = new MdlTransaksi();
                    $tr->addFilter("transaksi.cabang_id='" . $tableIn_master['cabang_id'] . "'");
                    $insertID = $tr->writeMainEntries($tableIn_master);

                    showLast_query("hijau");

                    $mongoList['main'][] = $insertID;
                    $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $tableIn_master);

                    $mongoList['main'][] = $epID;

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

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

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

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

                    $addValues = array(
                        //===references
                        "id_master" => $insertID,
                        "id_top" => $insertID,
                        "ids_prev" => "",
                        "ids_prev_intext" => "",
                        "nomer_top" => $main['nomer'],
                        "nomers_prev" => "",
                        "nomers_prev_intext" => "",
                        "jenises_prev" => "",
                        "jenises_prev_intext" => "",
                        "ids_his" => $idHis_blob,
                        "ids_his_intext" => $idHis_intext,
                    );
                    foreach ($addValues as $key => $val) {
                        $tableIn_master[$key] = $val;
                    }

                }
                if (sizeof($tableIn_master_values) > 0) {
                    if (isset($configValues['tableIn']['mainValues'])) {
                        $inserMainValues = array();
                        foreach ($configValues['tableIn']['mainValues'] as $key => $src) {
                            if (isset($tableIn_master_values[$key])) {
                                $dd = $tr->writeMainValues($insertID, array(
                                    "key" => $key,
                                    "value" => $tableIn_master_values[$key],
                                ));
                                $inserMainValues[] = $dd;
                                $mongoList['mainValues'][] = $dd;
                            }

                        }
                        if (sizeof($inserMainValues) > 0) {
                            $arrBlob = blobEncode($inserMainValues);
                            $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                        }
                    }
                }
                if (sizeof($main_add_values) > 0) {
                    $inserMainValues = array();
                    foreach ($main_add_values as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoList['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }

                    //                            cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                }
                if (sizeof($main_inputs) > 0) {
                    foreach ($main_inputs as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoList['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }
                    //                            cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                }
                if (sizeof($main_add_fields) > 0) {
                    foreach ($main_add_fields as $key => $val) {
                        $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                    }
                    //                            cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                }
                if (sizeof($main_elements) > 0) {
                    foreach ($main_elements as $elName => $aSpec) {
                        $tr->writeMainElements($insertID, array(
                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                            "name" => $aSpec['name'],
                            "label" => isset($aSpec['label']) ? $aSpec['label'] : "",
                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",
                        ));

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

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

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

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

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

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

                //region nulis paymentSource
                $stepCode = $configUi['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_source");
                if (array_key_exists($stepCode, $paymentSources)) {
                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs[1] as $paymentSrcConfig) {
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $arrDataPym = array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $this->session->login['id'],
                                "extern_nama" => $this->session->login['nama'],
                                "nomer" => $main['nomer'],
                                "externValueBlob" => $toInsertBlob,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => isset($main["nilai_cash"]) ? $main["nilai_cash"] : 0,
                                "terbayar" => 0,
                                "sisa" => isset($main["nilai_cash"]) ? $main["nilai_cash"] : 0,
                                "cabang_id" => $this->session->login["cabang_id"],
                                "cabang_nama" => $this->session->login["cabang_nama"],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                            );
                            arrPrint($arrDataPym);
                            $pymSrcID = $tr->writePaymentSrc($insertID, $arrDataPym);
                            cekMerah($this->db->last_query());

                            $kolomValidasi = isset($paymentSrcConfig['kolom']) ? $paymentSrcConfig['kolom'] : array();
                            if (sizeof($kolomValidasi) > 0) {
                                $trr = New MdlTransaksi();
                                $trr->setFilters(array());
                                $pym = $trr->lookupPaymentSrcByID($pymSrcID)->result();
                                cekKuning($this->db->last_query());
                                foreach ($kolomValidasi as $kolom_validasi) {
                                    if (isset($pym[0]->$kolom_validasi)) {
                                        if ($pym[0]->$kolom_validasi == NULL) {
                                            $msg = "Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.";
                                            mati_disini($msg);
                                        }
                                        else {
                                            cekUngu("kolom ada isinya");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion

                //region update transaksi yang sudah disettle
                if ($insertID) {
                    $tr->setFilters(array());
                    foreach ($ids as $u => $idToupdate) {
                        $tr->setTableName("transaksi");
                        $tr->setFilters(array());
                        $wheres = array(
                            "id" => $idToupdate,
                        );
                        $dataUpd = array(
                            "settlement_id" => $insertID,
                        );
                        $tr->updateData($wheres, $dataUpd);
                        cekHitam($this->db->last_query());
                    }
                }
                //endregion
            }
        }
        else {
            matiHEre("semua transaksi penjualan sudah settle");
        }


//        $result = json_decode($sendToMainServer, true);
//        echo json_encode($result);
//        echo "<script>top.HoldOn.close();</script>";
//        matiHere("STOP DULU TRANSAKSI POS BELUM COMMIT");

        $this->db->trans_commit();

        $arrAlert = array(
            "type" => "success",
            "title" => "Settlement saved",
            "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );
        echo swalAlert($arrAlert);
        echo "<script>top.window.location.reload();</script>";
        echo "</script>";
        unset($this->session->errMsg);
    }

    public function previewSettlement(){

        $timeStart = date('Y-m-d H:i:s');
        $heTransaksiUi = $this->configUi;
        $selectedRegistries = array("main", "items");
        $currentTr = $this->uri->segment(4);
        $targetModul = $this->uri->segment(5);
        $targetJenis = $this->uri->segment(6);

        $action_target = $_POST['action_target'];

        $this->load->model("Mdls/MdlEmployeeCabang");
        $emp = new MdlEmployeeCabang();

        $this->load->model("Mdls/MdlProduk");
        $pr = new MdlProduk();

        $this->load->model("Mdls/MdlHargaProduk");
        $prc = new MdlHargaProduk();

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

        $tr->addFilter("oleh_id='" . $this->session->login['id'] . "'");
        $tr->addFilter("settlement_id='1'");
//        $tr->addFilter("settlement_id='3791'");
//        $tr->addFilter("settlement_id='3173'");
        $tr->addFilter("link_id='0'");
        $this->db->where("jenis IN('582','982')");

        $date1 = isset($_GET['date1']) ? $_GET['date1'] : mati_disini("Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : mati_disini("Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.");

        $this->db->where("fulldate>='" . $date1 . "'");
        $this->db->where("fulldate<='" . $date2 . "'");

        $tempTrans = $tr->lookUpAll()->result();
//        $arrTempProduk = $pr->lookUpAll()->result();
//        $arrTempProdukPrice = $prc->lookUpAll()->result();

//matiHere(__LINE__);

        $emp->addFilter("oto_settlement=1");
        $emp->addFilter("cabang_id='" . $this->session->login['cabang_id'] . "'");
        $arrEmployee = $emp->lookUpAll()->result();

//        arrPrint($arrEmployee);

//        $produkPrice = array();
//        if(!empty($arrTempProdukPrice)){
//            foreach($arrTempProdukPrice as $k => $row){
//                $produkPrice[$row->produk_id][$row->jenis_value] = $row->nilai;
//            }
//        }

        $ids = array();
        $idsCancel = array();
        $idsNett = array();
        if (sizeof($tempTrans) > 0) {

            foreach ($tempTrans as $temp) {
                $ids[$temp->id] = $temp->id;
                if($temp->trash_4==1){
                    $idsCancel[$temp->id] = $temp->id;
                }
                else{
                    $idsNett[$temp->id] = $temp->id;
                }
            }

            //ambil register
            $tr->setFilters(array());
            $tempReg = $tr->lookupBaseDataRegistries($ids)->result();

            $newItems = array();
            $newItemsCanceled = array();
            $tempItems = array();
            $sumProduk = array();
            $sumProdukCanceled = array();
            $itemsTrans = array();
            $itemsTransCanceled = array();

            $totalCash = 0;
            $totalAddDiskon = 0;
            $totalDiskonProduk = 0;
            $totalDiskonCust = 0;
            $totalHargaJual = 0;
            $totalDppPPn = 0;
            $totalPPn = 0;
            $totalNonDpp = 0;
            $totalCukai = 0;
            $totalCancel = 0;

            $totalCashCanceled = 0;
            $totalAddDiskonCanceled = 0;
            $totalDiskonProdukCanceled = 0;
            $totalDiskonCustCanceled = 0;
            $totalHargaJualCanceled = 0;
            $totalDppPPnCanceled = 0;
            $totalPPnCanceled = 0;
            $totalNonDppCanceled = 0;
            $totalCukaiCanceled = 0;

            $freeProduk=array();
            $freeProdukCanceled=array();

            $preInjectTrData = array();
            $preInjectTrDataCanceled = array();

            if (sizeof($tempReg) > 0) {
                foreach ($tempReg as $regData) {
                    $trID = $regData->transaksi_id;
                    if(!isset($idsCancel[$trID])){
                        $main = blobdecode($regData->main);
//                        arrPrint($main);
//                        matiHere();
                        $items = blobdecode($regData->items);
                        $preInjectTrData[$trID] = $main["nomer"];
                        $preItems = array();
                        $diskonProduk=0;
                        $hargaJual=0;
                        $dppPPn=0;
                        $pPn=0;
                        $nonDpp=0;
                        $cukai=0;

                        $preItemsCanceled = array();
                        $diskonProdukCanceled=0;
                        $hargaJualCanceled=0;
                        $dppPPnCanceled=0;
                        $pPnCanceled=0;
                        $nonDppCanceled=0;
                        $cukaiCanceled=0;

                        foreach ($items as $itemDataTmp) {

                            if($itemDataTmp['jenisTr'] == "582"){
                                //bagian jual
                                if( isset($itemDataTmp['free_items']) ){
                                    $freeProduk[] = $itemDataTmp['free_items'];
                                }

                                $itemDataTmp['cukai_produk'] = 0;
                                $tmpSumItems = array(
                                    "id" => $itemDataTmp['id'],
                                    "produk_id" => $itemDataTmp['id'],
                                    "nama" => $itemDataTmp['nama'],
                                    "produk_nama" => $itemDataTmp['nama'],
                                    "barcode" => $itemDataTmp['barcode'],
                                    "kode" => $itemDataTmp['barcode'],
                                    "produk_kode" => $itemDataTmp['barcode'],
                                    "jml" => $itemDataTmp['jml'],
                                    "produk_qty" => $itemDataTmp['jml'],
                                    "qty_unit" => $itemDataTmp['qty_unit'],
                                    "harga_list" => $itemDataTmp['harga_list'],
                                    "harga_jual" => $itemDataTmp['harga_jual'],
                                    "discNilai" => $itemDataTmp['discNilai'],
                                    "discPersen" => $itemDataTmp['discPersen'],
                                    "harga" => $itemDataTmp['harga'],
                                    "subtotal" => $itemDataTmp['subtotal'],
                                    "ppn_produk" => isset($itemDataTmp['tipe_pajak']) ? $itemDataTmp['tipe_pajak'] : 1,
                                    "ppnFactor" => isset($itemDataTmp['ppnFactor']) ? $itemDataTmp['ppnFactor'] : my_ppn_factor(),
                                    "ppn" => $itemDataTmp['ppn'],
                                    "sub_ppn" => $itemDataTmp['sub_ppn'],
                                    "satuan" => $itemDataTmp['satuan'],
                                    "satuan_id" => $itemDataTmp['satuan_id'],
                                    "satuan_factor_qty" => $itemDataTmp['satuan_factor_qty'],
                                    "satuan_factor_id" => $itemDataTmp['satuan_factor_id'],
                                    "satuan_factor_nama" => $itemDataTmp['satuan_factor_nama'],
                                );

//                        $sumProduk[$itemDataTmp["id"]][] = $itemDataTmp; //aslinya

                                $sumProduk[$itemDataTmp["id"]][] = $tmpSumItems;
                                $preItems[$main["nomer"]][$itemDataTmp["id"]] = $tmpSumItems;

                                $diskonProduk   += $itemDataTmp['discNilai']*1>0 ? $itemDataTmp['discNilai']*$itemDataTmp['jml'] : 0;
                                $hargaJual      += $itemDataTmp['harga_jual']*1>0 ? $itemDataTmp['harga_jual']*$itemDataTmp['jml'] : 0;
                                $dppPPn         += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;
                                $pPn            += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['sub_ppn'] : 0;
                                $nonDpp         += $itemDataTmp['ppn_produk']*1==0 ? $itemDataTmp['subtotal'] : 0;
                                $cukai          += $itemDataTmp['cukai_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;

                            }
                            elseif($itemDataTmp['jenisTr']=="982"){

                                //bagian cancel
                                if( isset($itemDataTmp['free_items']) ){
//                                    arrPrintPink('free_items (982)');
//                                    arrPrintPink($itemDataTmp['free_items']);
                                    $freeProdukCanceled[] = $itemDataTmp['free_items'];
                                }

                                $itemDataTmp['cukai_produk'] = 0;
                                $tmpSumItems = array(
                                    "id" => $itemDataTmp['id'],
                                    "produk_id" => $itemDataTmp['id'],
                                    "nama" => $itemDataTmp['nama'],
                                    "produk_nama" => $itemDataTmp['nama'],
                                    "barcode" => isset($itemDataTmp['barcode']) ? $itemDataTmp['barcode'] : "",
                                    "kode" => isset($itemDataTmp['barcode']) ? $itemDataTmp['barcode'] : "",
                                    "produk_kode" => isset($itemDataTmp['barcode']) ? $itemDataTmp['barcode'] : "",
                                    "jml" => $itemDataTmp['jml'],
                                    "produk_qty" => $itemDataTmp['jml'],
                                    "harga_list" => $itemDataTmp['harga_list'],
                                    "harga_jual" => $itemDataTmp['harga_jual'],
                                    "discNilai" => $itemDataTmp['discNilai'],
                                    "discPersen" => $itemDataTmp['discPersen'],
                                    "harga" => $itemDataTmp['harga'],
                                    "subtotal" => $itemDataTmp['subtotal'],
                                    "ppn_produk" => isset($itemDataTmp['tipe_pajak']) ? $itemDataTmp['tipe_pajak'] : 1,
                                    "ppnFactor" => $itemDataTmp['ppnFactor'],
                                    "ppn" => $itemDataTmp['ppn'],
                                    "sub_ppn" => $itemDataTmp['sub_ppn'],
                                    "satuan" => $itemDataTmp['satuan'],
                                    "satuan_id" => $itemDataTmp['satuan_id'],

//                                    "qty_unit" => $itemDataTmp['qty_unit'],
//                                    "satuan_factor_qty" => $itemDataTmp['satuan_factor_qty'],
//                                    "satuan_factor_id" => $itemDataTmp['satuan_factor_id'],
//                                    "satuan_factor_nama" => $itemDataTmp['satuan_factor_nama'],
                                );

//                        $sumProduk[$itemDataTmp["id"]][] = $itemDataTmp; //aslinya

                                $sumProdukCanceled[$itemDataTmp["id"]][] = $tmpSumItems;
                                $preItemsCanceled[$main["nomer"]][$itemDataTmp["id"]] = $tmpSumItems;

                                $diskonProdukCanceled   += $itemDataTmp['discNilai']*1>0 ? $itemDataTmp['discNilai']*$itemDataTmp['jml'] : 0;
                                $hargaJualCanceled      += $itemDataTmp['harga_jual']*1>0 ? $itemDataTmp['harga_jual']*$itemDataTmp['jml'] : 0;
                                $dppPPnCanceled         += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;
                                $pPnCanceled            += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['sub_ppn'] : 0;
                                $nonDppCanceled         += $itemDataTmp['ppn_produk']*1==0 ? $itemDataTmp['subtotal'] : 0;
                                $cukaiCanceled          += $itemDataTmp['cukai_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;

                            }

                        }

                        if( $main["jenisTr"] == "582"){

                            $totalCash          += $main["grand_total"];
                            $totalDiskonCust    += isset($main["disc"]) ? $main["disc"] : 0;
                            $totalAddDiskon     += isset($main["add_disc"]) ? $main["add_disc"]*1 : 0;

                            $totalDiskonProduk  += $diskonProduk;
                            $totalHargaJual     += $hargaJual;
                            $totalDppPPn        += $dppPPn;
                            $totalPPn           += $pPn;
                            $totalNonDpp        += $nonDpp;
                            $totalCukai         += $cukai;

                            $buildMainTmp=array(
                                "olehID" => $main['olehID'],
                                "sellerID" => $main['olehID'],
                                "olehName" => $main['olehName'],
                                "sellerName" => $main['olehName'],
                                "placeID" => $main['placeID'],
                                "placeName" => $main['placeName'],
                                "cabangID" => $main['cabangID'],
                                "cabangName" => $main['cabangName'],
                                "gudangID" => $main['gudangID'],
                                "gudangName" => $main['gudangName'],
                                "divID" => $main['divID'],
                                "tokoID" => $main['tokoID'],
                                "tokoNama" => $main['tokoNama'],
                                "stepCode" => $main['stepCode'],
                                "dtime" => $main['dtime'],
                                "fulldate" => $main['fulldate'],
                                "harga" => $main['harga'],
                                "grand_total" => $main['grand_total'],
                                "bayar" => isset($main['bayar']) ? $main['bayar'] : 0,
                                "oto_diskon" => isset($main['oto_diskon']) ? $main['oto_diskon'] : "",
                                "cash_account" => $main['cash_account'],
                                "cash_account__label" => $main['cash_account__label'],

                                "diskon_produk" => $diskonProduk, //diskon dari potongan produk
                                "add_disc" => $totalAddDiskon, //diskon tambahan (manual input diskon)
                                "diskon_tambahan_nilai" => $main['diskon_tambahan_nilai'], //diskon customer

                                "harga_jual" => $hargaJual,
                                "dpp_ppn" => $dppPPn,
                                "ppn" => $pPn,
                                "non_dpp" => $nonDpp,
                                "cukai" => $cukai,

                                "transaksi_id" => $main['transaksi_id'],
//                                "paymentMethod_cash" => $main['paymentMethod_cash'],
//                            "paymentMethod_cash" => $main['paymentMethod_cash'],

                                "harga_nett2" => $main['harga'],
                                "tagihan" => $main['grand_total'],
                                "kembali" => $main['kembali'],
                            );
//                        }
                            $itemsbase64 = base64_encode(json_encode($preItems[$main["nomer"]]));
                            $tempItems = $buildMainTmp + array("produk" => $itemsbase64, "nomor" => $main["nomer"]);
                            $newItems["items"][] = (object)$tempItems;
                            $itemsTrans[$trID] = $tempItems;
//                        cekUngu("transaksi_nilai: ". $main["grand_total"]);
                        }
                        else{

                            $totalCashCanceled          += $main["grand_total"];
                            $totalDiskonCustCanceled    += isset($main["disc"]) ? $main["disc"] : 0;
                            $totalAddDiskonCanceled     += isset($main["add_disc"]) ? $main["add_disc"]*1 : 0;

                            $totalDiskonProdukCanceled  += $diskonProdukCanceled;
                            $totalHargaJualCanceled     += $hargaJualCanceled;
                            $totalDppPPnCanceled        += $dppPPnCanceled;
                            $totalPPnCanceled           += $pPnCanceled;
                            $totalNonDppCanceled        += $nonDppCanceled;
                            $totalCukaiCanceled         += $cukaiCanceled;

                            $buildMainTmpCanceled=array(
                                "olehID" => $main['olehID'],
                                "sellerID" => $main['olehID'],
                                "olehName" => $main['olehName'],
                                "sellerName" => $main['olehName'],
                                "placeID" => $main['placeID'],
                                "placeName" => $main['placeName'],
                                "cabangID" => $main['cabangID'],
                                "cabangName" => $main['cabangName'],
                                "gudangID" => $main['gudangID'],
                                "gudangName" => $main['gudangName'],
                                "divID" => $main['divID'],
                                "tokoID" => $main['tokoID'],
                                "tokoNama" => $main['tokoNama'],
                                "stepCode" => $main['stepCode'],
                                "dtime" => $main['dtime'],
                                "fulldate" => $main['fulldate'],
                                "harga" => $main['harga'],
                                "grand_total" => $main['grand_total'],
                                "bayar" => isset($main['bayar']) ? $main['bayar'] : 0,
                                "oto_diskon" => isset($main['oto_diskon']) ? $main['oto_diskon'] : "",
                                "cash_account" => $main['cash_account'],
                                "cash_account__label" => $main['cash_account__label'],

                                "diskon_produk" => $diskonProduk, //diskon dari potongan produk
                                "add_disc" => $totalAddDiskon, //diskon tambahan (manual input diskon)
                                "diskon_tambahan_nilai" => $main['diskon_tambahan_nilai'], //diskon customer

                                "harga_jual" => $hargaJual,
                                "dpp_ppn" => $dppPPn,
                                "ppn" => $pPn,
                                "non_dpp" => $nonDpp,
                                "cukai" => $cukai,

                                "transaksi_id" => $main['transaksi_id'],
                                "paymentMethod_cash" => $main['paymentMethod_cash'],

                                "harga_nett2" => $main['harga'],
                                "tagihan" => $main['grand_total'],
                                "kembali" => $main['kembali'],
                            );

                            $itemsbase64Canceled = base64_encode(json_encode($preItemsCanceled[$main["nomer"]]));
                            $tempItemsCanceled = $buildMainTmpCanceled + array("produk" => $itemsbase64Canceled, "nomor" => $main["nomer"]);
                            $newItemsCanceled["items"][] = (object)$tempItemsCanceled;
                            $itemsTransCanceled[$trID] = $tempItemsCanceled;

                        }
                    }
                    else{
                        $main = blobdecode($regData->main);
                        $totalCancel += isset($idsCancel[$trID]) ? $main["grand_total"] : 0;
                    }
                }
            }
            else {
                matiHEre("no data to execute. silahkan relogin untuk membersihkan sesi");
            }

            $freeProdukSum=array();
            if(!empty($freeProduk)){
                foreach( $freeProduk as $ky => $arrDistProduk ){
                    foreach( $arrDistProduk as $idDisc => $distProduk ){
                        if(!isset($freeProdukSum[$distProduk['free_produk_id']])){
                            $freeProdukSum[$distProduk['free_produk_id']] = array();
                        }
                        if(!isset($freeProdukSum[$distProduk['free_produk_id']]['qty'])){
                            $freeProdukSum[$distProduk['free_produk_id']]['qty'] = 0;
                        }
                        $freeProdukSum[$distProduk['free_produk_id']]['nama_produk'] = $distProduk['free_produk_nama'];
                        $freeProdukSum[$distProduk['free_produk_id']]['qty'] += $distProduk['free_qty'];
                    }
                }
            }

            $freeProdukCanceledSum=array();
            if(!empty($freeProdukCanceled)){
                foreach( $freeProdukCanceled as $ky => $arrDistProduk ){
                    foreach( $arrDistProduk as $idDisc => $distProduk ){
                        if(!isset($freeProdukCanceledSum[$distProduk['free_produk_id']])){
                            $freeProdukCanceledSum[$distProduk['free_produk_id']] = array();
                        }
                        if(!isset($freeProdukCanceledSum[$distProduk['free_produk_id']]['qty'])){
                            $freeProdukCanceledSum[$distProduk['free_produk_id']]['qty'] = 0;
                        }
                        $freeProdukCanceledSum[$distProduk['free_produk_id']]['nama_produk'] = $distProduk['free_produk_nama'];
                        $freeProdukCanceledSum[$distProduk['free_produk_id']]['qty'] += $distProduk['free_qty'];
                    }
                }
            }

            $tr->setFilters(array());
            $tr->addFilter("transaksi_id in (" . implode(",", $idsNett) . ")");
            $trData = $tr->lookupTransaksiData()->result();
            $newTrData = array();
            $newTrDataCanceled = array();
            $idsNettPenjualan = array();
            $idsNettCanceled = array();
            if (sizeof($trData) > 0) {
                $newNr = array();
                $newNrCanceled = array();
                foreach ($trData as $iix => $trDataTmp) {
                    if($trDataTmp->sub_tail_code=="582"){
                        $buildDataTr = array(
                            "id" => $trDataTmp->id,
                            "transaksi_id" => $trDataTmp->transaksi_id,
                            "produk_jenis" => $trDataTmp->produk_jenis,
                            "produk_id" => $trDataTmp->produk_id,
                            "produk_nama" => $trDataTmp->produk_nama,
                            "valid_qty" => $trDataTmp->valid_qty,
                            "produk_ord_jml" => $trDataTmp->produk_ord_jml,
                            "produk_ord_hrg" => $trDataTmp->produk_ord_hrg,
                            "detail_tipe" => $trDataTmp->detail_tipe,
                            "sub_tail_code" => $trDataTmp->sub_tail_code,
                            "sub_tail_number" => $trDataTmp->sub_tail_number,
                            "next_substep_num" => $trDataTmp->next_substep_num,
                            "sub_step_avail" => $trDataTmp->sub_step_avail,
                            "sub_step_current" => $trDataTmp->sub_step_current,
                            "sub_step_number" => $trDataTmp->sub_step_number,
                        );
                        $trNr = (array)$buildDataTr + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                        $newNr[$iix] = (object)$trNr;
                        $idsNettPenjualan[$trDataTmp->transaksi_id] = $trDataTmp->transaksi_id;
                    }
                    else{
                        $buildDataTrCanceled = array(
                            "id" => $trDataTmp->id,
                            "transaksi_id" => $trDataTmp->transaksi_id,
                            "produk_jenis" => $trDataTmp->produk_jenis,
                            "produk_id" => $trDataTmp->produk_id,
                            "produk_nama" => $trDataTmp->produk_nama,
                            "valid_qty" => $trDataTmp->valid_qty,
                            "produk_ord_jml" => $trDataTmp->produk_ord_jml,
                            "produk_ord_hrg" => $trDataTmp->produk_ord_hrg,
                            "detail_tipe" => $trDataTmp->detail_tipe,
                            "sub_tail_code" => $trDataTmp->sub_tail_code,
                            "sub_tail_number" => $trDataTmp->sub_tail_number,
                            "next_substep_num" => $trDataTmp->next_substep_num,
                            "sub_step_avail" => $trDataTmp->sub_step_avail,
                            "sub_step_current" => $trDataTmp->sub_step_current,
                            "sub_step_number" => $trDataTmp->sub_step_number,
                        );
                        $trNrCanceled = (array)$buildDataTrCanceled + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                        $newNrCanceled[$iix] = (object)$trNrCanceled;
                        $idsNettCanceled[$trDataTmp->transaksi_id] = $trDataTmp->transaksi_id;
                    }
                }
                $newTrData["trData"] = $newNr;
                $newTrDataCanceled["trData"] = $newNrCanceled;
            }

            $doSendApi = array(
                "row" => count($tempTrans),
                "currentTr" => $currentTr,
                "targetJenis" => $targetJenis,
                "login" => $this->session->login,

                "newItems" => $newItems,
                "sumProduk" => $sumProduk,
                "itemsTrans" => $itemsTrans,

                "itemsTransCanceled" => $itemsTransCanceled,
                "sumProdukCanceled" => $sumProdukCanceled,
                "newItemsCanceled" => $newItemsCanceled,

                "freeProduk" => $freeProduk,
                "freeProdukSum" => $freeProdukSum,
                "freeProdukCanceledSum" => $freeProdukCanceledSum,

                "totalCash" => $totalCash,
                "totalDiskonProduk" => $totalDiskonProduk,
                "totalAddDiskon" => $totalAddDiskon,
                "totalDiskonCust" => $totalDiskonCust,

                "totalCashCanceled" => $totalCashCanceled,
                "totalDiskonProdukCanceled" => $totalDiskonProdukCanceled,
                "totalAddDiskonCanceled" => $totalAddDiskonCanceled,
                "totalDiskonCustCanceled" => $totalDiskonCustCanceled,

                "newTrData" => $newTrData,
                "newTrDataCanceled" => $newTrDataCanceled,

                "ids" => $ids,
                "idsCancel" => $idsCancel,
                "idsNett" => $idsNett,
                "idsNettPenjualan" => $idsNettPenjualan,
                "idsNettCanceled" => $idsNettCanceled,

                "debug" => 0, // <<==== MENGATUR DEBUG DI SERVER API TUJUAN
            );
            $dataEncoded = array(
                "data" => blobEncode($doSendApi)
            );

            $nomer_main = $this->session->login['id'] . "" . strtotime( date('Y-m-d') );

//            arrPrint($heTransaksiUi);

            $payment = array();
            $paymentNilai = array();
            foreach($itemsTrans as $ky => $row){
                $payment[$row['cash_account']] = $row['cash_account__label'];
                if(!isset($paymentNilai[$row['cash_account']])){
                    $paymentNilai[$row['cash_account']] = 0;
                }
                $paymentNilai[$row['cash_account']] += $row['tagihan'];
            }

            $paymentNilaiJson = json_encode($paymentNilai);

            echo "<div style='margin-bottom: 25px;padding: 6px;' class='panel panel-primary'>";
//            echo "$paymentNilaiJson"; //{"102":3202726,"106":2182768,"107":2571885}
            echo "<div style='' class='row'>";
            echo "<div style='' class='container-fluid'>";

            echo "<div class='col-lg-3 no-padding text-left'>
            <div style='font-size: 13px;' class='text-bold text-red'>Outlet</div>
            <div style='font-size: 18px;' class='text-bold text-muted text-capitalize'>".$this->session->login['cabang_nama']."</div>
                <input value='".$this->session->login['cabang_id']."' id='cabang_id' class='hidden'>
                <input value='".$this->session->login['toko_id']."' id='toko_id' class='hidden'>
            </div>";

            echo "<div class='col-lg-3 no-padding text-center'>
            <div style='font-size: 13px;' class='text-bold text-red'>Tgl Settlement</div>
            <div style='font-size: 18px;' class='text-bold text-muted text-capitalize'>".date("Y-m-d H:i")."</div>
            </div>";

            echo "<div class='col-lg-3 no-padding text-center'>
            <div style='font-size: 13px;' class='text-bold text-red'>Total Struk</div>
            <div style='font-size: 18px;' class='text-bold text-muted text-capitalize'>".count($itemsTrans)." Nota</div>
            </div>";

            echo "<div class='col-lg-3 no-padding text-center'>
            <div style='font-size: 13px;' class='text-bold text-red'>Kasir Nama</div>
            <div style='font-size: 18px;' class='text-bold text-muted text-capitalize'>".$this->session->login['nama']."</div>
                <input value='".$this->session->login['id']."' id='oleh_id' class='hidden'>
                <input value='".$this->session->login['nama']."' id='oleh_nama' class='hidden'>
            </div>";

            echo "</div>";
            echo "</div>";
            echo "</div>";

            if(!empty($payment)){
                foreach($payment as $payID => $payNama){
                    echo "<div style='margin-bottom: 3px;' class='row'>";
                    echo "<div class='col-lg-6'>";
                    echo "<span class='text-bold text-primary fa-2x'>$payNama</span>";
                    echo "</div>";
                    echo "<div class='col-lg-6'>";

//                    echo "<span><input value='".$paymentNilai[$payID]."' style='font-size: 23px;' class='form-control text-muted text-right text-bold form-payment text-capitalize' placeholder='nilai $payNama'></span>";
                    echo "<span><input style='font-size: 23px;' payid='$payID' paynama='$payNama' class='form-control text-muted text-right text-bold form-payment text-capitalize' placeholder='nilai $payNama'></span>";

                    echo "</div>";
                    echo "</div>";
                }

                if($totalCashCanceled*1>0){
                    //total canceled
                    echo "<div style='margin-top: 25px;' class='row'>";

                    echo "<div class='col-lg-6'>";
                    echo "<span class='text-bold text-red fa-2x pull-rightx'>TOTAL PEMBATALAN</span>";
                    echo "</div>";

                    echo "<div class='col-lg-6'>";
                    echo "<span><input style='font-size: 23px;' value='".number_format($totalCashCanceled)."' class='form-control text-red bg-gray text-right text-bold form-total-canceled' disabled></span>";
                    echo "</div>";

                    echo "</div>";
                    //total canceled

                    //total setoran
                    echo "<div style='margin-top: 3px;' class='row'>";
                }
                else{

                    //total setoran
                    echo "<div style='margin-top: 25px;' class='row'>";
                }

                echo "<div class='col-lg-6'>";
                echo "<span class='text-bold text-success fa-2x pull-rightx'>TOTAL DISETOR</span>";
                echo "</div>";

                echo "<div class='col-lg-6'>";
                echo "<span><input style='font-size: 23px;' class='form-control text-green bg-gray text-right text-bold form-total-payment' disabled></span>";
                echo "<input value='$totalCash' class='hidden form-total-cash'>";
                echo "</div>";

                echo "</div>";
                //total setoran


                //selisih setoran
                echo "<div style='margin-bottom: 10px;margin-top: 3px;' class='row hidden'>";

                echo "<div class='col-lg-6'>";
                echo "<span class='text-bold text-purple fa-2x pull-rightx'>SELISIH SETORAN</span>";
                echo "</div>";

                echo "<div class='col-lg-6'>";
                echo "<span><input style='font-size: 23px;' class='form-control text-purple bg-gray text-right text-bold form-total-selisih' disabled></span>";
                echo "</div>";

                echo "</div>";
                //selisih setoran
            }

            echo "<div style='margin-top: 25px;padding: 6px;display: none;' class='panel panel-success panel-terbilang'>";
            echo "<div style='' class='row'>";
            echo "<div style='' class='container-fluid'>";

            echo "<div class='col-lg-12 no-padding text-left'>
                    <div style='font-size: 14px;' class='text-bold text-info text-uppercase'>
                        <i class='fa fa-money'></i> TERBILANG <i class='fa fa-money'></i>
                    </div>
                    <div style='font-size: 18px;' class='text-bold text-green text-capitalize form-terbilang'></div>
                </div>";

            echo "</div>";
            echo "</div>";
            echo "</div>";

            echo "<div style='margin-top: 25px;padding: 6px;' class='panel panel-danger'>";
            echo "<div style='' class='row'>";
            echo "<div style='' class='container-fluid'>";

            echo "<div class='col-lg-12 no-padding text-center'>
                    <div style='font-size: 14px;' class='text-bold text-red text-uppercase blink'>
                        <i class='fa fa-warning'></i> NILAI SETORAN TIDAK DAPAT DIREVISI <i class='fa fa-warning'></i>
                    </div>
                    <div style='font-size: 12px;' class='text-bold text-muted text-capitalize'>Pastikan Nilai Setoran Anda sudah benar, karena data settlement tidak dapat di revisi setelah settlement berhasil.</div>
                </div>";

            echo "</div>";
            echo "</div>";
            echo "</div>";

            echo "<div style='margin-top: 25px;padding: 6px;' class='panel panel-info'>";
            echo "<div style='' class='row'>";
            echo "<div style='' class='container-fluid'>";

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

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

            echo "</select>
                    </div>
                </div>";

            echo "<div class='col-lg-7 no-padding text-left pull-right'>
                    <div style='font-size: 14px;' class='text-bold text-muted text-capitalize'>Masukan PIN/OTP PIC SETORAN</div>
                    <div class='input-group input-group-md'>
                        <form autocomplete='off'>
                            <input type='text' autocomplete='false' class='pin-otp-admin-nama' style='display: none;'>
                            <input type='password' autocomplete='off' class='form-control pin-otp-admin' placeholder='MASUKAN PIN / OTP'>
                        </form>
                        <span class='input-group-btn'>
                            <button type='button' disabled class='btn btn-info btn-flat btn-kirim'><i class='fa fa-send'></i> KIRIM SETTLEMENT</button>
                            <button type='button' data-dismiss='modal' class='btn btn-danger btn-flat btn-close-kirim'><i class='fa fa-times'></i></button>
                        </span>
                    </div>
                </div>";

            echo "</div>";
            echo "</div>";
            echo "</div>";

            echo "<div>";
            echo "<div style='margin-top:-20px;font-size: 14px;' class='text-bold'><r>*</r> Otorisator adalah person yang ditunjuk perusahaan untuk menerima settlement.</div>";
            echo "</div>";
            echo "<script>

                    var activeBtnNext = function(){

                        top.$('.btn-kirim').attr('disabled', false);
                        top.$('.btn-kirim').on('click', function(){
                            var pin_otp = $('.pin-otp-admin').val();
                            var total_setor = removeCommas( $('.form-total-payment').val());
                            var oto_settlement_id = $('select.select-otorisator option:checked').val();
                            var oto_settlement_nama = $('select.select-otorisator option:checked').text();

                            if( pin_otp != '' && total_setor*1>0 && oto_settlement_id*1>0 ){

                                var paymentTmp = $('.form-payment');
                                var arrPayment = []
                                jQuery.each(paymentTmp, function(i,p){
                                    var payID = $(p).attr('payid')
                                    var payNama = $(p).attr('paynama')
                                    var nilai = removeCommas($(p).val())
                                    arrPayment.push({payID:payID,payNama:payNama,nilai:nilai});
                                })

                                top.swal('Memproses Transaksi Settlement')
                                top.swal.showLoading();

                                top.$.ajax({
                                    url: '". base_url() .$this->modul . "/_shoppingCart/settlementOtorisator',
                                    method: 'post',
                                    data: {
                                        pin_diskon: pin_otp,
                                        nomer_main: $nomer_main,
                                        payment: arrPayment,
                                        terbilang: $('.form-terbilang').text(),
                                        payment_nilai: $paymentNilaiJson,
                                        action_target: '$action_target',
                                        oto_settlement_id: oto_settlement_id,
                                        oto_settlement_nama: oto_settlement_nama,
                                    },
                                    success: function(a){
                                        jsonData = JSON.parse(a);
                                        if(jsonData.status==1){
                                            top.swal('Proses Mengirim Settlement...<br>Mohon jangan menutup Browser Anda.')
                                            top.swal.showLoading();
                                            top.$('#result').load('$action_target', {payment:{
                                                payment: jsonData.dbData.payment,
                                                payment_nilai: jsonData.dbData.payment_nilai,
                                                payment_terbilang: jsonData.dbData.payment_terbilang,
                                                payment_nilai_seharusnya: jsonData.dbData.payment_nilai_seharusnya,
                                                payment_nilai_selisih: jsonData.dbData.payment_nilai_selisih,
                                                selisih_payment: jsonData.dbData.selisih_payment,
                                                payment_oto_id: jsonData.dbData.payment_oto_id,
                                                payment_oto_nama: jsonData.dbData.payment_oto_nama,
                                            }});
                                        }
                                        else{
                                            swal('Error', jsonData.reason, 'warning');
                                        }
                                    }
                                })
                            }
                            else{
                                if(pin_otp=='' && total_setor*1>0 && oto_settlement_id*1>0 ){
                                    swal('BELUM LENGKAP', 'PIN/OTP Harus Diisi Sebagai Kontrol Otorisasi.', 'warning');
                                }
                                else if(pin_otp!='' && total_setor*1==0 && oto_settlement_id*1>0 ){
                                    swal('BELUM LENGKAP', 'Nilai Settlement Harus Diisi.', 'warning');
                                }
                                else if(pin_otp!='' && total_setor*1>0 && oto_settlement_id*1==0 ){
                                    swal('BELUM LENGKAP', 'Otorisator Harus Dipilih.', 'warning');
                                }
                                else{
                                    swal('BELUM LENGKAP', 'Nilai Settlement, Otorisator dan PIN/OTP Harus Diisi.', 'warning');
                                }
                            }
                        })
                    }

//                    console.log('". base_url() . $this->modul ."/_shoppingCart/reqSettlementOTP/".$this->jenisTr."');
//                    console.log('nomer_main: $nomer_main');
//                    console.log('grand_total: $totalCash');
//                    console.log('this->jenisTr: ".$this->jenisTr."');

                    top.$.ajax({
                        url: '". base_url() . $this->modul ."/_shoppingCart/reqSettlementOTP/".$this->jenisTr."',
                        method: 'post',
                        data: {
                            'shoppingcart_order_id': '$nomer_main',
                            'grand_total': '$totalCash',
                            'main': '".blobEncode($doSendApi)."',
                        },
                        success: function(a){
                            jsonData = JSON.parse(a);
//                            console.log(jsonData);
                            if(jsonData.status){

                            }
                        }
                    })

            ";



            echo "$('.form-payment').on('keyup', function(){
                    $(this).val(addCommas(removeCommas($(this).val())))
                });\n";

            echo "$('.form-payment').on('click', function(){
                    $(this).select()
                });\n";

            echo "$('.form-payment').on('keyup', delay_v2(function(){
                    //hitung all form-payment
                    var formpayment = $('.form-payment')
                    var formtotalpayment = $('.form-total-payment')
                    var formtotalcanceled = $('.form-total-canceled')
                    var formtotalcash = $('.form-total-cash')
                    var formtotalselisih = $('.form-total-selisih')
                    var total = 0
                    var selisih = 0

                    jQuery.each(formpayment, function(a,b){
                        total += removeCommas( $(b).val() )*1 > 0 ? removeCommas( $(b).val() ) : 0
                    })

                    $(formtotalpayment).val( (total*1>0?addCommas(total):total*-1)  )

                    selisih = total - removeCommas($(formtotalcash).val());

                    if(selisih*1>0){
                        $(formtotalselisih).val('+ ' + addCommas(selisih)  ).removeClass('text-red').addClass('text-purple')
                    }
                    else{
                        $(formtotalselisih).val( addCommas(selisih)  ).removeClass('text-purple').addClass('text-red')
                    }

                    if(total*1>0){
                        $('.form-terbilang').html( pembilang(removeCommas(total),1) )
                        $('.panel-terbilang').fadeIn();
                    }
                    else{
                        $('.form-terbilang').html( '' )
                        $('.panel-terbilang').fadeOut();
                    }
                },100));\n";

            echo "$('.btn-kirim').on('click', function(){
                    var pinotp   = $('.pin-otp-admin').val()
                    var terbilang   = $('.form-terbilang').text()
                    var total_setor = removeCommas( $('.form-total-payment').val() )
                    var cabang_id   = $('#cabang_id').val()
                    var toko_id     = $('#toko_id').val()
                    var oleh_id     = $('#oleh_id').val()
                    var oleh_nama   = $('#oleh_nama').val()

//                    console.log('terbilang', terbilang);
//                    console.log('total_setor', total_setor);
//                    console.log('cabang_id', cabang_id);
//                    console.log('toko_id', toko_id);
//                    console.log('oleh_id', oleh_id);
//                    console.log('oleh_nama', oleh_nama);
//                    console.error('pinotp', pinotp);
                });\n";

            echo "$('.pin-otp-admin').on('click', function(){
                        $(this).select();
                    });\n";

            echo "$('.pin-otp-admin').on('keyup', delay_v2( function(){
                    var pinotp   = $(this).val()
                    if( pinotp.length >= 6 ){
//                        console.log( $(this).val() );
                        activeBtnNext()
                    }
                    else{
                        top.$('.btn-kirim').attr('disabled', true);
                        top.$('.btn-kirim').off('click');
                    }
                }, 500));\n";

            echo "$('.form-payment').trigger('keyup')\n";

            echo "</script>";

        }
    }

    public function doSettlementPos()
    {

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

        $selectedRegistries = array("main", "items");

        $currentTr = $this->uri->segment(4);
        $targetModul = $this->uri->segment(5);
        $targetJenis = $this->uri->segment(6);

        $payment_info = $_POST['payment'];

        $this->load->model("Mdls/MdlProduk");
        $pr = new MdlProduk();

        $this->load->model("Mdls/MdlHargaProduk");
        $prc = new MdlHargaProduk();

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

        $tr->addFilter("oleh_id='" . $this->session->login['id'] . "'");
        $tr->addFilter("settlement_id='1'");
        $tr->addFilter("link_id='0'");

        $this->db->where("jenis IN('582','982')");

        $date1 = isset($_GET['date1']) ? $_GET['date1'] : mati_disini("Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : mati_disini("Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.");

        $this->db->where("fulldate>='" . $date1 . "'");
        $this->db->where("fulldate<='" . $date2 . "'");

        $tempTrans = $tr->lookUpAll()->result();

        $ids = array();
        $idsCancel = array();
        $idsNett = array();
        $dataEncoded = array();
        if (sizeof($tempTrans) > 0) {
            foreach ($tempTrans as $temp) {
                $ids[$temp->id] = $temp->id;
                if($temp->trash_4==1){
                    $idsCancel[$temp->id] = $temp->id;
                }
                else{
                    $idsNett[$temp->id] = $temp->id;
                }
            }
            //panggil library curl untuk koneksi ke API server UTAMA
            $this->load->library("Curl");
            $curl = New Curl();
            //ambil register
            $tr->setFilters(array());
            $tempReg = $tr->lookupBaseDataRegistries($ids)->result();
            $newItems = array();
            $tempItems = array();
            $sumProduk = array();
            $sumProdukCanceled = array();
            $itemsTrans = array();
            $itemsTransCanceled = array();
            $totalCash = 0;
            $totalDiskonProduk = 0;
            $totalDiskonCust = 0;
            $totalHargaJual = 0;
            $totalDppPPn = 0;
            $totalPPn = 0;
            $totalNonDpp = 0;
            $totalCukai = 0;
            $totalCancel = 0;
            $totalCashCanceled = 0;
            $totalAddDiskonCanceled = 0;
            $totalDiskonProdukCanceled = 0;
            $totalDiskonCustCanceled = 0;
            $totalHargaJualCanceled = 0;
            $totalDppPPnCanceled = 0;
            $totalPPnCanceled = 0;
            $totalNonDppCanceled = 0;
            $totalCukaiCanceled = 0;
            $totalAddDiskon = 0;
            $freeProduk=array();
            $freeProdukCanceled=array();
            $preInjectTrData = array();
            $preInjectTrDataCanceled = array();
            $keyToPoint = array(
                "customerID",
                "customerName",
                "tokoID",
                "tokoNama",
                "cabangID",
                "cabangName",
                "jenisTr",
                "dtime",
                "paymentMethod",
            );
            $diskonProdukCanceled=0;
            if (sizeof($tempReg) > 0) {
                foreach ($tempReg as $regData) {
                    $trID = $regData->transaksi_id;
                    if(!isset($idsCancel[$trID])){
                        $main = blobdecode($regData->main);
                        $items = blobdecode($regData->items);
                        $preInjectTrData[$trID] = $main["nomer"];
                        $preItems = array();

                        $hargaJual=0;
                        $dppPPn=0;
                        $pPn=0;
                        $nonDpp=0;
                        $cukai=0;

                        $preItemsCanceled = array();

                        $hargaJualCanceled=0;
                        $dppPPnCanceled=0;
                        $pPnCanceled=0;
                        $nonDppCanceled=0;
                        $cukaiCanceled=0;

                        foreach ($items as $itemDataTmp) {
                            $diskonProduk=0;
                            if($itemDataTmp['jenisTr'] == "582"){
                                //bagian jual
                                if( isset($itemDataTmp['free_items']) ){
                                    $freeProduk[] = $itemDataTmp['free_items'];
                                }
                                $itemDataTmp['cukai_produk'] = 0;
                                $tmpSumItems = array(
                                    "id" => $itemDataTmp['id'],
                                    "produk_id" => $itemDataTmp['id'],
                                    "nama" => $itemDataTmp['nama'],
                                    "produk_nama" => $itemDataTmp['nama'],
                                    "barcode" => $itemDataTmp['barcode'],
                                    "kode" => $itemDataTmp['barcode'],
                                    "produk_kode" => $itemDataTmp['barcode'],
                                    "jml" => $itemDataTmp['jml'],
                                    "produk_qty" => $itemDataTmp['jml'],
                                    "qty_unit" => $itemDataTmp['qty_unit'],
                                    "harga_list" => $itemDataTmp['harga_list'],
                                    "harga_jual" => $itemDataTmp['harga_jual'],
                                    "discNilai" => $itemDataTmp['discNilai'],
                                    "discPersen" => $itemDataTmp['discPersen'],
                                    "harga" => $itemDataTmp['harga'],
                                    "subtotal" => $itemDataTmp['subtotal'],
                                    "ppn_produk" => isset($itemDataTmp['tipe_pajak']) ? $itemDataTmp['tipe_pajak'] : 1,
                                    "ppnFactor" => $itemDataTmp['ppnFactor'],
                                    "ppn" => $itemDataTmp['ppn'],
                                    "sub_ppn" => $itemDataTmp['sub_ppn'],
                                    "satuan" => $itemDataTmp['satuan'],
                                    "satuan_id" => $itemDataTmp['satuan_id'],
                                    "satuan_factor_qty" => $itemDataTmp['satuan_factor_qty'],
                                    "satuan_factor_id" => $itemDataTmp['satuan_factor_id'],
                                    "satuan_factor_nama" => $itemDataTmp['satuan_factor_nama'],
                                );

                                $sumProduk[$itemDataTmp["id"]][] = $tmpSumItems;
                                $preItems[$main["nomer"]][$itemDataTmp["id"]] = $tmpSumItems;

                                $diskonProduk   += $itemDataTmp['discNilai']*1>0 ? $itemDataTmp['discNilai']*$itemDataTmp['jml'] : 0;
                                $hargaJual      += $itemDataTmp['harga_jual']*1>0 ? $itemDataTmp['harga_jual']*$itemDataTmp['jml'] : 0;
                                $dppPPn         += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;
                                $pPn            += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['sub_ppn'] : 0;
                                $nonDpp         += $itemDataTmp['ppn_produk']*1==0 ? $itemDataTmp['subtotal'] : 0;
                                $cukai          += $itemDataTmp['cukai_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;

                            }
                            elseif($itemDataTmp['jenisTr']=="982"){

                                //bagian cancel
                                if( isset($itemDataTmp['free_items']) ){
                                    $freeProdukCanceled[] = $itemDataTmp['free_items'];
                                }

                                $itemDataTmp['cukai_produk'] = 0;
                                $tmpSumItems = array(
                                    "id" => $itemDataTmp['id'],
                                    "produk_id" => $itemDataTmp['id'],
                                    "nama" => $itemDataTmp['nama'],
                                    "produk_nama" => $itemDataTmp['nama'],
                                    "barcode" => isset($itemDataTmp['barcode']) ? $itemDataTmp['barcode'] : "" ,
                                    "kode" => isset($itemDataTmp['barcode']) ? $itemDataTmp['barcode'] : "" ,
                                    "produk_kode" => isset($itemDataTmp['barcode']) ? $itemDataTmp['barcode'] : "" ,
                                    "jml" => $itemDataTmp['jml'],
                                    "produk_qty" => $itemDataTmp['jml'],
                                    "harga_list" => $itemDataTmp['harga_list'],
                                    "harga_jual" => $itemDataTmp['harga_jual'],
                                    "discNilai" => $itemDataTmp['discNilai'],
                                    "discPersen" => $itemDataTmp['discPersen'],
                                    "harga" => $itemDataTmp['harga'],
                                    "subtotal" => $itemDataTmp['subtotal'],
                                    "ppn_produk" => isset($itemDataTmp['tipe_pajak']) ? $itemDataTmp['tipe_pajak'] : "",
                                    "ppnFactor" => $itemDataTmp['ppnFactor'],
                                    "ppn" => $itemDataTmp['ppn'],
                                    "sub_ppn" => $itemDataTmp['sub_ppn'],
                                    "satuan" => $itemDataTmp['satuan'],
                                    "satuan_id" => $itemDataTmp['satuan_id'],
                                );

                                $sumProdukCanceled[$itemDataTmp["id"]][] = $tmpSumItems;
                                $preItemsCanceled[$main["nomer"]][$itemDataTmp["id"]] = $tmpSumItems;

                                $diskonProdukCanceled   += $itemDataTmp['discNilai']*1>0 ? $itemDataTmp['discNilai']*$itemDataTmp['jml'] : 0;
                                $hargaJualCanceled      += $itemDataTmp['harga_jual']*1>0 ? $itemDataTmp['harga_jual']*$itemDataTmp['jml'] : 0;
                                $dppPPnCanceled         += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;
                                $pPnCanceled            += $itemDataTmp['ppn_produk']*1>0 ? $itemDataTmp['sub_ppn'] : 0;
                                $nonDppCanceled         += $itemDataTmp['ppn_produk']*1==0 ? $itemDataTmp['subtotal'] : 0;
                                $cukaiCanceled          += $itemDataTmp['cukai_produk']*1>0 ? $itemDataTmp['subtotal'] : 0;

                            }

                        }

                        if( $main["jenisTr"] == "582"){
                            /* -----------------------------------------------------------
                             * pengakimulasi point per customer dalam satu setlement
                             * -----------------------------------------------------------*/
                            if(!isset($newPoints[$main['customerID']]['qty_point'])){
                                $newPoints[$main['customerID']]['qty_point'] = 0;
                            }
                            $newPoints[$main['customerID']]['qty_point'] += $main['point_transaksi'];
                            $point_hpp = isset($main['point_hpp']) ? $main['point_hpp'] : 0;
                            if(!isset($newPoints[$main['customerID']]['hpp_point'])){
                                $newPoints[$main['customerID']]['hpp_point'] = 0;
                            }
                            $newPoints[$main['customerID']]['hpp_point'] += $point_hpp;
                            $newPoints[$main['customerID']]['hpp_point_satuan'] = $point_hpp;

                            $newPoints[$main['customerID']]['id'] = $main['customerID'];
                            $newPoints[$main['customerID']]['nama'] = $main['customerName'];
                            $newPoints[$main['customerID']]['transaksi_nilai'] = $main['grand_total'];
                            $newPoints[$main['customerID']]['dtime'] = $main['dtime'];
                            $newPoints[$main['customerID']]['nomer'] = isset($main['nomer']) ? $main['nomer'] : (isset($main['nomor']) ? $main['nomor'] : 0);

                            foreach ($keyToPoint as $point_key) {
                                $newPoints[$main['customerID']][$point_key] = $main[$point_key];
                            }
                            // -----------------------------------------------------------
                            $totalCash          += $main["grand_total"];
                            $totalDiskonCust    += isset($main["disc"]) ? $main["disc"] : 0;
                            $totalAddDiskon     += isset($main["add_disc"]) ? $main["add_disc"]*1 : 0;

                            $totalDiskonProduk  += $diskonProduk;
                            $totalHargaJual     += $hargaJual;
                            $totalDppPPn        += $dppPPn;
                            $totalPPn           += $pPn;
                            $totalNonDpp        += $nonDpp;
                            $totalCukai         += $cukai;

                            $buildMainTmp=array(
                                "olehID" => $main['olehID'],
                                "sellerID" => $main['olehID'],
                                "customerID" => $main['customerID'],
                                "customerName" => $main['customerName'],
                                "olehName" => $main['olehName'],
                                "sellerName" => $main['olehName'],
                                "placeID" => $main['placeID'],
                                "placeName" => $main['placeName'],
                                "cabangID" => $main['cabangID'],
                                "cabangName" => $main['cabangName'],
                                "gudangID" => $main['gudangID'],
                                "gudangName" => $main['gudangName'],
                                "divID" => $main['divID'],
                                "tokoID" => $main['tokoID'],
                                "tokoNama" => $main['tokoNama'],
                                "stepCode" => $main['stepCode'],
                                "dtime" => $main['dtime'],
                                "fulldate" => $main['fulldate'],
                                "harga" => $main['harga'],
                                "grand_total" => $main['grand_total'],
                                "bayar" => $main['bayar'],
                                "oto_diskon" => isset($main['oto_diskon']) ? $main['oto_diskon'] : "",
                                "cash_account" => $main['cash_account'],
                                "cash_account__label" => $main['cash_account__label'],

                                "diskon_produk" => $diskonProduk, //diskon dari potongan produk
                                "add_disc" => isset($main["add_disc"]) ? $main["add_disc"]*1 : 0,
                                "diskon_tambahan_nilai" => isset($main["diskon_tambahan_nilai"]) ? $main["diskon_tambahan_nilai"]*1 : 0, //diskon customer

                                "harga_jual" => $hargaJual,
                                "dpp_ppn" => $dppPPn,
                                "ppn" => $pPn,
                                "non_dpp" => $nonDpp,
                                "cukai" => $cukai,

                                "transaksi_id" => $main['transaksi_id'],
                                "paymentMethod_cash" => $main['paymentMethod_cash'],

                                "harga_nett2" => $main['harga'],
                                "tagihan" => $main['grand_total'],
                                "kembali" => $main['kembali'],
                                "machineID" => $main['machineID'],
                                "cpu_info" => $main['CPU_INFO'],
                                "com_info" => $main['COM_INFO'],
                            );

                            $itemsbase64 = base64_encode(json_encode($preItems[$main["nomer"]]));
                            $tempItems = $buildMainTmp + array("produk" => $itemsbase64, "nomor" => $main["nomer"]);
                            $newItems["items"][] = (object)$tempItems;
                            $itemsTrans[$trID] = $tempItems;

                            $newPoints_2["customerPoint"] = $newPoints;
                        }
                        else{

                            $totalCashCanceled          += $main["grand_total"];
                            $totalDiskonCustCanceled    += isset($main["disc"]) ? $main["disc"] : 0;
                            $totalAddDiskonCanceled     += isset($main["add_disc"]) ? $main["add_disc"]*1 : 0;

                            $totalDiskonProdukCanceled  += $diskonProdukCanceled;
                            $totalHargaJualCanceled     += $hargaJualCanceled;
                            $totalDppPPnCanceled        += $dppPPnCanceled;
                            $totalPPnCanceled           += $pPnCanceled;
                            $totalNonDppCanceled        += $nonDppCanceled;
                            $totalCukaiCanceled         += $cukaiCanceled;

                            $buildMainTmpCanceled=array(
                                "olehID" => $main['olehID'],
                                "sellerID" => $main['olehID'],
                                "olehName" => $main['olehName'],
                                "sellerName" => $main['olehName'],
                                "customerID" => $main['customerID'],
                                "customerName" => $main['customerName'],
                                "placeID" => $main['placeID'],
                                "placeName" => $main['placeName'],
                                "cabangID" => $main['cabangID'],
                                "cabangName" => $main['cabangName'],
                                "gudangID" => $main['gudangID'],
                                "gudangName" => $main['gudangName'],
                                "divID" => $main['divID'],
                                "tokoID" => $main['tokoID'],
                                "tokoNama" => $main['tokoNama'],
                                "stepCode" => $main['stepCode'],
                                "dtime" => $main['dtime'],
                                "fulldate" => $main['fulldate'],
                                "harga" => $main['harga'],
                                "grand_total" => $main['grand_total'],
                                "bayar" => $main['bayar'],
                                "oto_diskon" => isset($main['oto_diskon']) ? $main['oto_diskon'] : "",
                                "cash_account" => $main['cash_account'],
                                "cash_account__label" => $main['cash_account__label'],

                                "diskon_produk" => $diskonProduk, //diskon dari potongan produk
                                "add_disc" => isset($main["add_disc"]) ? $main["add_disc"]*1 : 0,
                                "diskon_tambahan_nilai" => isset($main["diskon_tambahan_nilai"]) ? $main["diskon_tambahan_nilai"]*1 : 0, //diskon customer

                                "harga_jual" => $hargaJual,
                                "dpp_ppn" => $dppPPn,
                                "ppn" => $pPn,
                                "non_dpp" => $nonDpp,
                                "cukai" => $cukai,

                                "transaksi_id" => $main['transaksi_id'],
                                "paymentMethod_cash" => $main['paymentMethod_cash'],

                                "harga_nett2" => $main['harga'],
                                "tagihan" => $main['grand_total'],
                                "kembali" => $main['kembali'],

                                "machineID" => $main['machineID'],
                                "cpu_info" => $main['CPU_INFO'],
                                "com_info" => $main['COM_INFO'],
                            );

                            $itemsbase64Canceled = base64_encode(json_encode($preItemsCanceled[$main["nomer"]]));
                            $tempItemsCanceled = $buildMainTmpCanceled + array("produk" => $itemsbase64Canceled, "nomor" => $main["nomer"]);
                            $newItemsCanceled["items"][] = (object)$tempItemsCanceled;
                            $itemsTransCanceled[$trID] = $tempItemsCanceled;

                        }
                    }
                    else{
                        $main = blobdecode($regData->main);
                        $totalCancel += isset($idsCancel[$trID]) ? $main["grand_total"] : 0;
                    }
                }
            }
            else {
                matiHEre("no data to execute. silahkan relogin untuk membersihkan sesi");
            }
            $freeProdukSum=array();
            if(!empty($freeProduk)){
                foreach( $freeProduk as $ky => $arrDistProduk ){
                    foreach( $arrDistProduk as $idDisc => $distProduk ){
                        if(!isset($freeProdukSum[$distProduk['free_produk_id']])){
                            $freeProdukSum[$distProduk['free_produk_id']] = array();
                        }
                        if(!isset($freeProdukSum[$distProduk['free_produk_id']]['qty'])){
                            $freeProdukSum[$distProduk['free_produk_id']]['qty'] = 0;
                        }
                        $freeProdukSum[$distProduk['free_produk_id']]['nama_produk'] = $distProduk['free_produk_nama'];
                        $freeProdukSum[$distProduk['free_produk_id']]['qty'] += $distProduk['free_qty'];
                    }
                }
            }
            $freeProdukCanceledSum=array();
            if(!empty($freeProdukCanceled)){
                foreach( $freeProdukCanceled as $ky => $arrDistProduk ){
                    foreach( $arrDistProduk as $idDisc => $distProduk ){
                        if(!isset($freeProdukCanceledSum[$distProduk['free_produk_id']])){
                            $freeProdukCanceledSum[$distProduk['free_produk_id']] = array();
                        }
                        if(!isset($freeProdukCanceledSum[$distProduk['free_produk_id']]['qty'])){
                            $freeProdukCanceledSum[$distProduk['free_produk_id']]['qty'] = 0;
                        }
                        $freeProdukCanceledSum[$distProduk['free_produk_id']]['nama_produk'] = $distProduk['free_produk_nama'];
                        $freeProdukCanceledSum[$distProduk['free_produk_id']]['qty'] += $distProduk['free_qty'];
                    }
                }
            }
            $tr->setFilters(array());
            $tr->addFilter("transaksi_id in (" . implode(",", $idsNett) . ")");
            $trData = $tr->lookupTransaksiData()->result();
            $newTrData = array();
            $newTrDataCanceled = array();
            $idsNettPenjualan = array();
            $idsNettCanceled = array();
            if (sizeof($trData) > 0) {
                $newNr = array();
                $newNrCanceled = array();
                foreach ($trData as $iix => $trDataTmp) {
                    if($trDataTmp->sub_tail_code=="582"){
                        $buildDataTr = array(
                            "id" => $trDataTmp->id,
                            "transaksi_id" => $trDataTmp->transaksi_id,
                            "produk_jenis" => $trDataTmp->produk_jenis,
                            "produk_id" => $trDataTmp->produk_id,
                            "produk_nama" => $trDataTmp->produk_nama,
                            "valid_qty" => $trDataTmp->valid_qty,
                            "produk_ord_jml" => $trDataTmp->produk_ord_jml,
                            "produk_ord_hrg" => $trDataTmp->produk_ord_hrg,
                            "detail_tipe" => $trDataTmp->detail_tipe,
                            "sub_tail_code" => $trDataTmp->sub_tail_code,
                            "sub_tail_number" => $trDataTmp->sub_tail_number,
                            "next_substep_num" => $trDataTmp->next_substep_num,
                            "sub_step_avail" => $trDataTmp->sub_step_avail,
                            "sub_step_current" => $trDataTmp->sub_step_current,
                            "sub_step_number" => $trDataTmp->sub_step_number,
                        );
                        $trNr = (array)$buildDataTr + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                        $newNr[$iix] = (object)$trNr;
                        $idsNettPenjualan[$trDataTmp->transaksi_id] = $trDataTmp->transaksi_id;
                    }
                    else{
                        $buildDataTrCanceled = array(
                            "id" => $trDataTmp->id,
                            "transaksi_id" => $trDataTmp->transaksi_id,
                            "produk_jenis" => $trDataTmp->produk_jenis,
                            "produk_id" => $trDataTmp->produk_id,
                            "produk_nama" => $trDataTmp->produk_nama,
                            "valid_qty" => $trDataTmp->valid_qty,
                            "produk_ord_jml" => $trDataTmp->produk_ord_jml,
                            "produk_ord_hrg" => $trDataTmp->produk_ord_hrg,
                            "detail_tipe" => $trDataTmp->detail_tipe,
                            "sub_tail_code" => $trDataTmp->sub_tail_code,
                            "sub_tail_number" => $trDataTmp->sub_tail_number,
                            "next_substep_num" => $trDataTmp->next_substep_num,
                            "sub_step_avail" => $trDataTmp->sub_step_avail,
                            "sub_step_current" => $trDataTmp->sub_step_current,
                            "sub_step_number" => $trDataTmp->sub_step_number,
                        );
                        $trNrCanceled = (array)$buildDataTrCanceled + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                        $newNrCanceled[$iix] = (object)$trNrCanceled;
                        $idsNettCanceled[$trDataTmp->transaksi_id] = $trDataTmp->transaksi_id;
                    }
                }
                $newTrData["trData"] = $newNr;
                $newTrDataCanceled["trData"] = $newNrCanceled;
            }
            $totalPoint = 0;
            if(!empty($newPoints_2)){
                foreach($newPoints_2 as $custP => $datas){
                    foreach($datas as $idp => $dat){
                        $totalPoint+= $dat['qty_point'];
                    }
                }
            }
            $doSendApi = array(
                "row" => count($tempTrans),
                "currentTr" => $currentTr,
                "targetJenis" => $targetJenis,
                "login" => $this->session->login,
                "newItems" => $newItems,
                "sumProduk" => $sumProduk,
                "itemsTrans" => $itemsTrans,
                "itemsTransCanceled" => $itemsTransCanceled,
                "sumProdukCanceled" => $sumProdukCanceled,
                "newItemsCanceled" => $newItemsCanceled,
                "freeProduk" => $freeProduk,
                "freeProdukSum" => $freeProdukSum,
                "freeProdukCanceledSum" => $freeProdukCanceledSum,
                "totalCash" => $totalCash,
                "totalDiskonProduk" => $totalDiskonProduk,
                "totalAddDiskon" => $totalAddDiskon,
                "totalDiskonCust" => $totalDiskonCust,
                "totalCashCanceled" => $totalCashCanceled,
                "totalDiskonProdukCanceled" => $totalDiskonProdukCanceled,
                "totalAddDiskonCanceled" => $totalAddDiskonCanceled,
                "totalDiskonCustCanceled" => $totalDiskonCustCanceled,
                "newTrData" => $newTrData,
                "newTrDataCanceled" => $newTrDataCanceled,
                "ids" => $ids,
                "idsCancel" => $idsCancel,
                "idsNett" => $idsNett,
                "idsNettPenjualan" => $idsNettPenjualan,
                "idsNettCanceled" => $idsNettCanceled,
                "payment" => $payment_info,
                "newPointCustomer" => $newPoints_2,
                "totalPoint" => $totalPoint,
                "debug" => 0, // <<==== MENGATUR DEBUG DI SERVER API TUJUAN
            );
            $dataEncoded = array(
                "data" => blobEncode($doSendApi)
            );
            }

        $this->db->trans_begin();
        $ids = array();
        $idsReturn = array();

        if (sizeof($tempTrans) > 0) {
            foreach ($tempTrans as $temp) {
                $ids[$temp->id] = $temp->id;
            }

            //region build items dari main ke gerbang items
            $tr->setFilters(array());
            $tempReg = $tr->lookupBaseDataRegistries($ids)->result();

            $newItems = array();
            $tempItems = array();
            $sumProduk = array();
            $itemsTrans = array();
            $preInjectTrData = array();
            if (sizeof($tempReg) > 0) {
                $newPoints = array();
                foreach ($tempReg as $regData) {
                    $trID = $regData->transaksi_id;
                    $main = blobdecode($regData->main);
                    $items = blobdecode($regData->items);
                    $preInjectTrData[$trID] = $main["nomer"];
                    $itemsbase64 = base64_encode(json_encode($items));
                    $tempItems = $main + array("produk" => $itemsbase64, "nomor" => $main["nomer"]);
                    $newItems["items"][] = (object)$tempItems;
                    /* -----------------------------------------------------------
                     * pengakimulasi point per customer dalam satu setlement
                     * -----------------------------------------------------------*/
                    if(!isset($newPoints[$tempItems['customerID']]['qty_point'])){
                        $newPoints[$tempItems['customerID']]['qty_point'] = 0;
                    }
                    $newPoints[$tempItems['customerID']]['qty_point'] += $tempItems['point_transaksi'];
                    $point_hpp = isset($main['point_hpp']) ? $main['point_hpp'] : 0;
                    if(!isset($newPoints[$tempItems['customerID']]['hpp_point'])){
                        $newPoints[$tempItems['customerID']]['hpp_point'] = 0;
                    }
                    $newPoints[$tempItems['customerID']]['hpp_point'] += $point_hpp;
                    $newPoints[$tempItems['customerID']]['hpp_point_satuan'] = $point_hpp;
                    foreach ($keyToPoint as $point_key) {
                        $newPoints[$main['customerID']][$point_key] = $main[$point_key];
                    }
                    // -----------------------------------------------------------
                    $itemsTrans[$trID] = $tempItems;
                    foreach ($items as $itemDataTmp) {
                        $sumProduk[$itemDataTmp["id"]][] = $itemDataTmp;
                    }
                }
            }
            else {
                matiHEre("no data to execute. silahkan relogin untuk membersihkan sesi");
            }
            //endregion

            $pointCustomer['point_customer'] = $newPoints;

            //region build trData
            $tr->setFilters(array());
            $tr->addFilter("transaksi_id in (" . implode(",", $ids) . ")");
            $trData = $tr->lookupTransaksiData()->result();
            $newTrData = array();
            if (sizeof($trData) > 0) {
                $newNr = array();
                foreach ($trData as $iix => $trDataTmp) {
                    $trNr = (array)$trDataTmp + array("nomor" => $preInjectTrData[$trDataTmp->transaksi_id]);
                    $newNr[$iix] = (object)$trNr;
                }
                $newTrData["trData"] = $newNr;
            }
            //endregion

            $fildsSumItems = array(
                "id" => "id",
                "nama" => "nama",
                "no_part" => "no_part",
                "satuan" => "satuan",
                "harga" => "harga",
                "subtotal" => "subtotal",
                "jml" => "jml",
                "qty" => "qty",
                "produk_qty" => "produk_qty",
                "placeID" => "placeID",
                "cabangID" => "cabangID",
            );
            $sumProdukNew = array();
            if (sizeof($sumProduk) > 0) {
                foreach ($sumProduk as $ii => $data) {
                    $sumSubtotal = 0;
                    $sumJml = 0;
                    foreach ($data as $itemsdetail) {
                        $sumProdukNew["sumProduk"][$ii] = $itemsdetail;
                        $sumSubtotal += $itemsdetail["subtotal"];
                        $sumJml += $itemsdetail["jml"];
                    }
                    $sumProdukNew["sumProduk"][$ii]["subtotal"] = $sumSubtotal;
                    $sumProdukNew["sumProduk"][$ii]["jml"] = $sumJml;
                    $sumProdukNew["sumProduk"][$ii]["qty"] = $sumJml;
                }
            }
            $data = $newItems + $newTrData + $sumProdukNew + $pointCustomer;
            $toInsertBlob = blobEncode($data);

            //region array builder transaction
            $itemsTmp = array(
                "handler" => "Selectors/_processSelectBiaya",
                "id" => "transaksi_id",
                "harga" => "harga",
                "subtotal" => "subtotal",
                "nama" => "nama",
                "label" => "",
                "reference" => "",
                "qty" => "1",
                "name" => "name",
                "sub_harga" => "sub_harga",
                "sub_subtotal" => "sub_total",
                "olehID" => "olehID",
                "olehName" => "olehName",
                "placeID" => "placeID",
                "placeName" => "cabang_nama",
                "cabangID" => "cabangID",
                "cabangName" => "cabangName",
                "gudangID" => "gudangID",
                "gudangName" => "gudangName",
                "gudang2ID" => "-1",
                "gudang2Name" => "default center warehouse",
                "jenisTr" => $targetJenis,
                "next_substep_code" => $targetJenis,
                "next_subgroup_code" => "o_finance",
                "sub_step_number" => "1",
                "sub_step_current" => "1",
                "nilai_bayar" => "",
                "new_sisa" => "0",
                "sub_new_sisa" => "0",
                "note" => "",
                "pihakID" => "-1",
                "pihakName" => "PUSAT",
            );
            $items2 = array();
            $items2_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $tableIn_masterTmp = array(
                "trash" => "0",
                "jenis_master" => $targetJenis,
                "jenis_top" => $targetJenis,
                "jenis" => $targetJenis,
                "jenis_label" => "request depresiasi",
                "div_id" => "2",
                "div_nama" => "default",
                "oleh_id" => "olehID",
                "oleh_nama" => "olehName",
                "cabang_id" => "cabangID",
                "cabang_nama" => "cabangName",
                "transaksi_nilai" => "sub_total",
                "transaksi_jenis" => $targetJenis,
                "gudang_id" => "gudangID",
                "gudang_nama" => "gudangName",
                "gudang2_id" => "-1",
                "gudang2_nama" => "default center warehouse",
                "keterangan" => "",
                "cabang2_id" => "-1",
                "cabang2_nama" => "PUSAT",
                "pihakMainName" => "",
                "pihakMainID" => "",
            );
            $tableIn_detailTmp = array(
                "produk_id" => "transaksi_id",
                "produk_kode" => "",
                "produk_label" => "",
                "produk_nama" => "nomer",
                "produk_ord_jml" => "1",
                "produk_ord_hrg" => "nilai_cash",
                "hpp" => "nilai_cash",
                "satuan" => "",
                "note" => "",
                "reference" => "",
                "trash" => "0",
                "produk_jenis" => "invoice",
                "valid_qty" => "1",
            );
            $tableIn_detail2_sum = array();
            $tableIn_detail_rsltItems = array();
            $tableIn_detail_rsltItems2 = array();
            $tableIn_master_valuesTmp = array(
                "gudang2" => "-1",
                "harga" => "harga",
                "divID" => "2",
                "subtotal" => "subtotal",
                "reference" => "0",
                "nilai_bayar" => "0",
                "note" => "0",
            );
            $tableIn_detail_valuesTmp = array(
                "jml" => "1",
                "harga" => "nilai_cash",
                "subtotal" => "nilai_cash",
                "qty" => "1",
                "sub_harga" => "nilai_cash",
                "sub_subtotal" => "nilai_cash",
                "sub_new_sisa" => "0",
            );
            $tableIn_detail_values_rsltItemsTmp = array();
            $tableIn_detail_values_rsltItems2Tmp = array();
            $tableIn_detail_values2_sumTmp = array();
            $tableIn_detail2 = array();
            $main_add_values = array();
            $main_add_fields = array();
            $main_elements = array(
                "gudang2" => Array
                (
                    "elementType" => "dataModel",
                    "name" => "gudang2",
                    "key" => "-1",
                    "labelSrc" => "name",
                    "label" => "gudang dc",
                    "labelValue" => "default center warehouse",
                    "mdl_name" => "MdlGudangDefault_center",
                    "contents" => "YToxOntzOjQ6Im5hbWEiO3M6MDoiIjt9",
                    "contents_intext" => print_r(array("nama" => ""),true),
                ),
            );
            $main_inputs = array();
            $main_inputs_orig = array();
            $receiptDetailFieldsTmp = array(
                "produk_nama" => "nomer",
            );
            $receiptSumFieldsTmp = array(
                "harga" => "total amount",
            );
            $receiptDetailFields2 = array();
            $receiptSumFields2 = array();
            $tableIn_detail_values2_sum = array();
            $items3 = array();
            $items3_sum = array();
            $tableIn_detail_values_rsltItems = array();
            $tableIn_detail_values_rsltItems2 = array();
            //endregion
            //region builder mian
            $main = array(
                "olehID" => $this->session->login["id"],
                "olehName" => $this->session->login["nama"],
                "placeID" => $this->session->login["cabang_id"],
                "placeName" => $this->session->login["cabang_nama"],
                "cabangID" => $this->session->login["cabang_id"],
                "cabangName" => $this->session->login["cabang_nama"],
                "gudangID" => $this->session->login["gudang_id"],
                "gudangName" => $this->session->login["gudang_nama"],
                "tokoID" => $this->session->login["toko_id"],
                "jenisTr" => $targetJenis,
                "jenisTrMaster" => $targetJenis,
                "jenisTrTop" => $targetJenis,
                "jenisTrName" => "settlement",
                "stepNumber" => "1",
                "stepCode" => $targetJenis,
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "harga" => $totalCash,
                "divID" => "2",
                "divName" => $this->session->login["div_nama"],
                "subtotal" => $totalCash,
                // "harga" => $totalCash,
                "nilai_cash" => $totalCash,
                "reference" => "0",
                "jenis" => $targetJenis,
                "transaksi_jenis" => $targetJenis,
                "next_step_code" => $targetJenis,
                "next_group_code" => "c_finance",
                "step_number" => "1",
                "step_current" => "1",
                "longitude" => "",
                "lattitude" => "",
                "accuracy" => "",
                "nilai_bayar" => "0",
                "new_sisa" => "0",
                "note" => "0",
                "description" => "",
                "pihakDisc" => "",
                "pihakName" => $this->session->login["nama"],
                "pihakID" => $this->session->login["id"],
                "machineID" => $this->session->login["machineID"],
            );
            //endregion
            //region builder items
            // arrPrint($itemsTrans);
            $items = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($itemsTmp as $col => $selectedRow) {
                    $items[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion builder items
            //region builder tabel in master
            $tableIn_master = array(
                "trash" => "0",
                "jenis_master" => $targetJenis,
                "jenis_top" => $targetJenis,
                "jenis" => $targetJenis,
                "jenis_label" => "settlement",
                "div_id" => "2",
                "div_nama" => "default",
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "oleh_id" => $this->session->login["id"],
                "oleh_nama" => $this->session->login["nama"],
                "cabang_id" => $this->session->login["cabang_id"],
                "cabang_nama" => $this->session->login["cabang_nama"],
                "transaksi_nilai" => $totalCash,
                "transaksi_jenis" => $targetJenis,
                "gudang_id" => $this->session->login["gudang_id"],
                "gudang_nama" => $this->session->login['gudang_nama'],
                "pihakMainName" => $this->session->login["id"],
                "pihakMainID" => $this->session->login["nama"],
            );

            //endregion
            //region builder table in detil
            $tableIn_detail = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($tableIn_detailTmp as $col => $selectedRow) {
                    $tableIn_detail[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            // arrPrintPink($tableIn_detail);
            //endregion builder table in detil
            //region table in master values
            $tableIn_master_values = array(
                "gudang" => $this->session->login["gudang_id"],
                "harga" => $totalCash,
                "divID" => "2",
                "subtotal" => $totalCash,
                "reference" => "0",
                "nilai_bayar" => "0",
                "note" => "0",
            );
            //endregion table in master values
            //region build table in detil values
            $tableIn_detail_values = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($tableIn_detail_valuesTmp as $col => $selectedRow) {
                    $tableIn_detail_values[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }

//            arrPrintWebs($tableIn_detail_values);
            //endregion build table in detil values
            //region build table receipDetailFields
            $receiptDetailFields = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($receiptDetailFieldsTmp as $col => $selectedRow) {
                    $receiptDetailFields[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion
            //region receiptSumFields
            $receiptSumFields = array();
            foreach ($itemsTrans as $itsID => $itsData) {
                foreach ($receiptSumFieldsTmp as $col => $selectedRow) {
                    $receiptSumFields[$itsID][$col] = isset($itsData[$selectedRow]) ? $itsData[$selectedRow] : $selectedRow;
                }
            }
            //endregion

            $configUi       = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiUi');
            $configLayout   = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiLayout');
            $configCore = $this->load->config->item("heTransaksi_core");
            $configValues   = loadConfigModulJenis_he_misc($targetJenis, 'coTransaksiValues');
            $modul = $this->load->config->item("heTransaksi_ui")[$targetJenis]["modul"];
            $transaksiMode = $configUi["transaksiMode"];
            $core     =  isset($configCore[$modul][$transaksiMode]) ? $configCore[$modul][$transaksiMode]:array();
            $runCoreAkunting = isset($configUi["steps"]["1"]["runCoreAccounting"]) ? $configUi["steps"]["1"]["runCoreAccounting"]:false;

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

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

                //region penomoran receipt NEW
                //region penomoran receipt
                $this->load->model("CustomCounter");
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $configCustomParams = $configValues['counters'];

                if (sizeof($configCustomParams) > 0) {
                    $cContent = array();
                    foreach ($configCustomParams as $i => $cRawParams) {
                        $cParams = explode("|", $cRawParams);
                        $cValues = array();
                        foreach ($cParams as $param) {
                            $cValues[$i][$param] = $main[$param];
                        }
                        $cRawValues = implode("|", $cValues[$i]);
                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i], my_toko_id());
                        $cContent[$cRawParams][$cRawValues] = $paramSpec["value"];
                        switch ($paramSpec["id"]) {
                            case 0: //===counter type is new
                                $addData = array(
                                    "toko_id" => my_toko_id(),
                                    "toko_nama" => my_toko_nama(),
                                );
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                break;
                            default: //===counter to be updated
                                $cn->updateCount($paramSpec["id"], $paramSpec["value"]);
                                break;
                        }
                    }
                }

                $appliedCounters = base64_encode(serialize($cContent));
                $appliedCounters_inText = print_r($cContent, true);

                //region NUMBERING

                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");

                $counterForNumber = array($configValues['formatNota']);
                foreach ($counterForNumber as $i => $c0RawParams) {
                    $c0Params = explode(",", $c0RawParams);
                    foreach($c0Params as $k=>$cRawParams){
                        $dParams = explode("|", $cRawParams);

                        if(count($dParams)>1){
                            if (!in_array($cRawParams, $configValues['counters'])) {
                                die(__LINE__ . "( $cRawParams ) Used number should be registered in counters config as well");
                            }
                        }
                    }
                }

                $tmpNomorNota="";
                $arrNomorNota=array();
                foreach ($counterForNumber as $i => $c0RawParams) {
                    $c0Params = explode(",", $c0RawParams);
                    $c0Values = array();
                    foreach($c0Params as $k=>$cRawParams){
                        $arrRawParams = explode("|", $cRawParams);
                        if(sizeof($arrRawParams)>1){
                            $cRawParamsValues = array();
                            foreach($arrRawParams as $key){
                                $cRawParamsValues[$key] = $main[$key];
                            }
                            $cRawParamsValuesK = implode("|", array_keys($cRawParamsValues));
                            $cRawParamsValuesV = implode("|", $cRawParamsValues);
                            $arrNomorNota[] = digit_4($cContent[$cRawParamsValuesK][$cRawParamsValuesV]);
                        }
                        else{
                            $cRawParamsValuesK = $arrRawParams[0];
                            $cRawParamsValuesV = $main[$arrRawParams[0]];
                            if($arrRawParams[0]=="fulldate"){
                                $arrNomorNota[] = $arrRawParams[0]."|".date("mY", strtotime($cRawParamsValuesV));
                            }
                            elseif($arrRawParams[0]=="stepCode"){
                                $arrNomorNota[] = $cRawParamsValuesV;
                            }
                            elseif($arrRawParams[0]=="placeID"){
                                $arrNomorNota[] = digit_4($cRawParamsValuesV);
                            }
                            elseif($arrRawParams[0]=="customerID"){
                                $arrNomorNota[] = digit_4($cRawParamsValuesV);
                            }
                            elseif($arrRawParams[0]=="machineID"){
                                if($cRawParamsValuesV!=""){
                                    $arrNomorNota[] = substr($cRawParamsValuesV,-4);
                                }
                                else{
                                    $arrNomorNota[] = "NMID";
                                }
                            }
                            elseif($arrRawParams[0]=="olehID"){
                                $arrNomorNota[] = digit_4($cRawParamsValuesV);
                            }
                            else{
                                $arrNomorNota[] = digit_4($cContent[$cRawParamsValuesK][$cRawParamsValuesV]);
                            }
                        }
                    }
                }

                $stepNumber = 1;
                $tmpNomorNota = implode("-", $arrNomorNota);

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

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

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

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

                    $tr = new MdlTransaksi();
                    $tr->addFilter("transaksi.cabang_id='" . $tableIn_master['cabang_id'] . "'");
                    $insertID = $tr->writeMainEntries($tableIn_master);

                    showLast_query("hijau");

                    $mongoList['main'][] = $insertID;
                    $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $tableIn_master);

                    $mongoList['main'][] = $epID;

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

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

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

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

                    $addValues = array(
                        //===references
                        "id_master" => $insertID,
                        "id_top" => $insertID,
                        "ids_prev" => "",
                        "ids_prev_intext" => "",
                        "nomer_top" => $main['nomer'],
                        "nomers_prev" => "",
                        "nomers_prev_intext" => "",
                        "jenises_prev" => "",
                        "jenises_prev_intext" => "",
                        "ids_his" => $idHis_blob,
                        "ids_his_intext" => $idHis_intext,
                    );
                    foreach ($addValues as $key => $val) {
                        $tableIn_master[$key] = $val;
                    }

                }
                if (sizeof($tableIn_master_values) > 0) {
                    if (isset($configValues['tableIn']['mainValues'])) {
                        $inserMainValues = array();
                        foreach ($configValues['tableIn']['mainValues'] as $key => $src) {
                            if (isset($tableIn_master_values[$key])) {
                                $dd = $tr->writeMainValues($insertID, array(
                                    "key" => $key,
                                    "value" => $tableIn_master_values[$key],
                                ));
                                $inserMainValues[] = $dd;
                                $mongoList['mainValues'][] = $dd;
                            }

                        }
                        if (sizeof($inserMainValues) > 0) {
                            $arrBlob = blobEncode($inserMainValues);
                            $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                        }
                    }
                }
                if (sizeof($main_add_values) > 0) {
                    $inserMainValues = array();
                    foreach ($main_add_values as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoList['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }

                    //                            cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                }
                if (sizeof($main_inputs) > 0) {
                    foreach ($main_inputs as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoList['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }
                    //                            cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                }
                if (sizeof($main_add_fields) > 0) {
                    foreach ($main_add_fields as $key => $val) {
                        $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                    }
                    //                            cekHitam("LINE: " . __LINE__ . " || " . $this->db->last_query());
                }
                if (sizeof($main_elements) > 0) {
                    foreach ($main_elements as $elName => $aSpec) {
                        $tr->writeMainElements($insertID, array(
                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                            "name" => $aSpec['name'],
                            "label" => isset($aSpec['label']) ? $aSpec['label'] : "",
                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",
                        ));

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

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

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

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

                //region COMPONENT-----
                if ($runCoreAkunting == true) {

                    //region processing main components, if in single step
                    $componentGate['master'] = array();
                    $componentConfig['master'] = array();
                    //==filter nilai, jika NOL tidak dikirim, sesuai config==
                    $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
                    if (isset($configValues[$targetJenis]['relativeComponets']) && $configValues[$this->jenisTr]['relativeComponets'] == true) {
                        $iterator = isset($main['revert']['jurnal']['master']) ? $main['revert']['jurnal']['master'] : array();

                    }
                    else {
                        if (isset($main['componentsBuilder'][1]['master'])) {
                            $iterator =$main['componentsBuilder'][1]['master'];

                        }
                        else {
                            // matiHEre($runCoreAkunting);
                            $iterator = isset($core['components']['master']) ? $core['components']['master'] : array();
                        }
                    }

                    // arrprintWebs($main);
                    // matiHEre(__LINE__);
                    if (sizeof($iterator) > 0) {
                        $componentConfig['master'] = $iterator;
                        $cCtr = 0;
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $cCtr++;
                            $comName = $tComSpec['comName'];
                            if (substr($comName, 0, 1) == "{") {
                                $comName = trim($comName, "{");
                                $comName = trim($comName, "}");
                                $comName = str_replace($comName, $main[$comName], $comName);
                            }
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            cekHere("component # $cCtr: $comName<br>") ;

                            // $dSpec = $this->cCodeData[$cCode][$srcGateName];
                            $tmpOutParams = array();
                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {
                                    if (substr($key, 0, 1) == "{") {
                                        $key = trim($key, "{");
                                        $key = trim($key, "}");
                                        $key = str_replace($key, $main[$key], $key);
                                    }
                                    $realValue = makeValue($value, $main, $main, 0);
                                    $tmpOutParams['loop'][$key] = $realValue;
                                }
                            }
                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {
                                    $realValue = makeValue($value, $main, $main, 0);
                                    $tmpOutParams['static'][$key] = $realValue;
                                }
                                if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                    $tmpOutParams['static']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                    $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                }
                                $tmpOutParams['static']["urut"] = $cCtr;
                                $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $tmpOutParams['static']["keterangan"] = $configUi["steps"][1]["label"] . " nomor " . $tmpNomorNota . " oleh " .$tableIn_master['oleh_nama'];
                            }

                            $mdlName = "Com" . ucfirst($comName);
                            $this->load->model("Coms/" . $mdlName);
                            $m = new $mdlName();

                            //===filter value nol, jika harus difilter
                            $tobeExecuted = true;
                            if (in_array($mdlName, $compValidators)) {
                                $loopParams = isset($tmpOutParams['loop']) ? $tmpOutParams['loop'] : array();
                                if (sizeof($loopParams) > 0) {
                                    foreach ($loopParams as $key => $val) {
                                        cekmerah("$comName : $key = $val ");
                                        if ($val == 0) {
                                            unset($tmpOutParams['loop'][$key]);
                                        }
                                    }
                                }
                                if (sizeof($tmpOutParams['loop']) < 1) {
                                    $tobeExecuted = false;
                                }
                            }
                            if ($tobeExecuted) {
                                //----- kiriman gerbang untuk counter mutasi rekening
                                if (method_exists($m, "setTableInMaster")) {
                                    $m->setTableInMaster($tableIn_master);
                                }
                                if (method_exists($m, "setMain")) {
                                    $m->setMain($main);
                                }
                                if (method_exists($m, "setJenisTr")) {
                                    $m->setJenisTr($this->jenisTr);
                                }
                                //----- kiriman gerbang untuk counter mutasi rekening
                                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                cekHitam($this->db->last_query());
                            }
                            $componentGate['master'][$cCtr] = $tmpOutParams;
                        }
                    }
                    else {
                        cekKuning("components is not set");
                    }
                    //endregion
                }
                else {
                    cekHitam("TIDAK ADA COMPONENT");
                }
                //endregion

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

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

                //region nulis paymentSource
                $stepCode = $configUi['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_source");
                if (array_key_exists($stepCode, $paymentSources)) {
                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs[1] as $paymentSrcConfig) {
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $arrDataPym = array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $this->session->login['id'],
                                "extern_nama" => $this->session->login['nama'],
                                "nomer" => $main['nomer'],
                                "externValueBlob" => blobEncode(array()),
//                                "externValueBlob" => $toInsertBlob, //blob untuk local POS di matikan, cukup ngirim ke web admin saja
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => isset($main["nilai_cash"]) ? $main["nilai_cash"] : 0,
                                "terbayar" => $payment_info['payment_nilai'],
                                "sisa" => isset($main["nilai_cash"]) ? $main["nilai_cash"]-$payment_info['payment_nilai'] : 0,
                                "cabang_id" => $this->session->login["cabang_id"],
                                "cabang_nama" => $this->session->login["cabang_nama"],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],

                                "machineID" => isset($this->session->login['machineID']) ? $this->session->login['machineID'] : "none",
                                "cpu_info" => isset($this->session->login['CPU_INFO']) ? $this->session->login['CPU_INFO'] : "none",
                                "com_name" => isset($this->session->login['COM_INFO']) ? $this->session->login['COM_INFO'] : "none",

                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                                "extern2_id" => $payment_info['payment_oto_id'],
                                "extern2_nama" => $payment_info['payment_oto_nama'],
                            );
//                            arrPrint($arrDataPym);
                            $pymSrcID = $tr->writePaymentSrc($insertID, $arrDataPym);
//                            cekMerah($this->db->last_query());

                            $kolomValidasi = isset($paymentSrcConfig['kolom']) ? $paymentSrcConfig['kolom'] : array();
                            if (sizeof($kolomValidasi) > 0) {
                                $trr = New MdlTransaksi();
                                $trr->setFilters(array());
                                $pym = $trr->lookupPaymentSrcByID($pymSrcID)->result();
//                                cekKuning($this->db->last_query());
                                foreach ($kolomValidasi as $kolom_validasi) {
                                    if (isset($pym[0]->$kolom_validasi)) {
                                        if ($pym[0]->$kolom_validasi == NULL) {
                                            $msg = "Settlement gagal disimpan. Sesi anda habis, silahkan login ulang.";
                                            mati_disini($msg);
                                        }
                                        else {
                                            cekUngu("kolom ada isinya");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion

                //region update transaksi yang sudah disettle
                if ($insertID) {
                    $tr->setFilters(array());
                    foreach ($ids as $u => $idToupdate) {
                        $tr->setTableName("transaksi");
                        $tr->setFilters(array());
                        $wheres = array(
                            "id" => $idToupdate,
                        );
                        $dataUpd = array(
                            "settlement_id" => $insertID,
                        );
                        $tr->updateData($wheres, $dataUpd);
                        cekHitam($this->db->last_query());
                    }
                }
                //endregion
            }
        }
        else {
            matiHEre("semua transaksi penjualan sudah settle");
        }

//        $result = json_decode($sendToMainServer, true);
//        echo json_encode($result);
//        echo "<script>top.HoldOn.close();</script>";
//        matiHere("STOP DULU TRANSAKSI POS BELUM COMMIT");
// matiHere();
        // $this->db->trans_commit();

        /*
         * API ke domian master di geser setelah commit karena  melibatakan jurnal di POS, kas pada penjualan hanya master
         */

        //region API Settle pusat
        $timeStart = strtotime(date("Y-m-d H:i:s"));
        $timeEnd = strtotime("+5 minutes", strtotime(date("Y-m-d H:i:s")));

        $url = ADM_DOMAIN."/penjualan/ActivityReportApi/doSettlementPosAPI";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dataEncoded) );
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        $sendToMainServer = curl_exec($ch);
        curl_close($ch);

        $this->fileSettlement($dataEncoded);

        $dateOutput = strtotime(json_decode($sendToMainServer, true)["date"]);

        if(($timeStart <= $dateOutput) && ($dateOutput <= $timeEnd)){

        $status = json_decode($sendToMainServer, true)["status"];

        if(!$status){
            $arrAlert = array(
                "type" => "error",
                "title" => "Gagal Settlement",
                "timer" => "1500",
                "showConfirmButton" => true,
                "allowOutsideClick" => false,
            );
            echo swalAlert($arrAlert);
            die();
        }
            elseif($status==99){
        $arrAlert = array(
                    "type" => "error",
                    "title" => "Settlement terkirim, Belum Commit...<br>(DEBUG MASIH AKTIF)",
//                    "timer" => "1500",
                    "showConfirmButton" => true,
                    "allowOutsideClick" => false,
                );
                echo swalAlert($arrAlert);
                die();
            }
            else{
                $arrAlert = array(
            "type" => "success",
            "title" => "Settlement Saved",
//                    "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );
        echo swalAlert($arrAlert);
                echo "<script> setTimeout(function(){ top.window.location.reload() }, 2500);</script>";
        unset($this->session->errMsg);
                $this->db->trans_commit();
            }
        }
        else{
            $arrAlert = array(
                "type" => "error",
                "title" => "Gagal Settlement <br> Cek Koneksi Internet, refresh browser dan ulangi settlement",
//                "timer" => "1500",
                "showConfirmButton" => true,
                "allowOutsideClick" => false,
            );
            echo swalAlert($arrAlert);
            die();
        }

    }

    public function fileSettlement($data)
    {
        $date = strtotime(date("Y-m-d H:i:s"));
        $machineID = MACHINE_ID;
        $file = fopen(__DIR__ . '/view/settlement_' . $machineID . "_$date".".json", "w");
        fwrite($file, json_encode($data));
        fclose($file);
    }
}
