<?php

class ReceiveSuratJalan extends MY_Controller
{
    var $db;
    public function index()
    {
        echo "Receive Surat Jalan API";
    }

    public function __construct()
    {
        parent::__construct();
    }

    public function LookupEkspedisi()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $para = $this->sys_input;
            $type = $para['isInternal'];
            $name = "%";
            if ($para['expdName'] != "") {
                $name = $para['expdName'] . "%";
            }

            $sqlexp = "SELECT 
                ExpeditionID,
                ExpeditionName,
                ExpeditionIsInternal
            FROM expedition
            WHERE ExpeditionIsActive = 'Y'
                AND ExpeditionIsInternal = ?
                AND ExpeditionName LIKE ?";
            $qryexp = $this->db->query($sqlexp, [$type, $name]);
            if (!$qryexp) {
                $this->sys_error_db("error get listing expedition");
                exit;
            }

            $result = array(
                "records" => $qryexp->result_array(),
                "total" => sizeof($qryexp->result_array())
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function LookupEkspedisiStaff()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $para = $this->sys_input;
            $expID = $para['expID'];
            $name = "%";
            if ($para['staffName'] != "") {
                $name = $para['staffName'] . "%";
            }

            $sqlexp = "SELECT 
                ExpeditionStaffID,
                ExpeditionStaffName,
                ExpeditionStaffMobile
            FROM expeditionstaff
            WHERE ExpeditionStaffIsActive = 'Y'
                AND ExpeditionStaffExpeditionID = ?
                AND ExpeditionStaffName LIKE ?";
            $qryexp = $this->db->query($sqlexp, [$expID, $name]);
            if (!$qryexp) {
                $this->sys_error_db("error get listing expedition staff");
                exit;
            }

            $result = array(
                "records" => $qryexp->result_array(),
                "total" => sizeof($qryexp->result_array())
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function SaveReciveSJ()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $para = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $mustFields = ['suratJalanID', 'goodTransferID', 'warehouseID'];
            $missFields = [];
            foreach ($mustFields as $field) {
                if (empty($para[$field])) {
                    $missFields[] = $field;
                }
            }
            if (!empty($missFields)) {
                $this->sys_error("Missing fields: " . implode(", ", $missFields));
                exit;
            }

            $this->db->trans_begin();

            // query update surat jalan
            $sqlSJ = "UPDATE suratjalan 
                SET SuratJalanStatus = 'Completed',
                    SuratJalanReceivedDate = NOW(),
                    SuratJalanReceivedUserID = ?,
                    SuratJalanReceivedNote = ?,
                    SuratJalanReceivedWarehouseID = ?,
                    SuratJalanLastUpdated = NOW(),
                    SuratJalanUserID = ?
                WHERE SuratJalanID = ?";
            $qrySJ = $this->db->query($sqlSJ, [
                $userId,
                $para['notereceive'],
                $para['warehouseID'],
                $userId,
                $para['suratJalanID']
            ]);
            if (!$qrySJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("error update surat jalan", $this->db);
                exit;
            }

            // query untuk penerimaan qty
            if (count($para['detailsj']) > 0) {
                foreach ($para['detailsj'] as $k => $v) {
                    $sqldetail = "UPDATE suratjalan_detail SET
                        SuratJalanDetailQtyReceived = ?,
                        SuratJalanDetailLastUpdated = NOW(),
                        SuratJalanDetailUserID = ?
                        WHERE SuratJalanDetailID = ?";
                    $qrydetail = $this->db->query($sqldetail, [
                        intval($v['SuratJalanDetailQtyReceived']),
                        $userId,
                        $v['SuratJalanDetailID']
                    ]);
                    if (!$qrydetail) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("error update surat jalan detail", $this->db);
                        exit;
                    }
                }
            }

            // query update transfer request
            $sqlTransfer = "UPDATE t_goods_transfer
                        SET T_GoodsTransferStatus = 'Completed',
                            T_GoodsTransferLastUpdated = NOW(),
                            T_GoodsTransferM_UserID = ?
                            WHERE T_GoodsTransferID = ?";
            $qryTransfer = $this->db->query($sqlTransfer, [
                $userId,
                $para['goodTransferID']
            ]);
            if (!$qryTransfer) {
                $this->db->trans_rollback();
                $this->sys_error_db("error update transfer barang", $this->db);
            }

            // query untuk mendapatakan data suratjalan detail
            $sqlDetail = "SELECT SuratJalanDetailID,
                            SuratJalanDetailSuratJalanID,
                            SuratJalanDetailPurchaseRequestFlagID,
                            SuratJalanDetailM_ItemID,
                            SuratJalanDetailQtyReceived,
                            S_RegionalID,
                            M_BranchID,
                            M_BranchCode,
                            M_BranchName,
                            SuratJalanDetailT_GoodsTransferDetailID,
                            WarehouseID,
                            stock.*
                            FROM suratjalan_detail
                            JOIN suratjalan ON SuratJalanDetailSuratJalanID = SuratJalanID
                                AND SuratJalanIsActive = 'Y'
                            JOIN t_goods_transfer ON SuratJalanT_GoodsTransferID = T_GoodsTransferID 
                                AND T_GoodsTransferIsActive = 'Y'
                            JOIN m_branch ON T_GoodsTransferToM_BranchCode = M_BranchCode 
                                AND M_BranchIsActive = 'Y'
                            JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID 
                                AND S_RegionalIsActive = 'Y'
                            JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID 
                                AND M_ItemIsActive = 'Y'
                            JOIN stock ON StockItemID = M_ItemID 
                            JOIN warehouse ON StockWarehouseID = WarehouseID 
                                AND WarehouseIsTransit = 'Y'
                                AND WarehouseIsActive = 'Y'
                            WHERE SuratJalanDetailIsActive = 'Y'
                            AND SuratJalanDetailSuratJalanID = ?";
            $qry_flag = $this->db->query($sqlDetail, [$para['suratJalanID']]);
            if (!$qry_flag) {
                $this->db->trans_rollback();
                $this->sys_error_db("select surat jalan detail error", $this->db);
                exit;
            }
            $rowsDetailSJ = $qry_flag->result_array();
            // print_r($rowsDetailSJ);

            foreach ($rowsDetailSJ as $k => $v) {

                // update stock warehouse transit
                $updsto = "UPDATE stock 
                    SET StockQty = 0
                    WHERE StockID = ? 
                        AND StockWarehouseID = ?";
                $qrysto = $this->db->query($updsto, [
                    $v['StockID'],
                    $v['WarehouseID']
                ]);
                if (!$qrysto) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("update stock qty");
                    exit;
                }

                // insert into stocklog
                $slog = "INSERT INTO stocklog (
                        StockLogWarehouseID,
                        StockLogDateTime,
                        StockLogItemID,
                        StockLogItemUnitID,
                        StockLogStockNumber,
                        StockLogBatchNo,
                        StockLogED,
                        StockLogReffID,
                        StockLogStatus,
                        StockLogQty,
                        StockLogUserID
                    ) VALUES (?,NOW(),?,?,?,?,?,?,?,?,?)";
                $qlog = $this->db->query($slog, [
                    $v['WarehouseID'],
                    $v['StockItemID'],
                    $v['StockItemUnitID'],
                    $v['StockStockNumber'],
                    $v['StockBatchNo'],
                    $v['StockED'],
                    $v['SuratJalanDetailT_GoodsTransferDetailID'],
                    "TTW",
                    $v['SuratJalanDetailQtyReceived'],
                    $userId,
                ]);
                if (!$qlog) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] insert stocklog");
                    exit;
                }

                // Query untuk mendapatkan data purchase request flag
                $sql_select = "SELECT 
                    PurchaseRequestFlagID,
                    PurchaseRequestFlagQtyRest,
                    PurchaseRequestFlagPurchaseRequestDetailID
                FROM purchase_request_flag
                WHERE PurchaseRequestFlagID = ?";

                $qry_select = $this->db->query($sql_select, [$v["SuratJalanDetailPurchaseRequestFlagID"]]);

                if (!$qry_select) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("select purchase flag error", $this->db);
                    exit;
                }

                $rows_flag = $qry_select->result_array();
                // print_r($rows_flag);
                // exit;

                foreach ($rows_flag as $flag) {
                    $purchaseRequestFlagQtyRest = intval($flag['PurchaseRequestFlagQtyRest']);
                    $suratJalanDetailQtyReceived = intval($v['SuratJalanDetailQtyReceived']);

                    // Validasi sebelum update
                    if ($suratJalanDetailQtyReceived > $purchaseRequestFlagQtyRest) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("Qty received melebihi qty rest", $this->db);
                        exit;
                    }

                    $newQtyRest = $purchaseRequestFlagQtyRest - $suratJalanDetailQtyReceived;

                    // Update purchase request flag
                    $sql = "UPDATE purchase_request_flag SET
                            PurchaseRequestFlagQtyProses = 0,
                            PurchaseRequestFlagQtyRest = ?,
                            PurchaseRequestFlagUserID = ?,
                            PurchaseRequestFlagLastUpdated = NOW()
                        WHERE PurchaseRequestFlagID = ?";

                    $qry = $this->db->query($sql, [
                        $newQtyRest,
                        $userId,
                        $flag['PurchaseRequestFlagID']
                    ]);

                    if (!$qry) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("update flag error", $this->db);
                        exit;
                    }

                    // cari PRID untuk update purchase request
                    $sqlpr_detail = "SELECT PurchaseRequestDetailID,
                                    PurchaseRequestDetailPurchaseRequestID,
                                    PurchaseRequestDetailStatus,
                                    PurchaseRequestDetailQty
                                    FROM purchase_request_detail
                                    WHERE PurchaseRequestDetailID = ? 
                                    AND PurchaseRequestDetailIsActive = 'Y'";
                    $qrypr_detail = $this->db->query($sqlpr_detail, $flag['PurchaseRequestFlagPurchaseRequestDetailID']);
                    if (!$qrypr_detail) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("select purchase_request_detail error", $this->db);
                        exit;
                    }

                    $row_detail = $qrypr_detail->row_array();

                    // Menentukan status berdasarkan kondisi
                    $purchaseRequestStatus = 'Partial'; // Default status

                    if (intval($flag['PurchaseRequestFlagQtyRest']) == 0) {
                        $purchaseRequestStatus = 'Completed';
                    } elseif (intval($flag['PurchaseRequestFlagQtyRest']) < intval($row_detail["PurchaseRequestDetailQty"])) {
                        $purchaseRequestStatus = 'Partial';
                    }

                    // Update status purchase request hanya sekali dengan status yang sudah ditentukan
                    $sqlpr = "UPDATE purchase_request SET
                            PurchaseRequestStatus = ?,
                            PurchaseRequestUserID = ?,
                            PurchaseRequestLastUpdated = NOW()
                            WHERE PurchaseRequestID = ?";
                    $qrypr = $this->db->query($sqlpr, [
                        $purchaseRequestStatus,
                        $userId,
                        $row_detail["PurchaseRequestDetailPurchaseRequestID"]
                    ]);
                    if (!$qrypr) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("update purchase_request error", $this->db);
                        exit;
                    }
                }
            }

            $sql_json = "SELECT suratjalan.*, '' as details
            FROM suratjalan
            WHERE SuratJalanIsActive = 'Y'
            AND SuratJalanID = ?";
            $qry_json = $this->db->query($sql_json, [$para['suratJalanID']]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json sj error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $descActivity = "Simpan qty receive surat jalan No {$row_json['SuratJalanNumber']}, status {$row_json['SuratJalanStatus']}";

            $sql_json_detail = "SELECT suratjalan_detail.* 
                FROM suratjalan_detail
                WHERE SuratJalanDetailIsActive = 'Y'
                AND SuratJalanDetailSuratJalanID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$para['suratJalanID']]);
            if ($qry_json_detail) {
                $row_json["details"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail sj error", $this->db);
                exit;
            }

            $data_json = $row_json;

            $this->insertUserActivty(
                $para['suratJalanID'],
                'COMPLETED',
                $userId,
                $descActivity,
                json_encode($data_json)
            );
            $this->db->trans_commit();

            $newUpdate = "SELECT * FROM suratjalan WHERE SuratJalanID = {$para['suratJalanID']} AND SuratJalanIsActive = 'Y'";
            $records = $this->db->query($newUpdate, [])->result_array();
            $result = array("records" => $records, "msg" => "success update surat jalan");
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    public function ConfirmSuratJalan()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $para = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $mustFields = ['suratJalanID', 'goodTransferID', 'warehouseID'];
            $missFields = [];
            foreach ($mustFields as $field) {
                if (empty($para[$field])) {
                    $missFields[] = $field;
                }
            }
            if (!empty($missFields)) {
                $this->sys_error("Missing fields: " . implode(", ", $missFields));
                exit;
            }

            $this->db->trans_begin();

            $sqlDetail = "SELECT suratjalan.*, DATE_FORMAT(SuratJalanDate, '%d-%m-%Y') formatedDate,
                CASE
                    WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) 
                    WHEN WarehouseType = 'R' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) 
                ELSE ''
                END WarehouseName,
                WarehouseID
                FROM suratjalan
                JOIN warehouse
                ON SuratJalanReceivedWarehouseID = WarehouseID
                JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID AND M_BranchIsActive = 'Y'
                WHERE SuratJalanID = ?";
            $qry_flag = $this->db->query($sqlDetail, [$para['suratJalanID']]);
            if (!$qry_flag) {
                $this->db->trans_rollback();
                $this->sys_error_db("select surat jalan detail error", $this->db);
                exit;
            }
            $dataSJ = $qry_flag->row_array();
            if ($dataSJ['SuratJalanReceivedConfirmed'] == 'Y') {
                $this->db->trans_rollback();
                $this->sys_error("Surat jalan {$dataSJ['SuratJalanNumber']} sudah pernah dikonfirmasi");
                exit;
            }

            $sql = "SELECT suratjalan_detail.*, stock.*
                FROM suratjalan_detail
                JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID 
                    AND M_ItemIsActive = 'Y'
                JOIN stock ON StockItemID = M_ItemID 
                WHERE SuratJalanDetailSuratJalanID = ? AND SuratJalanDetailIsActive='Y'";
            $qry = $this->db->query($sql, [$para['suratJalanID']]);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("get sj detail ", $this->db);;
                exit;
            }
            $detailSJ =  $qry->result_array();

            $descActivity = "Konfirmasi Penerimaan Surat Jalan {$dataSJ['SuratJalanNumber']} Tanggal {$dataSJ['formatedDate']} Di {$dataSJ['WarehouseName']}.";
            foreach ($detailSJ as $k => $v) {

                $sql = "INSERT INTO stock (
                    StockWarehouseAlmariID,
                    StockWarehouseRackID,
                    StockWarehouseID,
                    StockStockNumber,
                    StockBatchNo,
                    StockItemID,
                    StockItemUnitID,
                    StockED,
                    StockItemPrice,
                    StockQty,
                    StockLastUpdated,
                    StockUserID
                ) VALUES (
                    0, 0, ?, fn_numbering('SN'), ?, ?, ?, ?, ?, ?, NOW(), ?
                )
                ON DUPLICATE KEY UPDATE
                    StockQty = StockQty + VALUES(StockQty),
                    StockLastUpdated = NOW(),
                    StockUserID = VALUES(StockUserID);";
                $qry = $this->db->query($sql, array(
                    $dataSJ['WarehouseID'],
                    $v['StockBatchNo'],
                    $v['SuratJalanDetailM_ItemID'],
                    $v['SuratJalanDetailItemUnitID'],
                    $v['StockED'],
                    $v['StockItemPrice'],
                    $v['SuratJalanDetailQtyReceived'],
                    $userId
                ));
                if (!$qry) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Error insert update or insert stock");
                    exit;
                }

                $sql = "SELECT * FROM stock 
                    WHERE StockWarehouseID = ?
                    AND StockWarehouseAlmariID = 0
                    AND StockWarehouseRackID = 0
                    AND StockBatchNo = ?
                    AND StockItemID = ?
                    AND StockItemUnitID = ?
                    AND StockED = ?
                    ";
                $qry = $this->db->query($sql, array(
                    $dataSJ['WarehouseID'],
                    $v['StockBatchNo'],
                    $v['SuratJalanDetailM_ItemID'],
                    $v['SuratJalanDetailItemUnitID'],
                    $v['StockED']
                ));
                if (!$qry) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Error get stock stock");
                    exit;
                }
                $stock = $qry->row_array();

                // insert stockcard
                $sqlcard = "INSERT INTO stockcard (
                    StockCardWarehouseID,
                    StockCardDatetime,
                    StockCardItemID,
                    StockCardItemUnitID,
                    StockCardBatchNo,
                    StockCardED,
                    StockCardReffID,
                    StockCardStatus,
                    StockCardBefore,
                    StockCardIn,
                    StockCardOut,
                    StockCardAfter,
                    StockCardUserID
                ) VALUES (?, NOW(), ?, ?, ?, ?, ?, 'SJ', ?, 0, ?, ?, ?)";
                $qrycard = $this->db->query($sqlcard, array(
                    $dataSJ["WarehouseID"],
                    $v["SuratJalanDetailM_ItemID"],
                    $v["SuratJalanDetailItemUnitID"],
                    $v['StockBatchNo'],
                    $v['StockED'],
                    $stock["StockID"],
                    (intval($stock['StockQty']) - intval($v['SuratJalanDetailQtyReceived'])) < 0 ? 0 : (intval($stock['StockQty']) - intval($v['SuratJalanDetailQtyReceived'])),
                    intval($v['SuratJalanDetailQtyReceived']),
                    intval($stock['StockQty']),
                    $userId
                ));
                if (!$qrycard) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Error insert stock card", $this->db);
                    exit;
                }

                // insert into stocklog
                $slog = "INSERT INTO stocklog (
                        StockLogWarehouseID,
                        StockLogDateTime,
                        StockLogItemID,
                        StockLogItemUnitID,
                        StockLogStockNumber,
                        StockLogBatchNo,
                        StockLogED,
                        StockLogReffID,
                        StockLogStatus,
                        StockLogQty,
                        StockLogUserID
                    ) VALUES (?,NOW(),?,?,?,?,?,?,?,?,?)";
                $qlog = $this->db->query($slog, [
                    $dataSJ['WarehouseID'],
                    $v['SuratJalanDetailM_ItemID'],
                    $v['SuratJalanDetailItemUnitID'],
                    $stock['StockStockNumber'],
                    $v['StockBatchNo'],
                    $v['StockED'],
                    $stock['StockID'],
                    "RSJ",
                    $v['SuratJalanDetailQtyReceived'],
                    $userId,
                ]);
                if (!$qlog) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] insert stocklog");
                    exit;
                }
            }

            // generate jurnal
            $this->GenerateJurnal($para['suratJalanID']);
            $this->insertUserActivty(
                $para['suratJalanID'],
                'CONFIRM',
                $userId,
                $descActivity,
                ''
            );
            $this->db->trans_commit();

            $newUpdate = "SELECT * FROM suratjalan WHERE SuratJalanID = {$para['suratJalanID']} AND SuratJalanIsActive = 'Y'";
            $records = $this->db->query($newUpdate, [])->result_array();
            $result = array("records" => $records, "msg" => "success update surat jalan");
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    // public function ConfirmSuratJalan_backup()
    // {
    //     try {
    //         if (!$this->isLogin) {
    //             $this->sys_error("invalid token");
    //             exit;
    //         }

    //         $para = $this->sys_input;
    //         $userId = $this->sys_user["M_UserID"];
    //         $mustFields = ['suratJalanID', 'goodTransferID', 'warehouseID'];
    //         $missFields = [];
    //         foreach ($mustFields as $field) {
    //             if (empty($para[$field])) {
    //                 $missFields[] = $field;
    //             }
    //         }
    //         if (!empty($missFields)) {
    //             $this->sys_error("Missing fields: " . implode(", ", $missFields));
    //             exit;
    //         }

    //         $this->db->trans_begin();

    //         // query update transfer request
    //         $sqlTransfer = "UPDATE t_goods_transfer
    //                     SET T_GoodsTransferStatus = 'Completed',
    //                         T_GoodsTransferLastUpdated = NOW(),
    //                         T_GoodsTransferM_UserID = ?
    //                         WHERE T_GoodsTransferID = ?";
    //         $qryTransfer = $this->db->query($sqlTransfer, [
    //             $userId,
    //             $para['goodTransferID']
    //         ]);
    //         if (!$qryTransfer) {
    //             $this->db->trans_rollback();
    //             $this->sys_error_db("error update transfer barang", $this->db);
    //         }

    //         // query untuk mendapatakan data suratjalan detail
    //         $sqlDetail = "SELECT SuratJalanDetailID,
    //                         SuratJalanDetailSuratJalanID,
    //                         SuratJalanDetailPurchaseRequestFlagID,
    //                         SuratJalanDetailM_ItemID,
    //                         SuratJalanDetailQtyReceived,
    //                         S_RegionalID,
    //                         M_BranchID,
    //                         M_BranchCode,
    //                         M_BranchName,
    //                         SuratJalanDetailT_GoodsTransferDetailID,
    //                         WarehouseID,
    //                         stock.*
    //                         FROM suratjalan_detail
    //                         JOIN suratjalan ON SuratJalanDetailSuratJalanID = SuratJalanID
    //                             AND SuratJalanIsActive = 'Y'
    //                         JOIN t_goods_transfer ON SuratJalanT_GoodsTransferID = T_GoodsTransferID 
    //                             AND T_GoodsTransferIsActive = 'Y'
    //                         JOIN m_branch ON T_GoodsTransferToM_BranchCode = M_BranchCode 
    //                             AND M_BranchIsActive = 'Y'
    //                         JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID 
    //                             AND S_RegionalIsActive = 'Y'
    //                         JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID 
    //                             AND M_ItemIsActive = 'Y'
    //                         JOIN stock ON StockItemID = M_ItemID 
    //                         JOIN warehouse ON StockWarehouseID = WarehouseID 
    //                             AND WarehouseIsTransit = 'Y'
    //                             AND WarehouseIsActive = 'Y'
    //                         WHERE SuratJalanDetailIsActive = 'Y'
    //                         AND SuratJalanDetailSuratJalanID = ?";
    //         $qry_flag = $this->db->query($sqlDetail, [$para['suratJalanID']]);
    //         if (!$qry_flag) {
    //             $this->db->trans_rollback();
    //             $this->sys_error_db("select surat jalan detail error", $this->db);
    //             exit;
    //         }
    //         $rowsDetailSJ = $qry_flag->result_array();
    //         // print_r($rowsDetailSJ);

    //         foreach ($rowsDetailSJ as $k => $v) {

    //             // update stock warehouse transit
    //             $updsto = "UPDATE stock 
    //                 SET StockQty = 0
    //                 WHERE StockID = ? 
    //                     AND StockWarehouseID = ?";
    //             $qrysto = $this->db->query($updsto, [
    //                 $v['StockID'],
    //                 $v['WarehouseID']
    //             ]);
    //             if (!$qrysto) {
    //                 $this->db->trans_rollback();
    //                 $this->sys_error_db("update stock qty");
    //                 exit;
    //             }


    //             $sql = "INSERT INTO stock (
    //                 StockWarehouseAlmariID,
    //                 StockWarehouseRackID,
    //                 StockWarehouseID,
    //                 StockStockNumber,
    //                 StockBatchNo,
    //                 StockItemID,
    //                 StockItemUnitID,
    //                 StockED,
    //                 StockItemPrice,
    //                 StockQty,
    //                 StockLastUpdated,
    //                 StockUserID
    //             ) VALUES (
    //                 0, 0, ?, fn_numbering('SN'), ?, ?, ?, ?, ?, ?, NOW(), ?
    //             )
    //             ON DUPLICATE KEY UPDATE
    //                 StockItemPrice = VALUES(StockItemPrice),
    //                 StockQty = StockQty + VALUES(StockQty),
    //                 StockLastUpdated = NOW(),
    //                 StockUserID = VALUES(StockUserID);";
    //             $qry = $this->db->query($sql, array(
    //                 $dataRo['WarehouseID'],
    //                 $item['ReceiveOrderPoDetailBatchNo'],
    //                 $item['ReceiveOrderPoItemID'],
    //                 $item['ReceiveOrderPoItemUnitID'],
    //                 $item['ReceiveOrderPoDetailEd'],
    //                 $item['ReceiveOrderPoDetailPrice'],
    //                 $item['ReceiveOrderPoDetailQty'],
    //                 $userId
    //             ));
    //             if (!$qry) {
    //                 $this->db->trans_rollback();
    //                 $this->sys_error_db("Error insert update or insert stock");
    //                 exit;
    //             }


    //             // insert stockcard
    //             $sqlcard = "INSERT INTO stockcard (
    //                 StockCardWarehouseID,
    //                 StockCardDatetime,
    //                 StockCardItemID,
    //                 StockCardItemUnitID,
    //                 StockCardBatchNo,
    //                 StockCardED,
    //                 StockCardReffID,
    //                 StockCardStatus,
    //                 StockCardBefore,
    //                 StockCardIn,
    //                 StockCardOut,
    //                 StockCardAfter,
    //                 StockCardUserID
    //             ) VALUES (?, NOW(), ?, ?, ?, ?, ?, 'SJ', ?, 0, ?, ?, ?)";
    //             $qrycard = $this->db->query($sqlcard, array(
    //                 $v["WarehouseID"],
    //                 $v["StockItemID"],
    //                 $v["StockItemUnitID"],
    //                 $v["StockBatchNo"],
    //                 $v["StockED"],
    //                 $v["StockID"],
    //                 (intval($v['StockQty']) - intval($v['SuratJalanDetailQtyReceived'])) < 0 ? 0 : (intval($v['StockQty']) - intval($v['SuratJalanDetailQtyReceived'])),
    //                 intval($v['SuratJalanDetailQtyReceived']),
    //                 intval($v['StockQty']),
    //                 $userId
    //             ));
    //             if (!$qrycard) {
    //                 $this->db->trans_rollback();
    //                 $this->sys_error_db("Error insert stock card", $this->db);
    //                 exit;
    //             }

    //             // insert into stocklog
    //             $slog = "INSERT INTO stocklog (
    //                     StockLogWarehouseID,
    //                     StockLogDateTime,
    //                     StockLogItemID,
    //                     StockLogItemUnitID,
    //                     StockLogStockNumber,
    //                     StockLogBatchNo,
    //                     StockLogED,
    //                     StockLogReffID,
    //                     StockLogStatus,
    //                     StockLogQty,
    //                     StockLogUserID
    //                 ) VALUES (?,NOW(),?,?,?,?,?,?,?,?,?)";
    //             $qlog = $this->db->query($slog, [
    //                 $v['WarehouseID'],
    //                 $v['StockItemID'],
    //                 $v['StockItemUnitID'],
    //                 $v['StockStockNumber'],
    //                 $v['StockBatchNo'],
    //                 $v['StockED'],
    //                 $v['SuratJalanDetailT_GoodsTransferDetailID'],
    //                 "TTW",
    //                 $v['SuratJalanDetailQtyReceived'],
    //                 $userId,
    //             ]);
    //             if (!$qlog) {
    //                 $this->db->trans_rollback();
    //                 $this->sys_error_db("[Error] insert stocklog");
    //                 exit;
    //             }

    //             // Query untuk mendapatkan data purchase request flag
    //             $sql_select = "SELECT 
    //                 PurchaseRequestFlagID,
    //                 PurchaseRequestFlagQtyRest,
    //                 PurchaseRequestFlagPurchaseRequestDetailID
    //             FROM purchase_request_flag
    //             WHERE PurchaseRequestFlagID = ?";

    //             $qry_select = $this->db->query($sql_select, [$v["SuratJalanDetailPurchaseRequestFlagID"]]);

    //             if (!$qry_select) {
    //                 $this->db->trans_rollback();
    //                 $this->sys_error_db("select purchase flag error", $this->db);
    //                 exit;
    //             }

    //             $rows_flag = $qry_select->result_array();
    //             // print_r($rows_flag);
    //             // exit;

    //             foreach ($rows_flag as $flag) {
    //                 $purchaseRequestFlagQtyRest = intval($flag['PurchaseRequestFlagQtyRest']);
    //                 $suratJalanDetailQtyReceived = intval($v['SuratJalanDetailQtyReceived']);

    //                 // Validasi sebelum update
    //                 if ($suratJalanDetailQtyReceived > $purchaseRequestFlagQtyRest) {
    //                     $this->db->trans_rollback();
    //                     $this->sys_error_db("Qty received melebihi qty rest", $this->db);
    //                     exit;
    //                 }

    //                 $newQtyRest = $purchaseRequestFlagQtyRest - $suratJalanDetailQtyReceived;

    //                 // Update purchase request flag
    //                 $sql = "UPDATE purchase_request_flag SET
    //                         PurchaseRequestFlagQtyProses = 0,
    //                         PurchaseRequestFlagQtyRest = ?,
    //                         PurchaseRequestFlagUserID = ?,
    //                         PurchaseRequestFlagLastUpdated = NOW()
    //                     WHERE PurchaseRequestFlagID = ?";

    //                 $qry = $this->db->query($sql, [
    //                     $newQtyRest,
    //                     $userId,
    //                     $flag['PurchaseRequestFlagID']
    //                 ]);

    //                 if (!$qry) {
    //                     $this->db->trans_rollback();
    //                     $this->sys_error_db("update flag error", $this->db);
    //                     exit;
    //                 }

    //                 // cari PRID untuk update purchase request
    //                 $sqlpr_detail = "SELECT PurchaseRequestDetailID,
    //                                 PurchaseRequestDetailPurchaseRequestID,
    //                                 PurchaseRequestDetailStatus,
    //                                 PurchaseRequestDetailQty
    //                                 FROM purchase_request_detail
    //                                 WHERE PurchaseRequestDetailID = ? 
    //                                 AND PurchaseRequestDetailIsActive = 'Y'";
    //                 $qrypr_detail = $this->db->query($sqlpr_detail, $flag['PurchaseRequestFlagPurchaseRequestDetailID']);
    //                 if (!$qrypr_detail) {
    //                     $this->db->trans_rollback();
    //                     $this->sys_error_db("select purchase_request_detail error", $this->db);
    //                     exit;
    //                 }

    //                 $row_detail = $qrypr_detail->row_array();

    //                 // Menentukan status berdasarkan kondisi
    //                 $purchaseRequestStatus = 'Partial'; // Default status

    //                 if (intval($flag['PurchaseRequestFlagQtyRest']) == 0) {
    //                     $purchaseRequestStatus = 'Completed';
    //                 } elseif (intval($flag['PurchaseRequestFlagQtyRest']) < intval($row_detail["PurchaseRequestDetailQty"])) {
    //                     $purchaseRequestStatus = 'Partial';
    //                 }

    //                 // Update status purchase request hanya sekali dengan status yang sudah ditentukan
    //                 $sqlpr = "UPDATE purchase_request SET
    //                         PurchaseRequestStatus = ?,
    //                         PurchaseRequestUserID = ?,
    //                         PurchaseRequestLastUpdated = NOW()
    //                         WHERE PurchaseRequestID = ?";
    //                 $qrypr = $this->db->query($sqlpr, [
    //                     $purchaseRequestStatus,
    //                     $userId,
    //                     $row_detail["PurchaseRequestDetailPurchaseRequestID"]
    //                 ]);
    //                 if (!$qrypr) {
    //                     $this->db->trans_rollback();
    //                     $this->sys_error_db("update purchase_request error", $this->db);
    //                     exit;
    //                 }
    //             }
    //         }

    //         // generate jurnal
    //         $this->GenerateJurnal($para['suratJalanID']);

    //         $this->db->trans_commit();

    //         $newUpdate = "SELECT * FROM suratjalan WHERE SuratJalanID = {$para['suratJalanID']} AND SuratJalanIsActive = 'Y'";
    //         $records = $this->db->query($newUpdate, [])->result_array();
    //         $result = array("records" => $records, "msg" => "success update surat jalan");
    //         $this->sys_ok($result);
    //     } catch (Exception $exc) {
    //         $message = $exc->getMessage();
    //         $this->sys_error($message);
    //     }
    // }

    public function GenerateJurnal($suratJalanID)
    {
        try {
            $para = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $this->db->trans_begin();

            $sqlData  = "SELECT SuratJalanID,
                            SuratJalanNumber,
                            SuratJalanReceivedDate,
                            SuratJalanReceivedUserID,
                            SuratJalanReceivedNote, 
                            SUM(StockItemPrice) AS StockItemPrice,
                            StockQty,
                            SUM(SuratJalanDetailQty) AS SuratJalanDetailQty,
                            SUM(SuratJalanDetailQtyReceived) AS SuratJalanDetailQtyReceived,
                            SUM(StockItemPrice * SuratJalanDetailQty) AS totalAmountQty,
                            SUM(StockItemPrice * SuratJalanDetailQtyReceived) AS totalAmountQtyReceive,
                            M_BranchS_RegionalID,
                            M_BranchID,
                            M_BranchCode,
                            M_BranchName,
                            M_BranchCompanyID,
                            M_BranchCompanyName,
                            CONCAT('Auto Jurnal Terima Barang Tanggal ', DATE_FORMAT(SuratJalanReceivedDate, '%d-%m-%Y')) xdescription,
                            CONCAT('Auto Jurnal Terima Barang Tanggal ', DATE_FORMAT(SuratJalanReceivedDate, '%d-%m-%Y'), ' Regional ',S_RegionalName) titleregional,
                            CONCAT('Auto Jurnal Terima Barang Tanggal ', DATE_FORMAT(SuratJalanReceivedDate, '%d-%m-%Y'), ' Cabang ',M_BranchName, ' ' ,M_BranchCode) titlebranch,
                            '' as detailjurnalreg,
                            '' as detailjurnalbran
                            FROM suratjalan
                            JOIN suratjalan_detail ON SuratJalanDetailSuratJalanID = SuratJalanID 
                                AND SuratJalanDetailIsActive = 'Y'
                            JOIN t_goods_transfer ON SuratJalanT_GoodsTransferID = T_GoodsTransferID 
                                AND T_GoodsTransferIsActive = 'Y'
                            JOIN warehouse ON SuratJalanReceivedWarehouseID = WarehouseID 
                                AND WarehouseIsActive = 'Y'
                            JOIN m_branch ON T_GoodsTransferToM_BranchCode = M_BranchCode 
                                AND M_BranchIsActive = 'Y'
                            JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID 
                                AND S_RegionalIsActive = 'Y'
                            JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID 
                                AND M_ItemIsActive = 'Y'
                            JOIN stock ON StockItemID = M_ItemID 
                            LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode 
                                AND M_BranchCompanyDetailIsActive = 'Y'
                            LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID 
                                AND M_BranchCompanyIsActive = 'Y'
                            WHERE SuratJalanIsActive = 'Y'
                            AND SuratJalanID = ?
                            GROUP BY SuratJalanID";
            $qryData = $this->db->query($sqlData, [$suratJalanID]);
            if ($qryData) {
                $data = $qryData->result_array()[0];
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db('select data jurnal error', $this->db);
                exit;
            }

            if ($data) {
                // print_r($data);
                // exit;
                $periodeID = 0;
                $branchID = $data["M_BranchID"];
                $branchCode = $data["M_BranchCode"];
                $branchCompanyID = $data["M_BranchCompanyID"];
                $date = date('Y-m-d');
                $description = $data["xdescription"];
                $regionalID = $data["M_BranchS_RegionalID"];
                $titleregional = $data["titleregional"];
                $titlebranch = $data["titlebranch"];
                $sjno = $data["SuratJalanNumber"];
                $qtyReceive = intval($data["SuratJalanDetailQtyReceived"]);
                $qty = intval($data["SuratJalanDetailQty"]);
                $totalAmountQtyReceive = intval($data["totalAmountQtyReceive"]);
                $totalAmountQty = intval($data["totalAmountQty"]);


                $qtyDifference = $qty - $qtyReceive;

                $sqlperiode = "SELECT periodeID FROM periode WHERE '{$date}' BETWEEN periodeStartDate AND periodeEndDate";
                $periodeID = $this->db->query($sqlperiode)->row()->periodeID;

                $sqltype = "SELECT JurnalTypeID FROM jurnal_type WHERE JurnalTypeIsActive = 'Y' AND JurnalTypeCode = 'AUTOSENDGOODR'";
                $typeID = $this->db->query($sqltype)->row()->JurnalTypeID;

                // cek apakah ada selisih
                if ($qtyDifference != 0) {

                    // ambil data map coa under investigasi
                    $sqlCoaInvestigasi = "SELECT coaID, coaDescription FROM coa
                    WHERE coaAccountNo = '1150700002' AND coaIsActive = 'Y'";
                    $qryCoaInvestigasi = $this->db->query($sqlCoaInvestigasi);
                    if (!$qryCoaInvestigasi) {
                        $this->sys_error("Mapping STOCK / UNDER INVESTIGASI tidak ditemukan", $this->db);
                        exit;
                    }
                    $underInvestigasiID = $qryCoaInvestigasi->row()->coaID;
                    $underInvestigasiDesc = $qryCoaInvestigasi->row()->coaDescription;

                    $sqlOffBran = "SELECT Map_RkCabang_Rk_TypeID,
                                Map_RkCabang_SRegionalID,
                                Map_RkCabang_BranchCode,
                                Map_RkCabang_CoaID,
                                Map_RkCabang_CoaAccountNo,
                                Map_RkCabang_CoaDescription
                                FROM map_rk_cabang
                                JOIN rk_type ON Map_RkCabang_Rk_TypeID = Rk_TypeID AND Rk_TypeIsActive ='Y'
                                AND  Rk_TypeCode = 'STOK'
                                LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode 
                                WHERE Map_RkCabang_IsActive = 'Y'
                                AND Map_RkCabang_SRegionalID = ?
                                AND (Map_RkCabang_BranchCode  = '' OR Map_RkCabang_BranchCode IS NULL)";
                    $qryOffBran = $this->db->query($sqlOffBran, [
                        $regionalID
                    ]);
                    if (!$qryOffBran) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("select data regional error", $this->db);
                        exit;
                    }
                    $dataBran = $qryOffBran->row();

                    // ambil data item sesuai surat jalan
                    $sqlItem = "SELECT M_ItemID,
                            M_ItemCode,
                            M_ItemDesc,
                            SuratJalanDetailQty,
                            SuratJalanDetailQtyReceived,
                            StockItemPrice,
                            MapNatSub_PersediaanCoaID as coaID,
                            MapNatSub_PersediaanCoaDescription as coaDescription
                        FROM suratjalan_detail
                        JOIN suratjalan ON SuratJalanDetailSuratJalanID = SuratJalanID
                            AND SuratJalanIsActive = 'Y'
                        JOIN stock ON StockItemID = SuratJalanDetailM_ItemID
                            AND SuratJalanDetailIsActive = 'Y'
                        JOIN warehouse ON SuratJalanReceivedWarehouseID = WarehouseID
                            AND WarehouseIsActive = 'Y'
                        JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID
                            AND M_ItemIsActive = 'Y'
                        JOIN map_nat_subgroup ON M_ItemNat_SubGroupID = MapNatSub_NatSubGroupID
                            AND MapNatSub_IsActive = 'Y'
                        WHERE SuratJalanDetailIsActive = 'Y'
                            AND SuratJalanDetailSuratJalanID = ? 
                            AND WarehouseS_RegionalID = ?";
                    $qryItem = $this->db->query($sqlItem, [$suratJalanID, $regionalID]);
                    if (!$qryItem) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("select item error", $this->db);
                        exit;
                    }
                    $rowsItem = $qryItem->result_array();

                    // Inisialisasi variabel untuk menyimpan total selisih
                    $totalAmountStockD = 0;
                    $totalDiffAmountD = 0;

                    // Array untuk menyimpan jurnal
                    $detailjurnaldiff = [];

                    // Kelompokkan item berdasarkan coaID untuk persediaan
                    $coaGroups = [];
                    foreach ($rowsItem as $item) {
                        $coaID = $item["coaID"];
                        if (!isset($coaGroups[$coaID])) {
                            $coaGroups[$coaID] = [
                                'coaID' => $coaID,
                                'coaDescription' => $item["coaDescription"],
                                'totalAmount' => 0
                            ];
                        }

                        // Hitung total amount dari item yang diterima
                        $itemQtyReceived = $item["SuratJalanDetailQtyReceived"];
                        $itemPrice = $item["StockItemPrice"];
                        $itemReceivedAmount = $itemQtyReceived * $itemPrice;

                        $coaGroups[$coaID]['totalAmount'] += $itemReceivedAmount;
                    }

                    // Buat jurnal untuk setiap CoA persediaan yang berbeda
                    foreach ($coaGroups as $coaGroup) {
                        $detailjurnaldiff[] = [
                            'coaID' => $coaGroup['coaID'],
                            'xdescription' => $coaGroup['coaDescription'],
                            'debit' => $coaGroup['totalAmount'],
                            'credit' => 0,
                            'sjnoValue' => $sjno
                        ];

                        // Tambahkan ke total untuk persediaan
                        $totalAmountStockD += $coaGroup['totalAmount'];
                    }

                    // Jurnal untuk Rek. Cabang (credit)
                    $detailjurnaldiff[] = [
                        'coaID' => $dataBran->Map_RkCabang_CoaID,
                        'xdescription' => $dataBran->Map_RkCabang_CoaDescription,
                        'debit' => 0,
                        'credit' => 0,
                        'sjnoValue' => $sjno
                    ];

                    // Index untuk Rek. Cabang dalam array detailjurnaldiff
                    $rekCabangIndex = count($detailjurnaldiff) - 1;

                    // Iterasi untuk setiap item untuk menghitung selisih
                    foreach ($rowsItem as $key => $value) {
                        $itemCode = $value["M_ItemCode"];
                        $itemDesc = $value["M_ItemDesc"];
                        $itemQty = $value["SuratJalanDetailQty"];
                        $itemQtyReceived = $value["SuratJalanDetailQtyReceived"];
                        $itemPrice = $value["StockItemPrice"];

                        // Hitung selisih qty
                        $qtyDifference = $itemQty - $itemQtyReceived;

                        // Hitung nilai selisih berdasarkan harga
                        $itemDiffAmount = $qtyDifference * $itemPrice;

                        // Tambahkan ke total selisih
                        $totalDiffAmountD += $itemDiffAmount;

                        // Jika ada selisih, tambahkan ke jurnal under investigasi
                        if ($qtyDifference != 0) {
                            $detailjurnaldiff[] = [
                                'coaID' => $underInvestigasiID,
                                'xdescription' => $underInvestigasiDesc,
                                'debit' => $itemDiffAmount,
                                'credit' => 0,
                                'sjnoValue' => "Item Code " . $itemCode . " - " . $itemDesc
                            ];
                        }
                    }

                    // Update total credit pada jurnal Rek. Cabang
                    $detailjurnaldiff[$rekCabangIndex]['credit'] = $totalAmountStockD + $totalDiffAmountD;

                    $this->saveJurnalDiff(
                        $branchID,
                        $date,
                        $description,
                        $periodeID,
                        $regionalID,
                        $titlebranch,
                        $typeID,
                        $detailjurnaldiff,
                        $branchCompanyID
                    );
                } else {
                    // penerima kantor regional
                    $sqlCoaReg = "SELECT coaID, coaDescription FROM coa
                    WHERE coaAccountNo = '1150700001' AND coaIsActive = 'Y'";
                    $qryCoaReg = $this->db->query($sqlCoaReg);
                    if (!$qryCoaReg) {
                        $this->sys_error("Mapping COA tidak ditemukan", $this->db);
                        exit;
                    }
                    $stockDescID = $qryCoaReg->row()->coaID;
                    $stockDesc = $qryCoaReg->row()->coaDescription;

                    $sqlOffReg = "SELECT Map_RkCabang_Rk_TypeID,
                                Map_RkCabang_SRegionalID,
                                Map_RkCabang_BranchCode,
                                Map_RkCabang_CoaID,
                                Map_RkCabang_CoaAccountNo,
                                Map_RkCabang_CoaDescription
                                FROM map_rk_cabang
                                JOIN rk_type ON Map_RkCabang_Rk_TypeID = Rk_TypeID AND Rk_TypeIsActive ='Y'
                                AND Rk_TypeCode = 'STOK'
                                JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode 
                                WHERE Map_RkCabang_IsActive = 'Y'
                                AND Map_RkCabang_SRegionalID = ?
                                AND M_BranchCode = ?";
                    $qryOffReg = $this->db->query($sqlOffReg, [
                        $regionalID,
                        $branchCode
                    ]);
                    if (!$qryOffReg) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("select data regional error", $this->db);
                        exit;
                    }
                    $dataReg = $qryOffReg->row();

                    $detailjurnalreg = [
                        [
                            'coaID' => $dataReg->Map_RkCabang_CoaID,
                            'xdescription' => $dataReg->Map_RkCabang_CoaDescription,
                            'debit' => $totalAmountQtyReceive,
                            'credit' => 0
                        ],
                        [
                            'coaID' => $stockDescID,
                            'xdescription' => $stockDesc,
                            'debit' => 0,
                            'credit' => $totalAmountQty
                        ]
                    ];

                    // print_r($detailjurnalreg);
                    // exit;

                    $this->saveJurnalReg(
                        $date,
                        $description,
                        $periodeID,
                        $regionalID,
                        $titleregional,
                        $typeID,
                        $detailjurnalreg,
                        $sjno,
                        $branchCompanyID
                    );
                    // end penerima kantor regional

                    // penerima kantor cabang
                    $sqlCoaBran = "SELECT 
                            MapNatSub_PersediaanCoaID as coaID,
                            MapNatSub_PersediaanCoaDescription as coaDescription
                        FROM suratjalan_detail
                        JOIN suratjalan ON SuratJalanDetailSuratJalanID = SuratJalanID
                            AND SuratJalanIsActive = 'Y'
                        JOIN stock ON StockItemID = SuratJalanDetailM_ItemID
                            AND SuratJalanDetailIsActive = 'Y'
                        JOIN warehouse ON SuratJalanReceivedWarehouseID = WarehouseID
                            AND WarehouseIsActive = 'Y'
                        JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID
                            AND M_ItemIsActive = 'Y'
                        JOIN map_nat_subgroup ON M_ItemNat_SubGroupID = MapNatSub_NatSubGroupID
                            AND MapNatSub_IsActive = 'Y'
                        WHERE SuratJalanDetailIsActive = 'Y'
                            AND SuratJalanDetailSuratJalanID = ? 
                            AND WarehouseS_RegionalID = ?";
                    $qryCoaBran = $this->db->query($sqlCoaBran, [
                        $suratJalanID,
                        $regionalID
                    ]);
                    if (!$qryCoaBran) {
                        $this->sys_error("Mapping PERSEDIAAN tidak ditemukan", $this->db);
                        exit;
                    }
                    $persediaanID = $qryCoaBran->row()->coaID;
                    $persediaanDesc = $qryCoaBran->row()->coaDescription;

                    $sqlOffBran = "SELECT Map_RkCabang_Rk_TypeID,
                                Map_RkCabang_SRegionalID,
                                Map_RkCabang_BranchCode,
                                Map_RkCabang_CoaID,
                                Map_RkCabang_CoaAccountNo,
                                Map_RkCabang_CoaDescription
                                FROM map_rk_cabang
                                JOIN rk_type ON Map_RkCabang_Rk_TypeID = Rk_TypeID AND Rk_TypeIsActive ='Y'
                                AND  Rk_TypeCode = 'STOK'
                                LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode 
                                WHERE Map_RkCabang_IsActive = 'Y'
                                AND Map_RkCabang_SRegionalID = ?
                                AND (Map_RkCabang_BranchCode  = '' OR Map_RkCabang_BranchCode IS NULL)";
                    $qryOffBran = $this->db->query($sqlOffBran, [
                        $regionalID
                    ]);
                    if (!$qryOffBran) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("select data regional error", $this->db);
                        exit;
                    }
                    $dataBran = $qryOffBran->row();

                    $detailjurnalbran = [
                        [
                            'coaID' => $persediaanID,
                            'xdescription' => $persediaanDesc,
                            'debit' => $totalAmountQty,
                            'credit' => 0
                        ],
                        [
                            'coaID' => $dataBran->Map_RkCabang_CoaID,
                            'xdescription' => $dataBran->Map_RkCabang_CoaDescription,
                            'debit' => 0,
                            'credit' => $totalAmountQty
                        ]
                    ];

                    $this->saveJurnalBran(
                        $branchID,
                        $date,
                        $description,
                        $periodeID,
                        $regionalID,
                        $titlebranch,
                        $typeID,
                        $detailjurnalbran,
                        $sjno,
                        $branchCompanyID
                    );
                    // end penerima kantor cabang
                }
            }

            $this->db->trans_commit();
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function saveJurnalReg(
        $date,
        $description,
        $periodeID,
        $regionalID,
        $titleregional,
        $typeID,
        $detailjurnalreg,
        $sjno,
        $branchCompanyID
    ) {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db->trans_begin();
            $userid = $this->sys_user['M_UserID'];

            // $sql_branch = "SELECT 
            //         M_BranchID,
            //         M_BranchCode,
            //         M_BranchName
            //         FROM m_branch
            //         WHERE M_BranchIsActive = 'Y'
            //         AND M_BranchID = ?";
            // $qry_branch = $this->db->query($sql_branch, array($branchID));
            // if ($qry_branch) {
            //     $branchcodex = $qry_branch->row()->M_BranchCode;
            // } else {
            //     $this->db->trans_rollback();
            //     $this->sys_error_db("select branch error", $this->db);
            //     exit;
            // }

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalM_BranchCode,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchCompanyID,
                $regionalID,
                '',
                $periodeID,
                $titleregional,
                $description,
                $date,
                $typeID,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();

            foreach ($detailjurnalreg as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaID"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon 
                (jurnalAddOnJurnalID, 
                jurnalAddOnJurnalTxID, 
                jurnalAddOnCode, 
                jurnalAddOnValue, 
                jurnalAddOnCreated, 
                jurnalAddOnCreatedUserID, 
                jurnalAddOnLastUpdatedUserID, 
                jurnalAddOnLastUpdated) 
                VALUES
                (?,	
                ?,	
                'SENDGOODRDST',	
                ?,	
                now(),	
                ?,	
                ?,
                now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $sjno,
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }
            }


            $this->db->trans_commit();
            //  $result = array("total" => 1);
            //  $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function saveJurnalBran(
        $branchID,
        $date,
        $description,
        $periodeID,
        $regionalID,
        $titlebranch,
        $typeID,
        $detailjurnalbran,
        $sjno,
        $branchCompanyID
    ) {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db->trans_begin();
            $userid = $this->sys_user['M_UserID'];

            $sql_branch = "SELECT 
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM m_branch
                    WHERE M_BranchIsActive = 'Y'
                    AND M_BranchID = ?";
            $qry_branch = $this->db->query($sql_branch, array($branchID));
            if ($qry_branch) {
                $branchcodex = $qry_branch->row()->M_BranchCode;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch error", $this->db);
                exit;
            }

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalM_BranchCode,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchCompanyID,
                $regionalID,
                $branchcodex,
                $periodeID,
                $titlebranch,
                $description,
                $date,
                $typeID,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();

            foreach ($detailjurnalbran as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaID"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon 
                (jurnalAddOnJurnalID, 
                jurnalAddOnJurnalTxID, 
                jurnalAddOnCode, 
                jurnalAddOnValue, 
                jurnalAddOnCreated, 
                jurnalAddOnCreatedUserID, 
                jurnalAddOnLastUpdatedUserID, 
                jurnalAddOnLastUpdated) 
                VALUES
                (?,	
                ?,	
                'SENDGOODRDST',	
                ?,	
                now(),	
                ?,	
                ?,
                now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $sjno,
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }
            }


            $this->db->trans_commit();
            //  $result = array("total" => 1);
            //  $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function saveJurnalDiff(
        $branchID,
        $date,
        $description,
        $periodeID,
        $regionalID,
        $titlebranch,
        $typeID,
        $detailjurnaldiff,
        $branchCompanyID
    ) {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db->trans_begin();
            $userid = $this->sys_user['M_UserID'];

            $sql_branch = "SELECT 
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM m_branch
                    WHERE M_BranchIsActive = 'Y'
                    AND M_BranchID = ?";
            $qry_branch = $this->db->query($sql_branch, array($branchID));
            if ($qry_branch) {
                $branchcodex = $qry_branch->row()->M_BranchCode;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch error", $this->db);
                exit;
            }

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalM_BranchCode,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchCompanyID,
                $regionalID,
                $branchcodex,
                $periodeID,
                $titlebranch,
                $description,
                $date,
                $typeID,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();

            foreach ($detailjurnaldiff as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaID"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon 
                (jurnalAddOnJurnalID, 
                jurnalAddOnJurnalTxID, 
                jurnalAddOnCode, 
                jurnalAddOnValue, 
                jurnalAddOnCreated, 
                jurnalAddOnCreatedUserID, 
                jurnalAddOnLastUpdatedUserID, 
                jurnalAddOnLastUpdated) 
                VALUES
                (?,	
                ?,	
                'SENDGOODRDST',	
                ?,	
                now(),	
                ?,	
                ?,
                now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $value["sjnoValue"],
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }
            }


            $this->db->trans_commit();
            //  $result = array("total" => 1);
            //  $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function GetTFDataDetail()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $para = $this->sys_input;
            $sjID = $para['SuratJalanID'];
            $currpage = $para['currpagedetail'];

            $page = 0;
            $limit = 5;
            if ($currpage > 0) {
                $page = ($currpage - 1) * $limit;
            }

            $sqltot = "SELECT COUNT(*) as total
                FROM suratjalan_detail
                JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID
                    AND M_ItemIsActive = 'Y'
                LEFT JOIN itemunit ON ItemUnitID = SuratJalanDetailItemUnitID
                    AND ItemUnitIsActive = 'Y'
                WHERE SuratJalanDetailIsActive = 'Y'
                    AND SuratJalanDetailSuratJalanID = ?";
            $qrytot = $this->db->query($sqltot, [$sjID]);

            $totalcount = 0;
            $totalpage = 0;
            if ($qrytot) {
                $totalcount = $qrytot->result_array()[0]['total'];
                $totalpage = ceil($totalcount / $limit);
            } else {
                $this->sys_error_db("count surat jalan error", $this->db);
                exit;
            }

            $sqlSJD = "SELECT 
                    SuratJalanDetailID,
                    SuratJalanDetailM_ItemID,
                    SuratJalanDetailQty,
                    SuratJalanDetailQtyReceived,
                    SuratJalanDetailItemUnitID,
                    M_ItemCode,
                    M_ItemDesc,
                    ItemUnitCode,
                    ItemUnitName
                FROM suratjalan_detail
                JOIN m_item ON M_ItemID = SuratJalanDetailM_ItemID
                    AND M_ItemIsActive = 'Y'
                LEFT JOIN itemunit ON ItemUnitID = SuratJalanDetailItemUnitID
                    AND ItemUnitIsActive = 'Y'
                WHERE SuratJalanDetailIsActive = 'Y'
                    AND SuratJalanDetailSuratJalanID = ?
                LIMIT ? OFFSET ?";
            $qrySJD = $this->db->query($sqlSJD, [$sjID, $limit, $page]);
            if (!$qrySJD) {
                $this->sys_error_db("error get detail surat jaalan");
                exit;
            }
            $rows = $qrySJD->result_array();

            $result = array(
                "totalPage" => $totalpage,
                "total" => $totalcount,
                "records" => $rows,
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function ListingSuratJalan()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $para = $this->sys_input;
            $stardate = $para['startdate'];
            $enddate = $para['enddate'];
            $branchcode = $para['branchcode'];
            $status = $para['status'];
            $keyword = $para['search'];
            $currpage = $para['currpage'];

            $page = 0;
            $limit = 10;
            if ($currpage > 0) {
                $page = ($currpage - 1) * $limit;
            }

            $keyw = "%";
            if ($keyword != "") {
                $keyw = $keyword . "%";
            }

            $sqtot = "SELECT COUNT(*) as total
                FROM suratjalan
                JOIN t_goods_transfer ON T_GoodsTransferID = SuratJalanT_GoodsTransferID
                    AND T_GoodsTransferIsActive = 'Y'
                JOIN m_branch ON M_BranchCode = T_GoodsTransferToM_BranchCode
                    AND M_BranchIsActive = 'Y' 
                LEFT JOIN expeditionstaff ON ExpeditionStaffID = SuratJalanEkspedisiStaffID
                    AND ExpeditionStaffIsActive = 'Y'
                LEFT JOIN expedition ON ExpeditionID = SuratJalanEkspedisiID
                    AND ExpeditionIsActive = 'Y'
                LEFT JOIN m_user ON M_UserID = SuratJalanReceivedUserID
                    AND M_UserIsActive = 'Y'
                LEFT JOIN m_staff ON M_UserM_StaffID = M_StaffID
                    AND M_StaffIsActive = 'Y'
                WHERE SuratJalanIsActive = 'Y' 
                    AND SuratJalanDate >= DATE(?) 
                    AND SuratJalanDate <= DATE(?) 
                    AND (? = 'ALL' OR T_GoodsTransferToM_BranchCode = ? )
                    AND (? = 'All' OR SuratJalanStatus = ? )
                    AND SuratJalanNumber LIKE ?";
            $qryto = $this->db->query($sqtot, [
                $stardate,
                $enddate,
                $branchcode,
                $branchcode,
                $status,
                $status,
                $keyw
            ]);

            $totalcount = 0;
            $totalpage = 0;
            if ($qryto) {
                $totalcount = $qryto->result_array()[0]['total'];
                $totalpage = ceil($totalcount / $limit);
            } else {
                $this->sys_error_db("count surat jalan error", $this->db);
                exit;
            }

            $sqlSJ = "SELECT 
                    SuratJalanID,
                    SuratJalanNumber,
                    SuratJalanDate,
                    SuratJalanNote,
                    M_BranchCode,
                    M_BranchName,
                    SuratJalanEkspedisiID,
                    ExpeditionID,
                    ExpeditionName,
                    ExpeditionIsInternal,
                    SuratJalanEkspedisiStaffID,
                    SuratJalanEkspedisiStaffContact,
                    ExpeditionStaffID,
                    ExpeditionStaffName,
                    ExpeditionStaffMobile,
                    SuratJalanStatus,
                    SuratJalanT_GoodsTransferID,
                    DATE_FORMAT(IF(SuratJalanReceivedDate = '0000-00-00 00:00:00' OR SuratJalanReceivedDate IS NULL, NULL, SuratJalanReceivedDate), '%d-%m-%Y') as SuratJalanReceivedDate,
                    SuratJalanReceivedNote,
                    SuratJalanReceivedWarehouseID,
                    SuratJalanReceivedConfirmed,
                    SuratJalanReceivedConfirmedDate,
                    SuratJalanReceivedConfirmedUserID,
                    M_StaffName
                FROM suratjalan
                JOIN t_goods_transfer ON T_GoodsTransferID = SuratJalanT_GoodsTransferID
                    AND T_GoodsTransferIsActive = 'Y'
                JOIN m_branch ON M_BranchCode = T_GoodsTransferToM_BranchCode
                    AND M_BranchIsActive = 'Y'
                LEFT JOIN expeditionstaff ON ExpeditionStaffID = SuratJalanEkspedisiStaffID
                    AND ExpeditionStaffIsActive = 'Y'
                LEFT JOIN expedition ON ExpeditionID = SuratJalanEkspedisiID
                    AND ExpeditionIsActive = 'Y'
                LEFT JOIN m_user ON M_UserID = SuratJalanReceivedUserID
                    AND M_UserIsActive = 'Y'
                LEFT JOIN m_staff ON M_UserM_StaffID = M_StaffID
                    AND M_StaffIsActive = 'Y'
                WHERE SuratJalanIsActive = 'Y'
                    AND SuratJalanDate >= DATE(?) 
                    AND SuratJalanDate <= DATE(?) 
                    AND (? = 'ALL' OR T_GoodsTransferToM_BranchCode = ? )
                    AND (? = 'ALL' OR SuratJalanStatus = ? )
                    AND SuratJalanNumber LIKE ?
                    ORDER BY SuratJalanID DESC
                LIMIT ? OFFSET ?";
            $qrySJ = $this->db->query($sqlSJ, [
                $stardate,
                $enddate,
                $branchcode,
                $branchcode,
                $status,
                $status,
                $keyw,
                $limit,
                $page
            ]);
            if (!$qrySJ) {
                $this->sys_error_db("error get listing data surat jalan", $this->db);
                exit;
            }
            $list = $qrySJ->result_array();

            $result = array(
                "totalPage" => $totalpage,
                "total" => $totalcount,
                "records" => $list
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function ListingBranch()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $regID = $prm["S_RegionalID"];

            $sql = "SELECT M_BranchID, M_BranchCode, M_BranchName
                    FROM m_branch
                    WHERE M_BranchIsActive = 'Y'
                    AND M_BranchS_RegionalID = ?";
            $qry = $this->db->query($sql, [$regID]);
            if (!$qry) {
                $this->sys_error_db("Failed to get Branches from RegionalID: {$regID}", $this->db);
                exit;
            }
            $rst = $qry->result_array();

            $this->sys_ok(["records" => $rst]);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function getWarehouse()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $payload = $this->sys_input;
            $user = $this->sys_user;
            $userId = $this->sys_user["M_UserID"];
            $regionalId =  $this->sys_user["S_RegionalID"];
            $sqlWhere = "";

            if ($user['M_UserLocationFlag'] == "R") {
                $sqlWhere = "AND WarehouseType = 'R'";
            }
            if ($user['M_UserLocationFlag'] == "RB" || $user['M_UserLocationFlag'] == "B") {
                $sqlWhere = "AND WarehouseType = 'B' AND WarehouseM_BranchID = {$user['M_BranchID']}";
            }

            $sql = "SELECT 
                    WarehouseID,
                    WarehouseCode,
                    CASE
                        WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) 
                        WHEN WarehouseType = 'R' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) 
                    ELSE ''
                    END WarehouseName,
                    WarehouseType,
                    WarehouseIsDefault,
                    WarehouseS_RegionalID,
                    WarehouseM_BranchID,
                    S_RegionalID,
                    S_RegionalName
                    FROM warehouse
                    JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID AND M_BranchIsActive = 'Y'
                    where WarehouseS_RegionalID = ?
                    AND WarehouseIsActive = 'Y'
                    AND WarehouseIsTransit = 'N'
                    $sqlWhere
                    ORDER BY WarehouseName ASC ";
            $qry = $this->db->query($sql, [$regionalId]);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("select warehouse", $this->db);;
                exit;
            }

            $rows = $qry->result_array();

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

            $this->sys_ok($rows);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function insertUserActivty($id, $type, $userID, $desc = '', $data = '')
    {
        // Query untuk menyisipkan log ke dalam tabel purchase_order_log
        $sql = "INSERT INTO user_activity (
                    UserActivityCode,
                    UserActivityStatus,
                    UserActivityDescription,
                    UserActivityRefID,
                    UserActivityData,
                    UserActivityUserID,
                    UserActivityCreated
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, NOW()
                )";

        // Eksekusi query dengan parameter yang diberikan
        $exec = $this->db->query($sql, [
            'RSJ',
            $type,
            $desc,
            $id,
            $data,
            $userID

        ]);

        // Jika query gagal, lempar error
        if (!$exec) {
            $this->sys_error_db("Error inserting user activity", $this->db);
            $this->db->trans_rollback();
            exit;
        }
    }
}
