<?php

class SuratJalan extends MY_Controller {

    var $db;
    public function index() {
        echo "Surat Jalan API";
    }

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

    ### QUERY ###  

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

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

            $tftype = "NP";
            if ($para['type'] == 'Persediaan') {
                $tftype = "P";
            }

            $sql = "SELECT 
                T_GoodsTransferID,
                T_GoodsTransferNum,
                T_GoodsTransferType,
                T_GoodsTransferDate
            FROM t_goods_transfer 
            WHERE T_GoodsTransferIsActive = 'Y'
                AND T_GoodsTransferStatus = 'Approved'
                AND T_GoodsTransferNum LIKE ?
                AND T_GoodsTransferType = ? 
                AND NOT EXISTS (
                    SELECT 1 
                    FROM suratjalan
                    WHERE SuratJalanIsActive = 'Y'
                        AND SuratJalanT_GoodsTransferID = T_GoodsTransferID 
                        AND SuratJalanT_GoodsTransferNum = T_GoodsTransferNum
                )
            GROUP BY T_GoodsTransferID";
            $que = $this->db->query($sql, [$TFnum, $tftype]);
            if (!$que) {
                $this->sys_error_db("[Error] get list TF request");
                exit;
            }
            $data = $que->result_array();
            $result = array(
                "records" => $data,
                "total" => sizeof($data)
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $para = $this->sys_input;

            $sql = "SELECT 
                T_GoodsTransferDetailID AS TGDetailID,
                T_GoodsTransferDetailM_ItemID AS M_ItemID,
                M_ItemDesc,
                T_GoodsTransferDetailItemUnitID AS ItemUnitID,
                ItemUnitName,
                T_GoodsTransferDetailQtyTF AS Quantity,
                T_GoodsTransferDetailT_PurchaseRequestFlagID AS PRFlagID,
                T_GoodsTransferDetailItemBatchNo,
                T_GoodsTransferDetailItemBarNote
            FROM t_goods_transfer_detail 
            JOIN m_item ON M_ItemID = T_GoodsTransferDetailM_ItemID 
                AND M_ItemIsActive = 'Y'
            JOIN itemunit ON ItemUnitID = T_GoodsTransferDetailItemUnitID 
                AND ItemUnitIsActive = 'Y'
            WHERE T_GoodsTransferDetailIsActive = 'Y'
                AND T_GoodsTransferDetailIDT_GoodsTransferID = ?";
            $que = $this->db->query($sql, [$para['TGoodID']]);
            if (!$que) {
                $this->sys_error_db("[Error] get data transfer request detail");
                exit;
            }

            $data = $que->result_array();
            $result = array(
                "records" => $data,
                "total" => sizeof($data)
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    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 LookupSuratJalanDetail() {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

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

            $sqlSJ = "SELECT 
                SuratJalanID,
                SuratJalanNumber,
                SuratJalanDate,
                SuratJalanNote,
                SuratJalanStatus,
                ExpeditionName,
                ExpeditionIsInternal,
                ExpeditionID,
                ExpeditionName,
                ExpeditionStaffID,
                ExpeditionStaffName,
                ExpeditionStaffMobile,
                T_GoodsTransferID,
                T_GoodsTransferNum,
                T_GoodsTransferDate,
                T_GoodsTransferType
            FROM suratjalan
            JOIN t_goods_transfer ON T_GoodsTransferID = SuratJalanT_GoodsTransferID
                AND T_GoodsTransferIsActive = 'Y'
            JOIN expedition ON ExpeditionID = SuratJalanEkspedisiID
                AND ExpeditionIsActive = 'Y'
            JOIN expeditionstaff ON ExpeditionStaffID = SuratJalanEkspedisiStaffID
                AND ExpeditionStaffIsActive = 'Y'
            WHERE SuratJalanIsActive = 'Y'
                AND SuratJalanID = ?";
            $qrySJ = $this->db->query($sqlSJ, [$sjID]);
            if (!$qrySJ) {
                $this->sys_error_db("error get surat jalan");
                exit;
            }
            $suratj = $qrySJ->result_array()[0];

            $sjdtot = "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($sjdtot, [$sjID]);
            if (!$qrytot) {
                $this->sys_error_db("error get detail surat jaalan");
                exit;
            }
            $detailtotal = $qrytot->result_array()[0]['total'];

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

            $sqlSJD = "SELECT 
                    SuratJalanDetailID,
                    SuratJalanDetailPurchaseRequestFlagID AS PRFlagID,
                    SuratJalanDetailT_GoodsTransferDetailID AS TGDetailID,
                    SuratJalanDetailM_ItemID AS M_ItemID,
                    SuratJalanDetailQty AS Quantity,
                    SuratJalanDetailItemUnitID AS ItemUnitID,
                    M_ItemCode,
                    M_ItemDesc,
                    ItemUnitCode,
                    ItemUnitName,
                    PurchaseRequestFlagS_RegionalID,
                    M_BranchID
                FROM suratjalan_detail
                JOIN purchase_request_flag ON SuratJalanDetailPurchaseRequestFlagID = PurchaseRequestFlagID
                    AND PurchaseRequestFlagIsActive = 'Y'
                JOIN m_branch ON M_BranchCode = PurchaseRequestFlagM_BranchCode
                    AND M_BranchIsActive = 'Y'
                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, $pg]);
            if (!$qrySJD) {
                $this->sys_error_db("error get detail surat jaalan");
                exit;
            }
            $suratj['detail'] = $qrySJD->result_array();
            $suratj['detailtotal'] = $detailtotal;

            $result = array(
                "records" => $suratj,
            );

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

    public function LookupListSuratJalan() {
        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' 
                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
            ]);
            if (!$qryto) {
                $this->sys_error_db("error get listing data surat jalan");
                exit;
            }
            $total = $qryto->result_array()[0]['total'];

            $sqlSJ = "SELECT 
                    SuratJalanID,
                    SuratJalanNumber,
                    SuratJalanDate,
                    M_BranchCode,
                    M_BranchName,
                    SuratJalanEkspedisiID,
                    SuratJalanEkspedisiStaffID,
                    ExpeditionStaffName,
                    SuratJalanStatus,
                    SuratJalanT_GoodsTransferID
                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'
                WHERE SuratJalanIsActive = 'Y'
                    AND SuratJalanDate >= DATE(?) 
                    AND SuratJalanDate <= DATE(?) 
                    AND (? = 'ALL' OR T_GoodsTransferToM_BranchCode = ? )
                    AND (? = 'ALL' OR SuratJalanStatus = ? )
                    AND SuratJalanNumber LIKE ?
                ORDER BY SuratJalanDate 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");
                exit;
            }
            $list = $qrySJ->result_array();

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

    public function LookupListBranch() {
        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);
        }
    }

    ### MUTATIONS ###  

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

            $data = $this->sys_input;
            $detail = $data['detail'];
            $user = $this->sys_user;

            $this->db->trans_begin();
            
            ## GENERATE SURAT JALAN NUMBER ##
            // $sqlnum = "SELECT `fn_numbering`('SJ') as SJNumber";
            // $qrynum = $this->db->query($sqlnum, []);
            // $SJNumber = $qrynum->row()->SJNumber;

            $areaid = $user['M_BranchID'];
            $areatype = 'B';
            if ($user['loginLevel'] == 'regional') {
                $areaid = $user['S_RegionalID'];
                $areatype = 'R';
            }

            $sqlusrdivisi = "SELECT M_UserDivisionDivisionID FROM m_userdivision 
                WHERE M_UserDivisionM_UserID = ? AND M_UserDivisionIsActive = 'Y'";
            $queusrdivisi = $this->db->query($sqlusrdivisi, [$user['M_UserID']]);
            if (!$queusrdivisi) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get user divisi", $this->db);
                exit;
            }
            $userDivID = $queusrdivisi->row_array()['M_UserDivisionDivisionID'];

            $sqlnum = "SELECT `fn_penomoran`(?, ?, ?, ?, ?, ?) AS numpd;";
            $quenum = $this->db->query($sqlnum, ['SJ', $userDivID, $areatype, $areaid, 'SM', 'Y']);
            if (!$quenum) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] generate number doc", $this->db);
                exit;
            }
            $SJNumber = $quenum->row_array()['numpd'];

            ## INSERT INTO TABLE SURATJALAN ##
            $sqlSJ = "INSERT INTO suratjalan (
                SuratJalanNumber,
                SuratJalanDate,
                SuratJalanNote,
                SuratJalanT_GoodsTransferID,
                SuratJalanT_GoodsTransferNum,
                SuratJalanEkspedisiID,
                SuratJalanEkspedisiStaffID,
                SuratJalanEkspedisiStaffContact,
                SuratJalanStatus,
                SuratJalanCreated,
                SuratJalanUserID
            ) VALUES (?,?,?,?,?,?,?,?,?,NOW(),?)";
            $queSJ = $this->db->query($sqlSJ, [
                $SJNumber, $data['SJdate'], $data['SJnote'], $data['TGoodID'], 
                $data['TGoodNum'], $data['EkspedisiID'], $data['EkspedisiStaffID'], 
                $data['EkspedisiStaffHP'], $data['SJstatus'], $user['M_UserID']
            ]);
            if (!$queSJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] insert into table surat jalan");
                exit;
            }
            $SJID = $this->db->insert_id();

            ## INSERT INTO TABLE SURATJALAN_DETAIL ##
            foreach ($detail as $key => $obj) {
                $sqlSJD = "INSERT INTO suratjalan_detail (
                    SuratJalanDetailSuratJalanID,
                    SuratJalanDetailPurchaseRequestFlagID,
                    SuratJalanDetailT_GoodsTransferDetailID,
                    SuratJalanDetailM_ItemID,
                    SuratJalanDetailQty,
                    SuratJalanDetailItemUnitID,
                    SuratJalanDetailCreated,
                    SuratJalanDetailUserID
                ) VALUES (?,?,?,?,?,?,NOW(),?)";
                $queSJD = $this->db->query($sqlSJD, [
                    $SJID, $obj['PRFlagID'], $obj['TGDetailID'], 
                    $obj['ItemID'], $obj['Qty'], $obj['ItemUnitID'], $user['M_UserID']
                ]);
                if (!$queSJD) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] insert into table suratjalan_detail");
                    exit;
                }
            }

            ## GET LAST INSERTED DATA ##
            $sqlgetSJ = "SELECT * FROM suratjalan WHERE SuratJalanID = ? AND SuratJalanIsActive = 'Y'";
            $quegetSJ = $this->db->query($sqlgetSJ, [$SJID]);
            if (!$quegetSJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get last inserted data from table suratjalan");
                exit;
            }
            $lastSJ = $quegetSJ->row_array();

            $sqlgetSJD = "SELECT * FROM suratjalan_detail WHERE SuratJalanDetailSuratJalanID = ? AND SuratJalanDetailIsActive = 'Y'";
            $quegetSJD = $this->db->query($sqlgetSJD, [$SJID]);
            if (!$quegetSJD) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get last inserted data from table suratjalan_detail");
                exit;
            }
            $lastSJD = $quegetSJD->result_array();
            $lastSJ['detail'] = $lastSJD;

            ## UPDATE STOCK DAN KALKULASI STOCK ##
            if (strtolower($data['SJstatus']) === 'process' && strtolower($data['TFtype']) === 'persediaan') {
                $this->confirmSuratJalan($lastSJ, $lastSJD, $user);
                $this->generateJurnal($lastSJ, $lastSJD, $data['TFtype'], $user);
            }

            if (strtolower($data['SJstatus']) === 'process' && strtolower($data['TFtype']) === 'non persediaan') {
                $this->confirmSuratJalanNP($lastSJ, $lastSJD, $user);
                $this->generateJurnal($lastSJ, $lastSJD, $data['TFtype'], $user);
            }

            ## INSERT INTO LOG ACTIVITY ##
            $msg = "Surat Jalan nomor: {$lastSJ['SuratJalanNumber']}, Tanggal: {$lastSJ['SuratJalanDate']}";
            $this->insertUserActivty($SJID, "CREATE", $user['M_UserID'], $msg, json_encode($lastSJ));

            $this->db->trans_commit();

            $result = array(
                "total" => 1,
                "msg" => $msg,
                "records" => $lastSJ
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $data = $this->sys_input;
            $detail = $data['detail'];
            $user = $this->sys_user;

            $this->db->trans_begin();

            $sqlSJ = "UPDATE suratjalan SET 
                SuratJalanDate = ?,
                SuratJalanNote = ?,
                SuratJalanT_GoodsTransferID = ?,
                SuratJalanT_GoodsTransferNum = ?,
                SuratJalanEkspedisiID = ?,
                SuratJalanEkspedisiStaffID = ?,
                SuratJalanEkspedisiStaffContact = ?,
                SuratJalanStatus = ?,
                SuratJalanLastUpdated = NOW()
            WHERE SuratJalanID = ?";
            $queSJ = $this->db->query($sqlSJ, [
                $data['SJdate'], $data['SJnote'], $data['TGoodID'], 
                $data['TGoodNum'], $data['EkspedisiID'], $data['EkspedisiStaffID'], 
                $data['EkspedisiStaffHP'], $data['SJstatus'], $data['SJID']
            ]);
            if (!$queSJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update table suratjalan");
                exit;
            }

            $sqlN = "UPDATE suratjalan_detail SET
                SuratJalanDetailIsActive = 'N',
                SuratJalanDetailLastUpdated = NOW() 
            WHERE SuratJalanDetailSuratJalanID = ? 
                AND SuratJalanDetailIsActive = 'Y'";
            $queN = $this->db->query($sqlN, [$data['SJID']]);
            if (!$queN) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update suratjalan_detail to N");
                exit;
            }

            foreach ($detail as $key => $obj) {
                $sqlSJD = "INSERT INTO suratjalan_detail (
                    SuratJalanDetailSuratJalanID,
                    SuratJalanDetailPurchaseRequestFlagID,
                    SuratJalanDetailT_GoodsTransferDetailID,
                    SuratJalanDetailM_ItemID,
                    SuratJalanDetailQty,
                    SuratJalanDetailItemUnitID,
                    SuratJalanDetailCreated,
                    SuratJalanDetailUserID
                ) VALUES (?,?,?,?,?,?,NOW(),?)";
                $queSJD = $this->db->query($sqlSJD, [
                    $data['SJID'], $obj['PRFlagID'], $obj['TGDetailID'], 
                    $obj['ItemID'], $obj['Qty'], $obj['ItemUnitID'], $user['M_UserID']
                ]);
                if (!$queSJD) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] insert into table suratjalan_detail");
                    exit;
                }
            }

            ## GET LAST INSERTED DATA ##
            $sqlgetSJ = "SELECT * FROM suratjalan WHERE SuratJalanID = ? AND SuratJalanIsActive = 'Y'";
            $quegetSJ = $this->db->query($sqlgetSJ, [$data['SJID']]);
            if (!$quegetSJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get last inserted data from table suratjalan");
                exit;
            }
            $lastSJ = $quegetSJ->row_array();

            $sqlgetSJD = "SELECT * FROM suratjalan_detail WHERE SuratJalanDetailSuratJalanID = ? AND SuratJalanDetailIsActive = 'Y'";
            $quegetSJD = $this->db->query($sqlgetSJD, [$data['SJID']]);
            if (!$quegetSJD) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get last inserted data from table suratjalan_detail");
                exit;
            }
            $lastSJD = $quegetSJD->result_array();
            $lastSJ['detail'] = $lastSJD;

            ## UPDATE STOCK DAN KALKULASI STOCK ##
            if (strtolower($data['SJstatus']) === 'process' && strtolower($data['TFtype']) === 'persediaan') {
                $this->confirmSuratJalan($lastSJ, $lastSJD, $user);
                $this->generateJurnal($lastSJ, $lastSJD, $data['TFtype'], $user);
            }

            if (strtolower($data['SJstatus']) === 'process' && strtolower($data['TFtype']) === 'non persediaan') {
                $this->confirmSuratJalanNP($lastSJ, $lastSJD, $user);
                $this->generateJurnal($lastSJ, $lastSJD, $data['TFtype'], $user);
            }

            ## INSERT INTO LOG ACTIVITY ##
            $msg = "Surat Jalan nomor: {$lastSJ['SuratJalanNumber']}, Tanggal: {$lastSJ['SuratJalanDate']}";
            $this->insertUserActivty($data['SJID'], "UPDATE", $user['M_UserID'], $msg, json_encode($lastSJ));

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

    function confirmSuratJalan($data, $detail, $user) {
        
        ## UPDATE STATUS SURATJALAN ##
        $sqlsj = "UPDATE suratjalan SET SuratJalanStatus = 'Process' WHERE SuratJalanID = ? AND SuratJalanIsActive = 'Y'";
        $quesj = $this->db->query($sqlsj, [$data['SuratJalanID']]);
        if (!$quesj) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] update status surat jalan");
            exit;
        }

        ## UPDATE STATUS T_GOODS_TRANSFER ##
        $sqltf = "UPDATE t_goods_transfer SET T_GoodsTransferStatus = 'Process' WHERE T_GoodsTransferID = ? AND T_GoodsTransferIsActive = 'Y'";
        $quetf = $this->db->query($sqltf, [$data['SuratJalanT_GoodsTransferID']]);
        if (!$quetf) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] update status transfer request");
            exit;
        }

        ## UPDATE STOCK KELUAR KE TRANSIT ##
        // foreach ($detail as $key => $obj) {
        //     ## GET DETAIL TF BATCHES STOCK ##
        //     $sqltfd = "SELECT T_GoodsTransferDetailItemBatchNo FROM t_goods_transfer_detail WHERE T_GoodsTransferDetailID = ? AND T_GoodsTransferDetailIsActive = 'Y'";
        //     $quetfd = $this->db->query($sqltfd, [$obj['SuratJalanDetailT_GoodsTransferDetailID']]);
        //     if (!$quetfd) {
        //         $this->db->trans_rollback();
        //         $this->sys_error_db("[Error] get data batch number stock");
        //         exit;
        //     }
        //     $jsonStr = $quetfd->row_array()['T_GoodsTransferDetailItemBatchNo'];
        //     $batches = [];

        //     if (!empty($jsonStr)) {
        //         $decode = json_decode($jsonStr, true);
        //         if ($decode !== null && json_last_error() === JSON_ERROR_NONE) {
        //             $batches = $decode;
        //         } else {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] decode batches number stock");
        //             exit;
        //         }
        //     }

        //     ## UPDATE STOCK WAREHOUSE REGIONAL AND WAREHOUSE TRANSIT ##
        //     foreach ($batches as $key => $ele) {
        //         $sqlupdstock = "UPDATE stock SET 
        //             StockQty = StockQty - ?,
        //             StockLastUpdated = NOW()
        //         WHERE StockID = ?";
        //         $queupdstock = $this->db->query($sqlupdstock, [$ele['QtyReq'], $ele['StockID']]);
        //         if (!$queupdstock) {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] update stock regional");
        //             exit;
        //         }

        //         $sqlwh = "SELECT 
        //             StockID,
        //             WarehouseID,
        //             WarehouseName
        //         FROM warehouse
        //         LEFT JOIN stock ON StockWarehouseID = WarehouseID 
        //             AND StockItemID = ?
        //             AND StockItemUnitID = ?
        //             AND StockBatchNo = ?
        //             AND WarehouseIsActive = 'Y'
        //         WHERE WarehouseIsTransit = 'Y'
        //             AND WarehouseS_RegionalID = ?
        //             AND WarehouseM_BranchID = 0";
        //        $quewh = $this->db->query($sqlwh, [
        //             $ele['StockItemID'], $ele['StockItemUnitID'], 
        //             $ele['StockBatchNo'], $user['S_RegionalID']
        //        ]);
        //        if (!$quewh) {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] check wh transit");
        //             exit;
        //        }
        //        $transit = $quewh->row_array();
               
        //        if (is_null($transit['StockID'])) {
        //             $sqlupdtsit = "INSERT INTO stock (
        //                 StockWarehouseID,
        //                 StockStockNumber,
        //                 StockItemID,
        //                 StockItemUnitID,
        //                 StockItemPrice,
        //                 StockBatchNo,
        //                 StockED,
        //                 StockQty,
        //                 StockUserID
        //             ) VALUES (?,fn_numbering('SN'),?,?,?,?,?,?,?)";
        //             $queupdtsit = $this->db->query($sqlupdtsit, [
        //                 $transit['WarehouseID'],
        //                 $ele['StockItemID'],
        //                 $ele['StockItemUnitID'],
        //                 $ele['StockItemPrice'],
        //                 $ele['StockBatchNo'],
        //                 $ele['StockED'],
        //                 $ele['QtyReq'],
        //                 $user['M_UserID']
        //             ]);
        //             if (!$queupdtsit) {
        //                 $this->db->trans_rollback();
        //                 $this->sys_error_db("[Error] insert stock to warehouse transit");
        //                 exit;
        //             }
        //        } else {
        //             $sqlupdtrst = "UPDATE stock SET
        //                 StockQty = StockQty + ?,
        //                 StockLastUpdated = NOW()
        //             WHERE StockID = ?";
        //             $queupdtrst = $this->db->query($sqlupdtrst, [$ele['QtyReq'], $transit['StockID']]);
        //             if (!$queupdtrst) {
        //                 $this->db->trans_rollback();
        //                 $this->sys_error_db("[Error] update stock to warehouse transit");
        //                 exit;
        //             }
        //        }

        //         $sqllog = "INSERT INTO stocklog (
        //             StockLogWarehouseID,
        //             StockLogDateTime,
        //             StockLogItemID,
        //             StockLogItemUnitID,
        //             StockLogStockNumber,
        //             StockLogBatchNo,
        //             StockLogED,
        //             StockLogReffID,
        //             StockLogStatus,
        //             StockLogQty,
        //             StockLogUserID
        //         ) VALUES (?,NOW(),?,?,?,?,?,?,?,?,?)";
        //         $quelog = $this->db->query($sqllog, [
        //             $ele['WarehouseID'], $ele['StockItemID'], $ele['StockItemUnitID'], $ele['StockStockNumber'],
        //             $ele['StockBatchNo'], $ele['StockED'], $obj['SuratJalanDetailT_GoodsTransferDetailID'],
        //             "WTT", $ele['QtyReq'], $user['M_UserID']
        //         ]);
        //         if (!$quelog) {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] insert into stock log");
        //             exit;
        //         }
        //     }
        // }
    }

    function confirmSuratJalanNP($data, $detail, $user) {
        ## UPDATE STATUS SURATJALAN ##
        $sqlsj = "UPDATE suratjalan SET SuratJalanStatus = 'Process' WHERE SuratJalanID = ? AND SuratJalanIsActive = 'Y'";
        $quesj = $this->db->query($sqlsj, [$data['SuratJalanID']]);
        if (!$quesj) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] update status surat jalan");
            exit;
        }

        ## UPDATE STATUS T_GOODS_TRANSFER ##
        $sqltf = "UPDATE t_goods_transfer SET T_GoodsTransferStatus = 'Process' WHERE T_GoodsTransferID = ? AND T_GoodsTransferIsActive = 'Y'";
        $quetf = $this->db->query($sqltf, [$data['SuratJalanT_GoodsTransferID']]);
        if (!$quetf) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] update status transfer request");
            exit;
        }


        ## UPDATE STOCK KELUAR KE TRANSIT ##
        // foreach ($detail as $key => $obj) {
        //     ## GET DETAIL TF BATCHES STOCK ##
        //     $sqltfd = "SELECT T_GoodsTransferDetailItemBarNote FROM t_goods_transfer_detail WHERE T_GoodsTransferDetailID = ? AND T_GoodsTransferDetailIsActive = 'Y'";
        //     $quetfd = $this->db->query($sqltfd, [$obj['SuratJalanDetailT_GoodsTransferDetailID']]);
        //     if (!$quetfd) {
        //         $this->db->trans_rollback();
        //         $this->sys_error_db("[Error] get data barnote number stock");
        //         exit;
        //     }
        //     $jsonStr = $quetfd->row_array()['T_GoodsTransferDetailItemBarNote'];
        //     $barnote = [];

        //     if (!empty($jsonStr)) {
        //         $decode = json_decode($jsonStr, true);
        //         if ($decode !== null && json_last_error() === JSON_ERROR_NONE) {
        //             $barnote = $decode;
        //         } else {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] decode barnote data number stock");
        //             exit;
        //         }
        //     }

        //     ## UPDATE STOCK WAREHOUSE REGIONAL AND WAREHOUSE TRANSIT ##
        //     foreach ($barnote as $key => $ele) {
        //         $sqlupdstock = "UPDATE stock SET 
        //             StockQty = StockQty - ?,
        //             StockLastUpdated = NOW()
        //         WHERE StockID = ?";
        //         $queupdstock = $this->db->query($sqlupdstock, [$ele['QtyReq'], $ele['StockID']]);
        //         if (!$queupdstock) {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] update stock regional");
        //             exit;
        //         }

        //         $sqlwh = "SELECT 
        //             StockID,
        //             WarehouseID,
        //             WarehouseName
        //         FROM warehouse
        //         LEFT JOIN stock ON StockWarehouseID = WarehouseID 
        //             AND StockItemID = ?
        //             AND StockItemUnitID = ?
        //             AND WarehouseIsActive = 'Y'
        //         WHERE WarehouseIsTransit = 'Y'
        //             AND WarehouseS_RegionalID = ?
        //             AND WarehouseM_BranchID = 0";
        //        $quewh = $this->db->query($sqlwh, [
        //             $ele['StockItemID'], $ele['StockItemUnitID'], $user['S_RegionalID']
        //        ]);
        //        if (!$quewh) {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] check wh transit");
        //             exit;
        //        }
        //        $transit = $quewh->row_array();

        //        if (is_null($transit['StockID'])) {
        //             $sqlupdtsit = "INSERT INTO stock (
        //                 StockWarehouseID,
        //                 StockStockNumber,
        //                 StockItemID,
        //                 StockItemUnitID,
        //                 StockItemPrice,
        //                 StockED,
        //                 StockQty,
        //                 StockUserID
        //             ) VALUES (?,fn_numbering('SN'),?,?,?,?,?,?)";
        //             $queupdtsit = $this->db->query($sqlupdtsit, [
        //                 $transit['WarehouseID'],
        //                 $ele['StockItemID'],
        //                 $ele['StockItemUnitID'],
        //                 $ele['StockItemPrice'],
        //                 $ele['StockED'],
        //                 $ele['QtyReq'],
        //                 $user['M_UserID']
        //             ]);
        //             if (!$queupdtsit) {
        //                 $this->db->trans_rollback();
        //                 $this->sys_error_db("[Error] insert stock to warehouse transit");
        //                 exit;
        //             }
        //        } else {
        //             $sqlupdtrst = "UPDATE stock SET
        //                 StockQty = StockQty + ?,
        //                 StockLastUpdated = NOW()
        //             WHERE StockID = ?";
        //             $queupdtrst = $this->db->query($sqlupdtrst, [$ele['QtyReq'], $transit['StockID']]);
        //             if (!$queupdtrst) {
        //                 $this->db->trans_rollback();
        //                 $this->sys_error_db("[Error] update stock to warehouse transit");
        //                 exit;
        //             }
        //        }

        //         $sqllog = "INSERT INTO stocklog (
        //             StockLogWarehouseID,
        //             StockLogDateTime,
        //             StockLogItemID,
        //             StockLogItemUnitID,
        //             StockLogStockNumber,
        //             StockLogED,
        //             StockLogReffID,
        //             StockLogStatus,
        //             StockLogQty,
        //             StockLogUserID
        //         ) VALUES (?,NOW(),?,?,?,?,?,?,?,?)";
        //         $quelog = $this->db->query($sqllog, [
        //             $ele['WarehouseID'], $ele['StockItemID'], $ele['StockItemUnitID'], $ele['StockStockNumber'],
        //             $ele['StockED'], $obj['SuratJalanDetailT_GoodsTransferDetailID'],
        //             "WTT", $ele['QtyReq'], $user['M_UserID']
        //         ]);
        //         if (!$quelog) {
        //             $this->db->trans_rollback();
        //             $this->sys_error_db("[Error] insert into stock log");
        //             exit;
        //         }
        //     }
        // }
    }

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

            $para = $this->sys_input;

            $this->db->trans_begin();
            
            ## GET DATA BEFORE DELETED ##
            $sqlgetSJ = "SELECT * FROM suratjalan WHERE SuratJalanID = ? AND SuratJalanIsActive = 'Y'";
            $quegetSJ = $this->db->query($sqlgetSJ, [$para['SJalanID']]);
            if (!$quegetSJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get last inserted data from table suratjalan");
                exit;
            }
            $lastSJ = $quegetSJ->row_array();

            $sqlgetSJD = "SELECT * FROM suratjalan_detail WHERE SuratJalanDetailSuratJalanID = ? AND SuratJalanDetailIsActive = 'Y'";
            $quegetSJD = $this->db->query($sqlgetSJD, [$para['SJalanID']]);
            if (!$quegetSJD) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] get last inserted data from table suratjalan_detail");
                exit;
            }
            $lastSJD = $quegetSJD->result_array();
            $lastSJ['detail'] = $lastSJD;

            ## UPDATE IS ACTIVE TABLE SURATJALAN ##
            $sqlSJ = "UPDATE suratjalan 
                SET SuratJalanIsActive = 'N'
                WHERE SuratJalanID = ? 
                    AND SuratJalanIsActive = 'Y'";
            $qrySJ = $this->db->query($sqlSJ, [$para['SJalanID']]);
            if (!$qrySJ) {
                $this->db->trans_rollback();
                $this->sys_error_db("error delete data surat jalan");
                exit;
            }

            ## UPDATE IS ACTIVE TABLE SURATJALAN DETAIL##
            $sqlSJD = "UPDATE suratjalan_detail 
                SET SuratJalanDetailIsActive = 'N'
                WHERE SuratJalanDetailSuratJalanID = ? 
                    AND SuratJalanDetailIsActive = 'Y'";
            $qrySJD = $this->db->query($sqlSJD, [$para['SJalanID']]);
            if (!$qrySJD) {
                $this->db->trans_rollback();
                $this->sys_error_db("error delete data surat jalan detail");
                exit;
            }

            $this->insertUserActivty($para['SJalanID'], "DELETE", $this->sys_user["M_UserID"], 'Delete Surat jalan', json_encode($lastSJ));
            $this->db->trans_commit();
            $this->sys_ok("success hapus surat jalan");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function generateJurnal($data, $detail, $type, $user) {
        ## CHECK JOURNAL TIME PERIOD ##
        $sqlperiod = "SELECT periodeID FROM periode WHERE DATE(NOW()) BETWEEN periodeStartDate AND periodeEndDate";
        $queperiod = $this->db->query($sqlperiod, []);
        if (!$queperiod) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] check periode");
            exit;
        }
        $periode = $queperiod->row_array();
        if (empty($periode)) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] periode waktu tidak ditemukan");
            exit;
        }

        ## GENERATE JURNAL NUMBER ##
        $sqlnum = "SELECT `fn_numbering`('J') as JNumber";
        $qrynum = $this->db->query($sqlnum, []);
        if (!$qrynum) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] generate jurnal number");
            exit;
        }
        $JurnalNumber = $qrynum->row()->JNumber;

        ## GET JURNAL TYPE ID ##
        $sqltype = "SELECT JurnalTypeID as Jtype FROM jurnal_type WHERE JurnalTypeCode = ?";
        $qrytype = $this->db->query($sqltype, ['AUTOSENDGOODR']);
        if (!$qrytype) {
            $this->db->trans_rollback();
            $this->sys_error("[Error] get id jurnal type");
            exit;
        }
        $Jurnaltype = $qrytype->row()->Jtype;

        ## TUJUAN TRANSFEr ##
        $sqltj = "SELECT 
            M_BranchName,
            M_BranchCode
        FROM t_goods_transfer
        JOIN m_branch ON M_BranchCode = T_GoodsTransferToM_BranchCode
        WHERE T_GoodsTransferID = ? AND T_GoodsTransferIsActive = 'Y'";
        $quetj = $this->db->query($sqltj, [$data['SuratJalanT_GoodsTransferID']]);
        if (!$quetj) {
            $this->db->trans_rollback();
            $this->sys_error("[Error] get tujuan transfer");
            exit;
        }
        $tjcabang = $quetj->row_array();

        $title = "Auto Jurnal Transfer Regional - Cabang Surat Jalan Number {$data['SuratJalanNumber']}";
        $descp = "Surat Jalan Number: {$data['SuratJalanNumber']}, Tanggal: {$data['SuratJalanDate']}, Tujuan: {$tjcabang['M_BranchName']} ({$tjcabang['M_BranchCode']})";
        $sqlJurnal = "INSERT INTO jurnal (
            jurnalM_BranchCompanyID,
            JurnalS_RegionalID,
            jurnalM_BranchCode,
            jurnalperiodeID,
            jurnalNo,
            jurnalTitle,
            jurnalDescription,
            jurnalDate,
            jurnalJurnalTypeID,
            jurnalM_UserID
        ) VALUES (?,?,?,?,?,?,?,?,?,?)";
        $queJurnal = $this->db->query($sqlJurnal, [
            $user['M_BranchCompanyID'], $user['S_RegionalID'], $user['M_BranchCode'], 
            $periode['periodeID'], $JurnalNumber, $title, $descp, 
            $data['SuratJalanDate'], $Jurnaltype, $user['M_UserID'] 
        ]);
        if (!$queJurnal) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] insert into table jurnal");
            exit;
        }
        $JurnalID = $this->db->insert_id();

        ## GET COA ID  ##
        $sqlcoa = "SELECT coaID, coaDescription FROM coa WHERE coaAccountNo = ? AND coaIsActive = 'Y'";
        $quecoa = $this->db->query($sqlcoa, ['1150700001']);
        if (!$quecoa) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] get coa id");
            exit;
        }
        $coa = $quecoa->row_array();
        if (empty($coa)) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] coa null or not found");
            exit;
        }

        ## INSERT DATA TO JURNAL TX ##
        $sqlJurnalTX = "INSERT INTO jurnal_tx (
            jurnalTxJurnalID,
            jurnalTxCoaID,
            jurnalTxDescription,
            jurnalTxDebit,
            jurnalTxCredit,
            jurnalTxM_UserID
        ) VALUES (?,?,?,?,?,?)";

        $total = 0.00;
        foreach ($detail as $key => $obj) {
            if (strtolower($type) === 'persediaan') {
                ## GET DETAIL TF BATCHES STOCK ##
                $sqltfd = "SELECT T_GoodsTransferDetailItemBatchNo FROM t_goods_transfer_detail WHERE T_GoodsTransferDetailID = ? AND T_GoodsTransferDetailIsActive = 'Y'";
                $quetfd = $this->db->query($sqltfd, [$obj['SuratJalanDetailT_GoodsTransferDetailID']]);
                if (!$quetfd) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] get data batch number stock");
                    exit;
                }
                $jsonStr = $quetfd->row_array()['T_GoodsTransferDetailItemBatchNo'];
                $batches = [];

                if (!empty($jsonStr)) {
                    $decode = json_decode($jsonStr, true);
                    if ($decode !== null && json_last_error() === JSON_ERROR_NONE) {
                        $batches = $decode;
                    } else {
                        $this->db->trans_rollback();
                        $this->sys_error_db("[Error] decode batches number stock");
                        exit;
                    }
                }

                $subtotal = 0.00;
                foreach ($batches as $key => $ele) {
                    $harga = intval($ele['QtyReq']) * doubleval($ele['StockItemPrice']);
                    $subtotal = round($subtotal + $harga, 2);
                }

                $sqlcoaitem = "SELECT 
                    MapNatSub_PersediaanCoaID,
                    MapNatSub_PersediaanCoaDescription,
                    MapNatSub_PersediaanCoaAccountNo
                FROM m_item 
                JOIN map_nat_subgroup ON MapNatSub_NatGroupID = M_ItemNat_GroupID
                    AND MapNatSub_NatSubGroupID = M_ItemNat_SubGroupID
                    AND MapNatSub_IsActive = 'Y'
                WHERE M_ItemID = ?";
                $quecoaitem = $this->db->query($sqlcoaitem, [$obj['SuratJalanDetailM_ItemID']]);
                if (!$quecoaitem) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] get coa item");
                    exit;
                }
                $coaItem = $quecoaitem->row_array();
                if (empty($coaItem)) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] coa item null or not found");
                    exit;
                }

                # INSERT COA JURNAL PERSEDIAAN BARANG #
                $queJurnalTX = $this->db->query($sqlJurnalTX, [
                    $JurnalID, $coaItem['MapNatSub_PersediaanCoaID'], 
                    $coaItem['MapNatSub_PersediaanCoaDescription'], 0, $subtotal, $user['M_UserID']
                ]);

                $total = $total + $subtotal;
            } else {
                ## NON PERSEDIAAN ##
                $sqltfd = "SELECT T_GoodsTransferDetailItemBarNote FROM t_goods_transfer_detail WHERE T_GoodsTransferDetailID = ? AND T_GoodsTransferDetailIsActive = 'Y'";
                $quetfd = $this->db->query($sqltfd, [$obj['SuratJalanDetailT_GoodsTransferDetailID']]);
                if (!$quetfd) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] get data barnote number stock");
                    exit;
                }
                $jsonStr = $quetfd->row_array()['T_GoodsTransferDetailItemBarNote'];
                $barnote = [];

                if (!empty($jsonStr)) {
                    $decode = json_decode($jsonStr, true);
                    if ($decode !== null && json_last_error() === JSON_ERROR_NONE) {
                        $barnote = $decode;
                    } else {
                        $this->db->trans_rollback();
                        $this->sys_error_db("[Error] decode barnote number stock");
                        exit;
                    }
                }

                $subtotal = 0.00;
                foreach ($barnote as $key => $ele) {
                    $harga = intval($ele['QtyReq']) * doubleval($ele['StockItemPrice']);
                    $subtotal = round($subtotal + $harga, 2);
                }

                $sqlcoaitem = "SELECT 
                    MapNatSub_BiayaCoaID,
                    MapNatSub_BiayaCoaAccountNo,
                    MapNatSub_BiayaCoaDescription
                FROM m_item 
                JOIN map_nat_subgroup ON MapNatSub_NatGroupID = M_ItemNat_GroupID
                    AND MapNatSub_NatSubGroupID = M_ItemNat_SubGroupID
                    AND MapNatSub_IsActive = 'Y'
                WHERE M_ItemID = ?";
                $quecoaitem = $this->db->query($sqlcoaitem, [$obj['SuratJalanDetailM_ItemID']]);
                if (!$quecoaitem) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] get coa item non persediaan");
                    exit;
                }
                $coaItem = $quecoaitem->row_array();
                if (empty($coaItem)) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] coa item non persediaan null or not found");
                    exit;
                }

                # INSERT COA JURNAL NON PERSEDIAAN BARANG #
                $queJurnalTX = $this->db->query($sqlJurnalTX, [
                    $JurnalID, $coaItem['MapNatSub_BiayaCoaID'], $coaItem['MapNatSub_BiayaCoaDescription'], 
                    0, $subtotal, $user['M_UserID']
                ]);
                
                $total = $total + $subtotal;
            }
        }

        # INSERT COA JURNAL STOCK DALAM PERJALANAN #
        $queJurnalTX = $this->db->query($sqlJurnalTX, [
            $JurnalID, $coa['coaID'], $coa['coaDescription'], 
            $total, 0, $user['M_UserID']
        ]);
        if (!$queJurnalTX) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] insert jurnal tx");
            exit;
        }
        $JurnalTXID = $this->db->insert_id();

        ## INSERT JURNAL ADDON ##
        $sqlJurnalAdd = "INSERT INTO jurnal_addon (
            jurnalAddOnJurnalID,
            jurnalAddOnJurnalTxID,
            jurnalAddOnCode,
            jurnalAddOnValue,
            jurnalAddOnCreated,
            jurnalAddOnCreatedUserID
        ) VALUES (?,?,?,?,NOW(),?)";
        $queJurnalAdd = $this->db->query($sqlJurnalAdd, [
            $JurnalID, $JurnalTXID, 'SENDGOODRDST', $data['SuratJalanNumber'], $user['M_UserID']
        ]);
        if (!$queJurnalAdd) {
            $this->db->trans_rollback();
            $this->sys_error_db("[Error] insert jurnal addon");
            exit;
        }
    }

    function insertUserActivty($id, $type, $userID, $desc = '', $data = '')
    {
        $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, [
            'SJ',
            $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;
        }
    }
}



// SELECT 
// M_BranchName,
// M_BranchCode
// FROM t_goods_transfer
// JOIN m_branch ON M_BranchCode = T_GoodsTransferToM_BranchCode
// WHERE T_GoodsTransferID = 2