<?php

/**
 * Created by PhpStorm.
 * User: aziz
 * Date: 2/14/2019
 * Time: 12:50 PM
 */
class ActivityReport extends CI_Controller
{
    private $jenisTr;
    private $steps = array();
    private $dates = array();

    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()
    {
        $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['year']) ? $_GET['year'] : 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;
        //        cekHitam($sID);
        $sID = isset($this->sID_alias[$sID]) ? $this->sID_alias[$sID] : "";
        //        cekHitam($sID);
        // $subj
        $steps = $this->config->item('heTransaksi_ui')[$this->jenisTr]['steps'];
        foreach ($steps as $num => $nSpec) {
            $stepNames[$nSpec['target']] = $nSpec['label'];
        }
        // arrPrint($stepNames);
        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->config->item("heTransaksi_ui")[$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("transaksi_data.trash='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');
        $this->db->where("year(transaksi.dtime)='$currYear'");
        // $this->db->where("month(transaksi.dtime)='$currMonth'");
        $tmp = $tr->lookupJoined()->result();

        // cekbiru($this->db->last_query());
        $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'");
            $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);
                    // 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();
        //arrprint($identifiers);

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

        $data = array(
            "mode"             => "recap",
            "title"            => $this->config->item("heTransaksi_ui")[$this->jenisTr]['label'] . " report",
            "subTitle"         => "monthly, " . $currYear,
            "times"            => $months,
            "timeLabel"        => "months",
            "names"            => isset($names) ? $names : array(),
            "recaps"           => $recaps,
            "jenisTr"          => $this->jenisTr,
            "trName"           => $this->config->item("heTransaksi_ui")[$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 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->config->item('heTransaksi_ui')[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$this->jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion

        $data = array(
            "jenisTr"          => $this->jenisTr,
            "mode"             => "recap",
            "title"            => $this->config->item("heTransaksi_ui")[$this->jenisTr]['label'] . " reports",
            "subTitle"         => "daily, " . lgTranslateTime($dateStr),
            "times"            => $months,
            "timeLabel"        => "dates",
            "names"            => isset($names) ? $names : array(),
            "recaps"           => $recaps,
            "jenisTr"          => $this->jenisTr,
            "trName"           => $this->config->item("heTransaksi_ui")[$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->config->item('heTransaksi_ui')[$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->config->item("heTransaksi_ui")[$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("transaksi_data.trash='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');
        $tr->addFilter("month(transaksi.dtime)='" . $currMonth . "'");
        $tr->addFilter("year(transaksi.dtime)='" . $currYear . "'");
        $tmp = $tr->lookupJoined()->result();

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

        $data = array(
            "jenisTr"          => $this->jenisTr,
            "mode"             => "recap",
            "title"            => $this->config->item("heTransaksi_ui")[$this->jenisTr]['label'] . " reports",
            "subTitle"         => "daily, " . lgTranslateTime($dateStr),
            "times"            => $months,
            "timeLabel"        => "dates",
            "names"            => isset($names) ? $names : array(),
            "recaps"           => $recaps,
            "jenisTr"          => $this->jenisTr,
            "trName"           => $this->config->item("heTransaksi_ui")[$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 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->config->item("heTransaksi_ui")[$this->jenisTr]['steps'][1]['label']) ? $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$jenisTr]['compactHistoryFields']) ? $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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 viewMySettlement()
    {
        // matiHere(__LINE__);
        $jenisTr = $this->uri->segment(3);

        $this->jenisTrName = isset($this->config->item("heTransaksi_ui")[$this->jenisTr]['steps'][1]['label']) ? $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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",
        );
        // arrPrint($historyFields);
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->config->item("heTransaksi_ui")[$jenisTr]['compactHistoryFields']) ? $this->config->item("heTransaksi_ui")[$jenisTr]['compactHistoryFields'] : array();
        }

        /* -------------------------- ---------------------------
         * JIKA DI CONFIG UI TIDAK ADA settlementHistoryFields
         * AKAN MENGUNAKAN HEADER DEFAULT
         * nilai-nilai disini hanya ngambil dari registry
         * ------------------------------------------------------*/
        $trHeaders = isset($this->config->item("heTransaksi_ui")[$jenisTr]['settlementHistoryFields']) ? $this->config->item("heTransaksi_ui")[$jenisTr]['settlementHistoryFields'] : array(
            "dtime"       => "time",
            "nomer"       => "receipt number",
            "jenis_label" => "activity",
            //            "transaksi_nilai" => "orig. value",
            //            "add_disc" => "discount",
            //            "grand_total" => "nett",
            "harga"       => "orig. value",
            "disc"        => "discount",
            "nett1"       => "nett",
            "ppn"         => "ppn",
            "nett2"       => "total",
        );
        $trItems = array();
        // arrPrint($trHeaders);
        //
        //region getting trans-IDs
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $mySettlementDatas = $tr->callMyTransaksi(my_id(), my_cabang_id());
        // arrPrint(sizeof($mySettlementDatas));

        $tr->setFilters(array());

        $tr->addFilter("transaksi.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_registry.param='tableIn_master_values'");
        $tr->addFilter("transaksi_registry.param='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;

        $this->db->order_by("transaksi.id");

        //        $tmpHist0 = $tr0->lookupHistories_joined_all()->result();
        $tmpHist0 = $tr0->lookupRegistries_joined()->result();
        // cekmerah($this->db->last_query());
        // arrPrint($tmpHist0);
        if (sizeof($tmpHist0) > 0) {
            foreach ($tmpHist0 as $row) {
                if (!in_array($row->transaksi_id, $trIDs)) {
                    $trIDs[] = $row->transaksi_id;
                    $tmpCol = array();
                    $content = blobDecode($row->values);

                    // arrPrintPink($row);
                    // arrPrint($content);

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

        $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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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,
            "trItems"           => $trItems,
            "mySettlementDatas" => $mySettlementDatas,


        );
        //endregion


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

        $data = array(
            "mode"             => "recap",
            "title"            => $this->config->item("heTransaksi_ui")[$this->jenisTr]['label'] . " report",
            "subTitle"         => "monthly, " . $currYear,
            "times"            => $months,
            "timeLabel"        => "months",
            "names"            => isset($names) ? $names : array(),
            "recaps"           => $recaps,
            "jenisTr"          => $this->jenisTr,
            "trName"           => $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$this->jenisTr]['label'] . " report",
            "subTitle"         => "",
            // "times"            => $months,
            "tblHeadings"      => $headers,
            "tblBodies"        => $bodies,
            "names"            => isset($names) ? $names : array(),
            // "recaps"           => $recaps,
            "jenisTr"          => $this->jenisTr,
            "trName"           => $this->config->item("heTransaksi_ui")[$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()
    {
        $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->config->item("heTransaksi_ui")[$jenisTr]['historyFields'][$selectedSTep]) ? $this->config->item("heTransaksi_ui")[$jenisTr]['historyFields'][$selectedSTep] : $this->config->item("heTransaksi_ui")[$jenisTr]['shortHistoryFields'];
        $pairRegistries = isset($this->config->item("heTransaksi_ui")[$jenisTr]['pairRegistries']) ? $this->config->item("heTransaksi_ui")[$jenisTr]['pairRegistries'] : array();
        $pairTransaksi = isset($this->config->item("heTransaksi_ui")[$jenisTr]['pairTransaksi']) ? $this->config->item("heTransaksi_ui")[$jenisTr]['pairTransaksi'] : array();

        $historyFieldsExt = isset($this->config->item("heTransaksi_ui")[$jenisTr]["extHistoryFields"][$selectedSTep]) ? $this->config->item("heTransaksi_ui")[$jenisTr]["extHistoryFields"][$selectedSTep] : array();
        $customButton = isset($this->config->item("heTransaksi_layout")[$jenisTr]["customButton"][$selectedSTep]) ? $this->config->item("heTransaksi_layout")[$jenisTr]["customButton"][$selectedSTep] : array();
        $printValas = isset($this->config->item("heTransaksi_layout")[$jenisTr]["print_nvalas"]) ? $this->config->item("heTransaksi_layout")[$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->config->item("heTransaksi_ui") && sizeof($this->config->item("heTransaksi_ui")) > 0) {
            foreach ($this->config->item("heTransaksi_ui") 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->config->item("heTransaksi_ui")[$jenisTr]['shortHistoryFields']) ? $this->config->item("heTransaksi_ui")[$jenisTr]['shortHistoryFields'] : array();
                $pairRegistries = isset($this->config->item("heTransaksi_ui")[$jenisTr]['pairRegistries']) ? $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$jenisTr]['compactHistoryFields']) ? $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui");
        $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", "settlement 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->config->item("heTransaksi_ui")[$this->jenisTr]) ? $this->config->item("heTransaksi_ui")[$this->jenisTr] : matiHere("undetected jenis transaksi");
        $curentJenis = $config_ui["steps"]["1"]["target"];
        // matiHEre($curentJenis);
        // $this->jenisTr = "589";

        $cCode = "_TR_" . $jenisTr;
        // arrPrint($this->config->item("heTransaksi_core")[$jenisTr]);
        $configGates = isset($this->config->item("heTransaksi_core")[$jenisTr]['settlementGates']) ? $this->config->item("heTransaksi_core")[$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->config->item("heTransaksi_ui")[$jenisTr]['settlementHistoryFields']) ? $this->config->item("heTransaksi_ui")[$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->config->item("heTransaksi_ui");
        $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!");
        }
    }
}
