<?php

use BcMath\Number;

class TransferRequest extends MY_Controller
{
    var $db;

    public function index()
    {
        echo "Goods Transfer Request/Requester API";
    }

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

    public function getBranches()
    {
        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 getStatus()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }

            $rst = [
                ["value" => 0, "title" => "All"],
                ["value" => 1, "title" => "Draft"],
                ["value" => 2, "title" => "Pending"],
                ["value" => 3, "title" => "Approved"],
                ["value" => 4, "title" => "Rejected"],
                ["value" => 5, "title" => "Paid"],
                ["value" => 6, "title" => "Completed"]
            ];

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

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

            $payload = $this->sys_input;

            $startDate = $payload["startDate"];
            $endDate = $payload["endDate"];
            $branchCode = $payload["M_BranchCode"];
            $status = $payload["StatusName"];
            $search = "";

            if (isset($payload['search'])) {
                $search = trim($payload["search"]);
                if ($search != "") {
                    $search = '%' . $payload['search'] . '%';
                } else {
                    $search = '%%';
                }
            }

            $filterBranch = "";
            $filterStatus = "";
            if (isset($branchCode) && $branchCode != "") {
                if (strtolower($branchCode) == "all") {
                    $filterBranch .= "";
                } else {
                    $filterBranch .= " AND M_BranchCode = '{$branchCode}'";
                }
            }
            if (isset($status) && $status != "") {
                if (strtolower($status) == "all") {
                    $filterStatus .= "";
                } else {
                    $filterStatus .= " AND T_GoodsTransferStatus = '{$status}'";
                }
            }

            $sql = "SELECT
                    t_goods_transfer.*,
                    S_RegionalID,
                    S_RegionalName,
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM t_goods_transfer
                    JOIN s_regional ON T_GoodsTransferFromS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON T_GoodsTransferToM_BranchCode = M_BranchCode AND  M_BranchIsActive = 'Y'
                    WHERE T_GoodsTransferIsActive = 'Y'
                    AND (T_GoodsTransferDate BETWEEN '{$startDate} 00:00:00' AND '{$endDate} 23:59:59')
                    AND (T_GoodsTransferNum LIKE '{$search}')
                    $filterBranch $filterStatus
                    ORDER BY T_GoodsTransferNum DESC";

            $sqlTotal = "SELECT count(*)  as total FROM ($sql) as x";
            $qryTotal = $this->db->query($sqlTotal);

            $number_offset = 0;
            $number_limit = 10;

            if ($payload["current_page"] > 0) {
                $number_offset = ($payload["current_page"] - 1) * $number_limit;
            }

            $totalCount = 0;
            $totalPage = 0;
            if ($qryTotal) {
                $totalCount = $qryTotal->result_array()[0]["total"];
                $totalPage = ceil($totalCount / $number_limit);
            } else {
                $this->sys_error_db("Error count total SQL Result", $this->db);;
                exit;
            }

            $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset";
            $qry = $this->db->query($sql_select);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->sys_error_db("Failed search Transfer Request List", $this->db);
                exit;
            }

            $result = array(
                "totalPage" => $totalPage,
                "totalFilter" => $totalCount,
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $payload = $this->sys_input;
            $regionalID = $this->sys_user["S_RegionalID"];

            $startDate = $payload["startDate"];
            $endDate = $payload["endDate"];
            $search = $payload['search'];
            if ($search == "") {
                $search = "%";
            }

            $status = $payload['StatusName'];
            if (strtolower($status) == "all") {
                $status = "%";
            }

            $cabangcode = $payload["M_BranchCode"];
            if (strtolower($cabangcode) == "all") {
                $cabangcode = "%";
            }

            $offset = 0;
            $limit = 10;
            if ($payload['currentPage'] > 0) {
                $offset = ($payload['currentPage'] - 1) * $limit;
            }

            $sql = "SELECT
                t_goods_transfer.*,
                M_BranchID,
                M_BranchCode,
                M_BranchName
            FROM t_goods_transfer
            JOIN m_branch ON T_GoodsTransferToM_BranchCode = M_BranchCode 
                AND M_BranchIsActive = 'Y'
            WHERE T_GoodsTransferIsActive = 'Y'
                AND T_GoodsTransferFromS_RegionalID = ?
                AND T_GoodsTransferNum LIKE ?
                AND T_GoodsTransferToM_BranchCode LIKE ?
                AND T_GoodsTransferType = 'P'
                AND T_GoodsTransferStatus LIKE ?
                AND T_GoodsTransferDate BETWEEN DATE(?) AND DATE(?)
            ORDER BY T_GoodsTransferDate DESC";

            $sqldata = $sql . " LIMIT ? OFFSET ?";
            $quedata = $this->db->query($sqldata, [
                $regionalID, $search, $cabangcode, 
                $status, $startDate, $endDate,
                $limit, $offset
            ]);
            if (!$quedata) {
                $this->sys_error_db("[Error] get data");
                exit;
            }
            $data = $quedata->result_array();

            $sqltotal = "SELECT COUNT(*) AS total FROM ($sql) AS x";
            $quetotal = $this->db->query($sqltotal, [
                $regionalID, $search, $cabangcode, 
                $status, $startDate, $endDate
            ]);
            if (!$quetotal) {
                $this->sys_error_db("[Error] get total data");
                exit;
            }
            $total = $quetotal->result_array()[0]['total'];
            
            $result = array(
                "records" => $data,
                "total" => $total
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function createTfRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $userID = $this->sys_user["M_UserID"];
            $data = $this->sys_input;

            // Check if mandatory fields in $data are empty. And return field that are empty if any
            $mandatoryFields = ["S_RegionalID", "M_BranchCode", "GoodsTfDate", "GoodsTfStatus"];
            $emptyFields = [];
            foreach ($mandatoryFields as $field) {
                if (empty($data[$field])) {
                    $emptyFields[] = $field;
                }
            }

            if (!empty($emptyFields)) {
                $this->sys_error("Mandatory fields are empty: " . implode(", ", $emptyFields));
                exit;
            }
            $tfdetail = $data['detail'];

            $this->db->trans_begin($data["isDebug"] == 'true');
            // Generate Goods Transfer Number
            $sql = "SELECT `fn_numbering`('TR') AS GoodsTfNum";
            $exec = $this->db->query($sql, []);
            $goodsTfNum = $exec->row()->GoodsTfNum;

            // Make sure branchCode is in a region
            $sql = "SELECT M_BranchCode, M_BranchName, S_RegionalName FROM m_branch 
                JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID
            WHERE M_BranchCode = ? AND M_BranchS_RegionalID = ?";
            $exec = $this->db->query($sql, [$data["M_BranchCode"], $data["S_RegionalID"]]);
            if ($exec->num_rows() == 0 || $exec->row() == null) {
                $this->sys_error("Tidak bisa transfer ke cabang di luar regional");
                exit;
            }
            $regBranch = $exec->row_array();

            $descActivity = "Transfer Request dari {$regBranch["S_RegionalName"]} ke {$data["M_BranchName"]} dengan kode transfer {$goodsTfNum} dan status {$data["GoodsTfStatus"]} telah dibuat";
            $sql = "INSERT INTO t_goods_transfer (
                        T_GoodsTransferFromS_RegionalID,
                        T_GoodsTransferToM_BranchCode,
                        T_GoodsTransferNum,
                        T_GoodsTransferNotes,
                        T_GoodsTransferDate,
                        T_GoodsTransferStatus,
                        T_GoodsTransferIsActive,
                        T_GoodsTransferCreatedAt,
                        T_GoodsTransferM_UserID
                    ) VALUES (?, ?, ?, ?, ?, ?, 'Y', NOW(), ?)";

            $exec = $this->db->query($sql, [
                $data["S_RegionalID"],
                $data["M_BranchCode"],
                $goodsTfNum,
                $data["GoodsTfNotes"],
                $data["GoodsTfDate"],
                $data["GoodsTfStatus"],
                $userID
            ]);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("Gagal insert Transfer Request (No. TF: {$goodsTfNum}). Error:", $this->db);
                exit;
            }
            $tGoodsTFID = $this->db->insert_id();

            // insert detail tf
            foreach ($tfdetail as $key => $value) {
                $flagID = $value['PurchaseRequestFlagID'];
                $itemID = $value['PurchaseRequestDetailM_ItemID'];
                $unitID = $value['PurchaseRequestDetailItemUnitID'];
                $QtyStart = intval($value['PurchaseRequestFlagQty']);
                $QtyTfRes = intval($value['PurchaseRequestFlagQtyRest']);

                // insert item batch
                $batchstring = "";
                foreach ($tfdetail['ItemRequest'] as $key => $value) {
                    $batchstring = $batchstring . $value['StockBatchNo'] . ", ";
                }

                $sqldetail = "INSERT INTO t_goods_transfer_detail (
                        T_GoodsTransferDetailIDT_GoodsTransferID,
                        T_GoodsTransferDetailT_PurchaseRequestFlagID,
                        T_GoodsTransferDetailM_ItemID,
                        T_GoodsTransferDetailItemUnitID,
                        T_GoodsTransferDetailItemBatchNo,
                        T_GoodsTransferDetailQty,
                        T_GoodsTransferDetailQtyTF,
                        T_GoodsTransferDetailCreatedAt,
                        T_GoodsTransferDetailM_UserID 
                    ) VALUES (?,?,?,?,?,?,?,NOW(),?)";
                $query = $this->db->query($sqldetail, [
                    $tGoodsTFID,
                    $flagID,
                    $itemID,
                    $unitID,
                    $batchstring,
                    $QtyStart,
                    $QtyTfRes,
                    $userID
                ]);

                if (!$query) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("gagal insert detail transfer request (No. TF: {$goodsTfNum}). Error: ", $this->db);
                    exit;
                }
                $TGoodsTFDetailID = $this->db->insert_id();
                $tfdetail[$key]['TGoodsTFDetailID'] = $TGoodsTFDetailID;

                if ($data["GoodsTfStatus"] == 'Verified') {
                    $sqlqtyproc = "SELECT PurchaseRequestFlagQtyProses 
                        FROM purchase_request_flag 
                        WHERE PurchaseRequestFlagID = ? 
                            AND PurchaseRequestFlagIsActive = 'Y'";
                    $qryprocqty = $this->db->query($sqlqtyproc, [$flagID]);
                    if (!$qryprocqty) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("error current purchase request flag process quantity");
                        exit;
                    }
                    $qtyproc = $qryprocqty->result_array()[0]['PurchaseRequestFlagQtyProses'];
                    $procesQty = intval($qtyproc) + $QtyTfRes;

                    $sqlflagdetail = "UPDATE purchase_request_flag 
                        SET PurchaseRequestFlagQtyRest = ?,
                            PurchaseRequestFlagQtyProses = ?
                        WHERE PurchaseRequestFlagID = ? 
                            AND PurchaseRequestFlagIsActive = 'Y'";
                    $qflag = $this->db->query($sqlflagdetail, [$QtyTfRes, $procesQty, $flagID]);
                    if (!$qflag) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("error update qty flag detail req transfer");
                        exit;
                    }
                }
            }

            $sql_json = "SELECT t_goods_transfer.*, '' as details
            FROM t_goods_transfer
            WHERE T_GoodsTransferIsActive = 'Y'
            AND T_GoodsTransferID = ?";
            $qry_json = $this->db->query($sql_json, [$tGoodsTFID]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json tf error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $sql_json_detail = "SELECT t_goods_transfer_detail.* 
                FROM t_goods_transfer_detail
                WHERE T_GoodsTransferDetailIsActive = 'Y'
                AND T_GoodsTransferDetailIDT_GoodsTransferID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$tGoodsTFID]);
            if ($qry_json_detail) {
                $row_json["details"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail tf error", $this->db);
                exit;
            }

            $data_json = $row_json;

            $this->insertUserActivty($tGoodsTFID, 'DRAFT', $userID, $descActivity, json_encode($data_json));
            $this->db->trans_commit();
            $msg = "Berhasil membuat Transfer Request (No. TF: {$goodsTfNum}) pada ID : " . $this->db->insert_id();


            $newInsert = "SELECT 
                    T_GoodsTransferNum, 
                    T_GoodsTransferID 
                FROM t_goods_transfer 
                WHERE T_GoodsTransferNum = ? 
                    AND T_GoodsTransferIsActive = 'Y'";
            $record = $this->db->query($newInsert, [$goodsTfNum])->result_array();
            $record[0]['detail'] = $tfdetail;

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

    public function updateTfRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $userID = $this->sys_user["M_UserID"];
            $data = $this->sys_input;
            $this->db->trans_begin();

            $sql = "UPDATE t_goods_transfer SET 
                    T_GoodsTransferFromS_RegionalID = ?,
                    T_GoodsTransferToM_BranchCode = ?,
                    T_GoodsTransferNum = ?,
                    T_GoodsTransferNotes = ?,
                    T_GoodsTransferDate = ?,
                    T_GoodsTransferStatus = ?,
                    T_GoodsTransferLastUpdated = NOW(),
                    T_GoodsTransferM_UserID = ?
                WHERE T_GoodsTransferID = ?
                AND T_GoodsTransferIsActive = 'Y'";

            $exec = $this->db->query($sql, [
                $data["S_RegionalID"],
                $data["M_BranchCode"],
                $data["GoodsTfNum"],
                $data["GoodsTfNotes"],
                $data["GoodsTfDate"],
                $data["GoodsTfStatus"],
                $userID,
                $data["GoodsTfID"]
            ]);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("Gagal menghapus Transfer Request (ID: {$data['GoodsTfID']}). Error:", $this->db);
                exit;
            }

            $sql_n = "UPDATE t_goods_transfer_detail 
                SET T_GoodsTransferDetailIsActive = 'N' 
                WHERE T_GoodsTransferDetailIDT_GoodsTransferID = ?";
            $qry_n = $this->db->query($sql_n, [$data["GoodsTfID"]]);
            if (!$qry_n) {
                $this->db->trans_rollback();
                $this->sys_error_db("error change into 'N'");
                exit;
            }

            $descActivity = "Update transfer request {$data['GoodsTfNum']} menjadi {$data["GoodsTfStatus"]}";
            $detail = $data["detail"];
            foreach ($detail as $key => $value) {
                $flagID = $value['PurchaseRequestFlagID'];
                $itemID = $value['PurchaseRequestDetailM_ItemID'];
                $unitID = $value['PurchaseRequestDetailItemUnitID'];
                $QtyStart = intval($value['PurchaseRequestFlagQty']);
                $QtyTfRes = intval($value['PurchaseRequestFlagQtyRest']);

                $batchstring = "";
                foreach ($value['ItemRequest'] as $key => $value) {
                    $batchstring = $batchstring . $value['StockBatchNo'] . ", ";
                }

                $sqldetail = "INSERT INTO t_goods_transfer_detail (
                        T_GoodsTransferDetailIDT_GoodsTransferID,
                        T_GoodsTransferDetailT_PurchaseRequestFlagID,
                        T_GoodsTransferDetailM_ItemID,
                        T_GoodsTransferDetailItemUnitID,
                        T_GoodsTransferDetailItemBatchNo,
                        T_GoodsTransferDetailQty,
                        T_GoodsTransferDetailQtyTF,
                        T_GoodsTransferDetailCreatedAt,
                        T_GoodsTransferDetailM_UserID 
                    ) VALUES (?,?,?,?,?,?,?,NOW(),?)";
                $query = $this->db->query($sqldetail, [
                    $data["GoodsTfID"],
                    $flagID,
                    $itemID,
                    $unitID,
                    $batchstring,
                    $unitID,
                    $QtyStart,
                    $QtyTfRes,
                    $userID
                ]);
                if (!$query) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("error insert new detail");
                    exit;
                }
                $TGoodsTFDetailID = $this->db->insert_id();
                $detail[$key]['TGoodsTFDetailID'] = $TGoodsTFDetailID;

                if ($data["GoodsTfStatus"] == "Verified") {
                    $sqlproc = "SELECT 
                            PurchaseRequestFlagQtyProses 
                        FROM purchase_request_flag
                        WHERE PurchaseRequestFlagID = ? 
                            AND PurchaseRequestFlagIsActive = 'Y'";
                    $qryproc = $this->db->query($sqlproc, [$flagID]);
                    if (!$qryproc) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("error get current purchase request flag qty proses");
                        exit;
                    }
                    $qtyProc = $qryproc->result_array()[0]['PurchaseRequestFlagQtyProses'];
                    $proses = intval($qtyProc) + $QtyTfRes;

                    $sqlflag = "UPDATE 
                            purchase_request_flag 
                        SET PurchaseRequestFlagQtyRest = ?,
                            PurchaseRequestFlagQtyProses = ?
                        WHERE PurchaseRequestFlagID = ? 
                            AND PurchaseRequestFlagIsActive = 'Y'";
                    $qryflag = $this->db->query($sqlflag, [$QtyTfRes, $proses, $flagID]);
                    if (!$qryflag) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("error update qty proses");
                        exit;
                    }
                }
            }

            $sql_json = "SELECT t_goods_transfer.*, '' as details
            FROM t_goods_transfer
            WHERE T_GoodsTransferIsActive = 'Y'
            AND T_GoodsTransferID = ?";
            $qry_json = $this->db->query($sql_json, [$data["GoodsTfID"]]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json tf error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $sql_json_detail = "SELECT t_goods_transfer_detail.* 
                FROM t_goods_transfer_detail
                WHERE T_GoodsTransferDetailIsActive = 'Y'
                AND T_GoodsTransferDetailIDT_GoodsTransferID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$data["GoodsTfID"]]);
            if ($qry_json_detail) {
                $row_json["details"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail tf error", $this->db);
                exit;
            }

            $data_json = $row_json;

            $this->insertUserActivty($data["GoodsTfID"], 'UPDATE', $userID, $descActivity, json_encode($data_json));

            $this->db->trans_commit();
            $newInsert = "SELECT 
                    T_GoodsTransferNum, 
                    T_GoodsTransferID 
                FROM t_goods_transfer 
                WHERE T_GoodsTransferNum = ?
                    AND  T_GoodsTransferID  = ?
                    AND T_GoodsTransferIsActive = 'Y'";
            $record = $this->db->query($newInsert, [$data["GoodsTfNum"], $data["GoodsTfID"]])->result_array();
            $record[0]['detail'] = $detail;

            $result = array("total" => 1, "msg" => "Success update TF {$data["GoodsTfNum"]}", "records" => $record);
            $this->sys_ok($result);
            exit;
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function deleteTfRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $userID = $this->sys_user["M_UserID"];
            $goodsTfID = $this->sys_input["GoodsTfID"];

            $this->db->trans_begin();

            $sql = "UPDATE t_goods_transfer SET 
                    T_GoodsTransferIsActive = 'N',
                    T_GoodsTransferDeleted = NOW(),
                    T_GoodsTransferM_UserID = ?
                WHERE T_GoodsTransferID = ?
                AND T_GoodsTransferIsActive = 'Y'";
            $qry = $this->db->query($sql, [$userID, $goodsTfID]);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("Gagal menghapus Transfer Request (ID: {$goodsTfID}). Error:", $this->db);
                exit;
            }

            $sqldet = "UPDATE t_goods_transfer_detail SET
                    T_GoodsTransferDetailIsActive = 'N',
                    T_GoodsTransferDetailDeletedAt = NOW(),
                    T_GoodsTransferDetailM_UserID = ?
                WHERE T_GoodsTransferDetailIDT_GoodsTransferID = ? AND T_GoodsTransferDetailIsActive = 'Y'
            ";
            $qdet = $this->db->query($sqldet, [$userID, $goodsTfID]);
            if (!$qdet) {
                $this->db->trans_rollback();
                $this->sys_error_db("failed delete detail transfer request item. Error:", $this->db);
                exit;
            }

            $sql_json = "SELECT t_goods_transfer.*, '' as details
            FROM t_goods_transfer
            WHERE T_GoodsTransferID = ?";
            $qry_json = $this->db->query($sql_json, [$goodsTfID]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json tf error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $descActivity = "Hapus transfer request {$row_json['T_GoodsTransferNum']}";

            $sql_json_detail = "SELECT t_goods_transfer_detail.* 
                FROM t_goods_transfer_detail
                WHERE T_GoodsTransferDetailIDT_GoodsTransferID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$goodsTfID]);
            if ($qry_json_detail) {
                $row_json["details"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail tf error", $this->db);
                exit;
            }

            $data_json = $row_json;

            $this->insertUserActivty($goodsTfID, 'DELETE', $userID, $descActivity, json_encode($data_json));
            $this->db->trans_commit();

            $this->sys_ok("Berhasil menghapus Transfer Request (ID: {$goodsTfID})");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $prm = $this->sys_input;
            $regionalid = $prm['regionalid'];
            $branchIDOrigin = $prm['branchIDorigin'];
            $branchCodeDestin = $prm['branchcodedestin'];
            $currpage = $prm['currpage'];

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

            $sqltotal = "SELECT 
                COUNT(DISTINCT PurchaseRequestDetailID) as total
            FROM purchase_request_flag 
            JOIN purchase_request_detail ON PurchaseRequestDetailID = PurchaseRequestFlagPurchaseRequestDetailID
                AND PurchaseRequestDetailIsActive = 'Y'
            JOIN purchase_request ON PurchaseRequestID = PurchaseRequestDetailPurchaseRequestID 
                AND PurchaseRequestIsActive = 'Y' 
            JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID AND M_ItemIsActive = 'Y'
                AND M_ItemItem_CategoryID = 1
            JOIN warehouse ON WarehouseS_RegionalID = PurchaseRequestS_RegionalID 
                AND WarehouseIsTransit = 'N'
                AND WarehouseM_BranchID = 0
                AND WarehouseIsActive = 'Y'
            LEFT JOIN stock ON StockItemId = M_ItemID AND StockWarehouseID = WarehouseID 
            WHERE PurchaseRequestFlagIsActive = 'Y' 
                AND FIND_IN_SET('TF', PurchaseRequestFlagStatus) 
                AND PurchaseRequestDetailStatus = 'Read' 
                AND PurchaseRequestFlagIsClosed = 'N' 
                AND PurchaseRequestS_RegionalID = ? 
                AND PurchaseRequestM_BranchCode = ? 
                AND NOT EXISTS (
                    SELECT 1 
                    FROM t_goods_transfer 
                    JOIN t_goods_transfer_detail ON T_GoodsTransferDetailIDT_GoodsTransferID = T_GoodsTransferID 
                        AND T_GoodsTransferDetailIsActive = 'Y' 
                    WHERE T_GoodsTransferDetailT_PurchaseRequestFlagID = PurchaseRequestFlagID
                        AND T_GoodsTransferFromS_RegionalID = ? 
                        AND T_GoodsTransferToM_BranchCode = ? 
                )";
            $quetotal = $this->db->query($sqltotal, [
                $regionalid, $branchCodeDestin, 
                $regionalid, $branchCodeDestin
            ]);
            if (!$quetotal) {
                $this->sys_error_db("error get total listing tf request");
                exit;
            }
            $total = $quetotal->result_array()[0]['total'];
            if (intval($total) === 0) {
                $result = array(
                    "records" => [],
                    "total" => $total
                );

                $this->sys_ok($result);
                exit;
            }

            $sqlist = "SELECT
                PurchaseRequestDate,
                PurchaseRequestNumber,
                PurchaseRequestDetailM_ItemID,
                PurchaseRequestDetailItemUnitID,
                M_ItemDesc,
                PurchaseRequestFlagID,
                PurchaseRequestFlagQty,
                PurchaseRequestFlagQtyRest,
                COALESCE(SUM(CASE WHEN WarehouseID IS NOT NULL AND StockItemId IS NOT NULL THEN StockQty ELSE 0 END), 0) as StockGudang,
                PurchaseRequestFlagStatus
            FROM purchase_request_flag 
            JOIN purchase_request_detail ON PurchaseRequestDetailID = PurchaseRequestFlagPurchaseRequestDetailID
                AND PurchaseRequestDetailIsActive = 'Y'
            JOIN purchase_request ON PurchaseRequestID = PurchaseRequestDetailPurchaseRequestID 
                AND PurchaseRequestIsActive = 'Y' 
            JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID AND M_ItemIsActive = 'Y' 
                AND M_ItemItem_CategoryID = 1
            JOIN warehouse ON WarehouseS_RegionalID = PurchaseRequestS_RegionalID 
                AND WarehouseIsTransit = 'N'
                AND WarehouseM_BranchID = 0 
                AND WarehouseIsActive = 'Y' 
            LEFT JOIN stock ON StockItemId = M_ItemID AND StockWarehouseID = WarehouseID 
            WHERE PurchaseRequestFlagIsActive = 'Y' 
                AND FIND_IN_SET('TF', PurchaseRequestFlagStatus) 
                AND PurchaseRequestDetailStatus = 'Read' 
                AND PurchaseRequestFlagIsClosed = 'N' 
                AND PurchaseRequestS_RegionalID = ? 
                AND PurchaseRequestM_BranchCode = ? 
                AND NOT EXISTS (
                    SELECT 1 
                    FROM t_goods_transfer 
                    JOIN t_goods_transfer_detail ON T_GoodsTransferDetailIDT_GoodsTransferID = T_GoodsTransferID 
                        AND T_GoodsTransferDetailIsActive = 'Y' 
                    WHERE T_GoodsTransferDetailT_PurchaseRequestFlagID = PurchaseRequestFlagID
                        AND T_GoodsTransferFromS_RegionalID = ? 
                        AND T_GoodsTransferToM_BranchCode = ? 
                )
            GROUP BY PurchaseRequestFlagID, PurchaseRequestNumber
            LIMIT ? OFFSET ?";

            $quelist = $this->db->query($sqlist, [
                $regionalid, $branchCodeDestin, 
                $regionalid, $branchCodeDestin, 
                $limit, $page
            ]);
            if (!$quelist) {
                $this->sys_error_db("error get listing detail request transfer");
                exit;
            }

            $rows = $quelist->result_array();
            foreach ($rows as $key => $value) {
                $rows[$key]['ItemRequest'] = [];
            }

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

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    public function getListDetail_old()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $regionalid = $prm['regionalid'];
            $branchcode = $prm['branchcode'];
            $currpage = $prm['currpage'];

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

            $sqltotal = "SELECT 
                COUNT(DISTINCT PurchaseRequestDetailID) as total
            FROM purchase_request_flag
            JOIN purchase_request_detail ON PurchaseRequestDetailID = PurchaseRequestFlagPurchaseRequestDetailID
            JOIN purchase_request ON PurchaseRequestID = PurchaseRequestDetailPurchaseRequestID
            JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID
                AND M_ItemIsActive = 'Y'
            JOIN m_branch ON M_BranchCode = PurchaseRequestM_BranchCode
                AND M_BranchIsActive = 'Y'
            JOIN warehouse ON WarehouseS_RegionalID = PurchaseRequestS_RegionalID
                AND WarehouseIsTransit = 'N'
                AND WarehouseM_BranchID != M_BranchID
                AND WarehouseIsActive = 'Y'
            LEFT JOIN stock ON StockItemId = M_ItemID 
                AND StockWarehouseID = WarehouseID
            WHERE PurchaseRequestFlagIsActive = 'Y' 
                AND FIND_IN_SET('TF', PurchaseRequestFlagStatus)
                AND PurchaseRequestDetailStatus = 'Read' 
                AND PurchaseRequestFlagIsClosed = 'N'
                AND PurchaseRequestS_RegionalID = ?
                AND PurchaseRequestM_BranchCode = ?
                AND NOT EXISTS (
                    SELECT 1 
                    FROM t_goods_transfer 
                    JOIN t_goods_transfer_detail ON T_GoodsTransferDetailIDT_GoodsTransferID = T_GoodsTransferID 
                        AND T_GoodsTransferDetailIsActive = 'Y' 
                    WHERE T_GoodsTransferDetailT_PurchaseRequestFlagID = PurchaseRequestFlagID
                        AND T_GoodsTransferFromS_RegionalID = ? 
                        AND T_GoodsTransferToM_BranchCode = ?
                )";
            $quetotal = $this->db->query($sqltotal, [$regionalid, $branchcode, $regionalid, $branchcode]);
            if (!$quetotal) {
                $this->sys_error_db("error get total listing tf request");
                exit;
            }
            $total = $quetotal->result_array()[0]['total'];
            if (intval($total) === 0) {
                $result = array(
                    "records" => [],
                    "total" => $total
                );

                $this->sys_ok($result);
                exit;
            }

            $sqlist = "SELECT
                PurchaseRequestDate,
                PurchaseRequestNumber,
                PurchaseRequestDetailM_ItemID,
                PurchaseRequestDetailItemUnitID,
                M_ItemDesc,
                PurchaseRequestFlagID,
                PurchaseRequestFlagQty,
                PurchaseRequestFlagQtyRest,
                COALESCE(SUM(CASE WHEN WarehouseID IS NOT NULL AND StockItemId IS NOT NULL THEN StockQty ELSE 0 END), 0) as StockGudang,
                PurchaseRequestFlagStatus
            FROM purchase_request_flag
            JOIN purchase_request_detail ON PurchaseRequestDetailID = PurchaseRequestFlagPurchaseRequestDetailID
            JOIN purchase_request ON PurchaseRequestID = PurchaseRequestDetailPurchaseRequestID
            JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID
                AND M_ItemIsActive = 'Y'
            JOIN m_branch ON M_BranchCode = PurchaseRequestM_BranchCode
                AND M_BranchIsActive = 'Y'
            JOIN warehouse ON WarehouseS_RegionalID = PurchaseRequestS_RegionalID
                AND WarehouseIsTransit = 'N'
                AND WarehouseM_BranchID != M_BranchID
                AND WarehouseIsActive = 'Y'
            LEFT JOIN stock ON StockItemId = M_ItemID 
                AND StockWarehouseID = WarehouseID
            WHERE PurchaseRequestFlagIsActive = 'Y' 
                AND FIND_IN_SET('TF', PurchaseRequestFlagStatus)
                AND PurchaseRequestDetailStatus = 'Read' 
                AND PurchaseRequestFlagIsClosed = 'N'
                AND PurchaseRequestS_RegionalID = ?
                AND PurchaseRequestM_BranchCode = ?
                AND NOT EXISTS (
                    SELECT 1 
                    FROM t_goods_transfer 
                    JOIN t_goods_transfer_detail ON T_GoodsTransferDetailIDT_GoodsTransferID = T_GoodsTransferID 
                        AND T_GoodsTransferDetailIsActive = 'Y' 
                    WHERE T_GoodsTransferDetailT_PurchaseRequestFlagID = PurchaseRequestFlagID
                        AND T_GoodsTransferFromS_RegionalID = ? 
                        AND T_GoodsTransferToM_BranchCode = ?
                )
            GROUP BY PurchaseRequestDate, PurchaseRequestNumber, PurchaseRequestDetailM_ItemID, 
                PurchaseRequestDetailItemUnitID, M_ItemDesc, PurchaseRequestFlagID, 
                PurchaseRequestFlagQty, PurchaseRequestFlagQtyRest, PurchaseRequestFlagStatus
            LIMIT ? OFFSET ?";

            $quelist = $this->db->query($sqlist, [$regionalid, $branchcode, $regionalid, $branchcode, $limit, $page]);
            if (!$quelist) {
                $this->sys_error_db("error get listing detail request transfer");
                exit;
            }

            $rows = $quelist->result_array();
            $result = array(
                "records" => $rows,
                "total" => $total
            );

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

    public function getDraftDetail()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $prm = $this->sys_input;
            $regID = $this->sys_user["S_RegionalID"];
            $goodTfID = $prm['goodTfID'];

            $sql = "SELECT 
                    PurchaseRequestDate,
                    PurchaseRequestNumber,
                    PurchaseRequestDetailM_ItemID,
                    PurchaseRequestDetailItemUnitID,
                    M_ItemDesc,
                    COALESCE(SUM(CASE WHEN WarehouseID IS NOT NULL AND StockItemId IS NOT NULL THEN StockQty ELSE 0 END), 0) as StockGudang,
                    PurchaseRequestFlagID,
                    T_GoodsTransferDetailQty as PurchaseRequestFlagQty,
                    T_GoodsTransferDetailQtyTF as PurchaseRequestFlagQtyRest,
                    T_GoodsTransferDetailItemBatchNo,
                    PurchaseRequestFlagStatus
                FROM t_goods_transfer
                LEFT JOIN t_goods_transfer_detail ON T_GoodsTransferDetailIDT_GoodsTransferID = T_GoodsTransferID
                    AND T_GoodsTransferDetailIsActive = 'Y'
                JOIN purchase_request_flag ON PurchaseRequestFlagID = T_GoodsTransferDetailT_PurchaseRequestFlagID
                    AND PurchaseRequestFlagIsActive = 'Y'
                JOIN purchase_request_detail ON PurchaseRequestDetailID = PurchaseRequestFlagPurchaseRequestDetailID
                    AND PurchaseRequestDetailIsActive = 'Y'
                JOIN purchase_request ON PurchaseRequestID = PurchaseRequestDetailPurchaseRequestID
                    AND PurchaseRequestIsActive = 'Y'
                JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID
                    AND M_ItemIsActive = 'Y'
                JOIN m_branch ON M_BranchCode = PurchaseRequestM_BranchCode
                    AND M_BranchIsActive = 'Y'
                JOIN warehouse ON WarehouseS_RegionalID = PurchaseRequestS_RegionalID
                    AND WarehouseIsTransit = 'N'
                    AND WarehouseM_BranchID != M_BranchID
                    AND WarehouseIsActive = 'Y'
                LEFT JOIN stock ON StockItemId = M_ItemID
                    AND StockWarehouseID = WarehouseID
                WHERE PurchaseRequestFlagIsActive = 'Y' 
                    AND T_GoodsTransferID = ? 
                    AND T_GoodsTransferIsActive = 'Y'
                GROUP BY PurchaseRequestNumber, PurchaseRequestFlagID";
            $qry = $this->db->query($sql, [$goodTfID]);
            if (!$qry) {
                $this->sys_error_db("error get data draft detail transfer");
                exit;
            }

            $detail = $qry->result_array();

            $sqlbatch = "SELECT 
                WarehouseName,
                StockID,
                StockStockNumber,
                StockItemID,
                StockItemUnitID,
                StockBatchNo,
                StockED,
                StockQty
            FROM warehouse
            JOIN stock ON StockWarehouseID = WarehouseID 
                AND WarehouseIsActive = 'Y'
                AND WarehouseIsTransit = 'N'
            WHERE WarehouseS_RegionalID = ?
                AND WarehouseM_BranchID = 0
                AND StockItemID = ?
                AND StockItemUnitID = ?
                AND StockBatchNo LIKE ?";

            foreach ($detail as $key => $value) {
                $value[$key]['ItemRequest'] = [];
                $batchs = array_filter(array_map('trim', explode(",", $value['T_GoodsTransferDetailItemBatchNo'])));
                foreach ($batchs as $key => $batch) {
                    $quebatch = $this->db->query($sqlbatch, [
                        $regID, $value['PurchaseRequestDetailM_ItemID'], 
                        $value['PurchaseRequestDetailItemUnitID'], $batch
                    ]);
                    if (!$quebatch) {
                        $this->sys_error_db("[Error] get batch item info");
                        exit;
                    }
                    $batchitem = $quebatch->row_array();
                    $detail[$key]['ItemRequest'][] = $batchitem;
                }
            }

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

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

            $userID = $this->sys_user["M_UserID"];
            $data = $this->sys_input;
            $tfdetail = $data['detail'];

            foreach ($tfdetail as $key => $value) {
                $reqFlagID = $data['PurchaseRequestFlagID'];
                $reqTFQty = $data['PurchaseRequestFlagQtyRest'];

                $sqlgetproc = "SELECT SELECT PurchaseRequestFlagQtyProses FROM purchase_request_flag
                    WHERE PurchaseRequestFlagID = ? AND PurchaseRequestFlagIsActive = 'Y'";
                $qrygetproc = $this->db->query($sqlgetproc, [$reqFlagID]);
                if (!$qrygetproc) {
                    $this->sys_error_db("error get current purchase request flag process quantity");
                    exit;
                }
                $qtyProc = $qrygetproc->result_array()[0]['PurchaseRequestFlagQtyProses'];

                $this->db->trans_begin();

                $procQtyUpdt = intval($qtyProc) + intval($reqTFQty);
                $sqlupdtproc = "UPDATE purchase_request_flag 
                    SET 
                        PurchaseRequestFlagQtyProses = ?,
                        PurchaseRequestFlagLastUpdated = NOW(),
                        PurchaseRequestFlagUserID = ? 
                    WHERE PurchaseRequestFlagID = ? 
                        AND PurchaseRequestFlagIsActive = 'Y'";
                $qryupdtproc = $this->db->query($sqlupdtproc, [$procQtyUpdt, $userID, $reqFlagID]);
                if (!$qryupdtproc) {
                    $this->db->trans_rollback();
                    $this->sys_error_db('error update flag update process qty');
                    exit;
                }
            }

            $this->db->trans_commit();
            $this->sys_ok("Berhasil mengupdate Qty process (ID: {$data['GoodsTfID']})");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $prm = $this->sys_input;
            $batchNo = "%";
            if ($prm['batchno'] != '') {
                $batchNo = $prm['batchno'] . "%";
            }

            $sqlbatch = "SELECT 
                WarehouseName,
                StockID,
                StockStockNumber,
                StockItemID,
                StockItemUnitID,
                StockBatchNo,
                StockED,
                StockQty
            FROM warehouse
            JOIN stock ON StockWarehouseID = WarehouseID 
                AND WarehouseIsActive = 'Y'
                AND WarehouseIsTransit = 'N'
            WHERE WarehouseS_RegionalID = ?
                AND WarehouseM_BranchID = 0
                AND StockItemID = ?
                AND StockItemUnitID = ?
                AND StockBatchNo LIKE ?";
            $quebatch = $this->db->query($sqlbatch, [
                $prm['regionalid'],
                $prm['itemid'],
                $prm['unitid'],
                $batchNo
            ]);
            if (!$quebatch) {
                $this->sys_error_db("error get data draft detail transfer");
                exit;
            }
            $batch = $quebatch->result_array();
            $result = array(
                'records' => $batch,
                'total' => sizeof($batch)
            );

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

    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, [
            'TR',
            $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;
        }
    }
}
