<?php

class RequestItemOut extends MY_Controller
{
    var $db;

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

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

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

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            // $currentPage = isset($payload["currentPage"]) ? $payload["currentPage"] : 1;
            $pageSize = isset($payload["pageSize"]) ? $payload["pageSize"] : 10;
            // $offset = ($currentPage - 1) * $pageSize;
            $startDate = isset($payload["startDate"]) ? $payload["startDate"] : "";
            $endDate = isset($payload["endDate"]) ? $payload["endDate"] : "";
            $status = isset($payload["status"]) ? $payload["status"] : "";
            $search = isset($payload["search"]) ? $payload["search"] : "";

            $approveLevelID = $this->sys_user['M_UserM_ApproveLevelID'];
            $flag = $payload['flag'];

            if ($approveLevelID == '1') {
                if ($flag == 'G') {
                    $sqlRIO = " AND RequestItemOutVerifiedUserID = 0";
                }
            } else if ($approveLevelID == '2') {
                if ($flag == 'G') {
                    $sqlRIO = " AND RequestItemOutVerifiedUserID != 0";
                }
            }

            $totalCount = 0;
            $totalPage = 1;

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

            $sql = "SELECT COUNT(*) as total
                    FROM request_item_out
                    JOIN s_regional ON S_RegionalID = RequestItemOutS_RegionalID
                    WHERE 
                    RequestItemOutIsActive = 'Y' AND 
                    ( RequestItemOutDate BETWEEN ? AND ? ) AND 
                    ( RequestItemOutStatus = ? OR ? = '' ) AND 
                    ( RequestItemOutNumber LIKE ?)
                    $sqlRIO
                    ORDER BY RequestItemOutNumber DESC";

            $exec = $this->db->query($sql, [$startDate, $endDate, $status, $status, '%' . $search . '%']);

            if ($exec) {
                $totalCount = $exec->result_array()[0]["total"];
                $totalPage = ceil($totalCount / $pageSize);
            } else {
                $this->sys_error_db("count request item out", $this->db);
                exit;
            }

            $sql = "SELECT DISTINCT RequestItemOutID as rioId, 
                    RequestItemOutNumber as rioNumber,
                    RequestItemOutWarehouseID as rioWarehouseId,
                    RequestItemOutDate as rioDate, 
                    RequestItemOutStatus as rioStatus, 
                    RequestItemOutS_RegionalID as rioRegionalId,
                    S_RegionalName as rioRegionalName,
                    RequestItemOutM_BranchCode as rioBranchCode,
                    M_BranchName as rioBranchName,
                    RequestItemOutNote as rioNote,
                    RequestItemOutDivisionID as rioDivisionId,
                    IFNULL(S_RegionalID, '') as S_RegionalID, 
                    IFNULL(S_RegionalName, '') as S_RegionalName,
                    IFNULL(M_BranchCode, '') as M_BranchCode,
                    IFNULL(M_BranchName, '') as M_BranchName,
                    RequestItemOutVerifiedUserID,
                    RequestItemOutVerifiedDate,
                    RequestItemOutApprovedUserID,
                    RequestItemOutApprovedDate
                    FROM request_item_out
                    JOIN s_regional ON S_RegionalID = RequestItemOutS_RegionalID
                    LEFT JOIN m_branch ON M_BranchCode = RequestItemOutM_BranchCode
                    WHERE 
                    RequestItemOutIsActive = 'Y' AND 
                    ( RequestItemOutDate BETWEEN ? AND ? ) AND 
                    ( RequestItemOutStatus = ? OR ? = '' ) AND 
                    ( RequestItemOutNumber LIKE ?)
                    $sqlRIO
                    ORDER BY RequestItemOutNumber DESC
                    LIMIT ? OFFSET ?";

            $exec = $this->db->query($sql, [$startDate, $endDate, $status, $status, '%' . $search . '%', $number_limit, $number_offset]);
            if (!$exec) {
                $this->sys_error_db("select request item out", $this->db);
                exit;
            }

            $rows = $exec->result_array();


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

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

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

            $payload = $this->sys_input;

            // Menggunakan parameter query
            $queryCount = "SELECT count(*) as total
                           FROM purchase_request_direct_detail
                           WHERE PurchaseRequestDirectDetailIsActive = 'Y' 
                           AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ?";
            $exec = $this->db->query($queryCount, [$payload['PRID']]);

            $totalCount = 0;

            if ($exec) {
                $totalCount = $exec->result_array()[0]["total"];
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select purchase request detail", $this->db);;
                exit;
            }

            // Menggunakan parameter query
            $query = "SELECT *, 
                      ROW_NUMBER() OVER(ORDER BY PurchaseRequestDirectDetailID) RowNumber 
                      FROM purchase_request_direct_detail 
                      WHERE PurchaseRequestDirectDetailIsActive = 'Y' 
                      AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ?
                      ORDER BY PurchaseRequestDirectDetailStatus ASC, 
                      PurchaseRequestDirectDetailID ASC";
            $exec = $this->db->query($query, [$payload['PRID']]);

            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select purchase request detail", $this->db);
                exit;
            }

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

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

    function getBranch()
    {
        try {
            $query = "SELECT DISTINCT
                      M_BranchCode,
                      M_BranchName
                      FROM m_branch
                      WHERE M_BranchIsActive = 'Y'
                      ORDER BY M_BranchName ASC";
            $exec = $this->db->query($query, []);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch", $this->db);
                exit;
            }

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

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

    function getRegionalBranchByUser()
    {
        try {
            $userId = $this->sys_user["M_UserID"];

            $query = "SELECT DISTINCT
                      M_BranchCode,
                      M_BranchName
                      FROM m_branch
                      WHERE M_BranchIsActive = 'Y'
                      ORDER BY M_BranchName ASC";
            $exec = $this->db->query($query, []);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch", $this->db);
                exit;
            }

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

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

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

            $this->db->trans_begin();

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $rioID = isset($prm["RIOID"]) ? $prm["RIOID"] : "";

            // Menggunakan parameter query untuk delete
            $sql = "UPDATE request_item_out SET
                    RequestItemOutLastUpdated = NOW(),
                    RequestItemOutUserID = ?,
                    RequestItemOutIsActive = 'N'
                    WHERE RequestItemOutID = ?";

            $deleteParams = [$userId, $rioID];

            $exec = $this->db->query($sql, $deleteParams);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("request delete error", $this->db);
                exit;
            }

            $sql_detail = "UPDATE request_item_out_detail SET
                    RequestItemOutDetailIsActive = 'N',
                    RequestItemOutDetailLastUpdated = NOW(),
                    RequestItemOutDetailUserID = ?
                    WHERE RequestItemOutDetailRequestItemOutID = ?";
            $deleteDetailParams = [$userId, $rioID];

            $execDetail = $this->db->query($sql_detail, $deleteDetailParams);

            if (!$execDetail) {
                $this->db->trans_rollback();
                $this->sys_error_db("request dwtail delete error", $this->db);
                exit;
            }

            // insert log
            $sql_json = "SELECT request_item_out.*, '' as detail
                FROM request_item_out
                WHERE RequestItemOutIsActive = 'N'
                AND RequestItemOutID = ?";
            $qry_json = $this->db->query($sql_json, [$rioID]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json rio");
                exit;
            }
            $row_json = $qry_json->row_array();

            $userdesc = "Request item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di hapus";

            $sql_json_detail = "SELECT request_item_out_detail.* 
                FROM request_item_out_detail
                WHERE RequestItemOutDetailIsActive = 'N'
                AND RequestItemOutDetailRequestItemOutID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$rioID]);
            if ($qry_json_detail) {
                $row_json["detail"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail rio", $this->db);
                exit;
            }

            $data_json = $row_json;

            $sql_log = "INSERT INTO user_activity(
                UserActivityCode,
                UserActivityStatus,
                UserActivityDescription,
                UserActivityRefID,
                UserActivityData,
                UserActivityUserID,
                UserActivityCreated
                ) VALUES('RIO','DELETE',?,?,?,?,NOW())";
            $qry_log = $this->db->query($sql_log, [
                $userdesc,
                $rioID,
                json_encode($data_json),
                $userId
            ]);
            if (!$qry_log) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert log", $this->db);
                exit;
            }

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

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

            $this->db->trans_begin();

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $PRDTotalPrice = intval($payload['PRDAmountRequest']) * intval($payload['PRDEstimationPrice']);

            // Gunakan parameter untuk query existensi
            $query = "SELECT COUNT(*) as exist 
                      FROM purchase_request_direct_detail 
                      WHERE PurchaseRequestDirectDetailIsActive = 'Y' 
                      AND PurchaseRequestDirectDescription = ? 
                      AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ?";
            $existParams = [$payload['PRDDescriptionDetail'], $payload['PRID']];
            $exist = $this->db->query($query, $existParams);

            if ($exist) {
                $row = $exist->row()->exist;
            } else {
                $this->sys_error_db("exist error", $this->db);
                exit;
            }

            if ($row == 0) {
                // Gunakan parameter untuk query insert
                $sql = "INSERT INTO purchase_request_direct_detail(
                        PurchaseRequestDirectDetailPurchaseRequestDirectID,
                        PurchaseRequestDirectDescription,
                        PurchaseRequestDirectDetailAmountRequest,
                        PurchaseRequestDirectDetailAmount,
                        PurchaseRequestDirectDetailEstimationPrice,
                        PurchaseRequestDirectDetailTotalEstimationPrice,
                        PurchaseRequestDirectDetailTotalRealitationPrice,
                        PurchaseRequestDirectDetailStatus,
                        PurchaseRequestDirectDetailIsActive,
                        PurchaseRequestDirectDetailCreated,
                        PurchaseRequestDirectDetailLastUpdated,
                        PurchaseRequestDirectDetailDeleted,
                        PurchaseRequestDirectDetailCreatedUserID,
                        PurchaseRequestDirectDetailLastUpdatedUserID,
                        PurchaseRequestDirectDetailDeletedUserID
                        ) VALUES (?, ?, ?, NULL, ?, ?, NULL, 'Pending', 'Y', NOW(), NULL, NULL, ?, NULL, NULL)";

                $insertParams = [
                    $payload['PRID'],
                    $payload['PRDDescriptionDetail'],
                    $payload['PRDAmountRequest'],
                    $payload['PRDEstimationPrice'],
                    $PRDTotalPrice,
                    $userId
                ];

                $exec = $this->db->query($sql, $insertParams);

                if (!$exec) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("request insert error", $this->db);
                    exit;
                } else {
                    // Gunakan parameter untuk query total harga
                    $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total
                                      FROM purchase_request_direct_detail
                                      WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ?
                                      AND PurchaseRequestDirectDetailIsActive = 'Y'";
                    $totalPriceParams = [$payload['PRID']];
                    $exec = $this->db->query($sqlTotalPrice, $totalPriceParams);
                    $total = 0;

                    if (!$exec) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("order purchase request error", $this->db);
                        exit;
                    } else {
                        $total = $exec->result_array()[0]["Total"];
                    }

                    // Gunakan parameter untuk query update
                    $sql = "UPDATE purchase_request_direct SET
                            PurchaseRequestDirectTotalEstimation = ?,
                            PurchaseRequestLastUpdated = NOW(),
                            PurchaseRequestLastUpdatedUserID = ?
                            WHERE PurchaseRequestDirectID = ?
                            AND PurchaseRequestDirectIsActive = 'Y'";
                    $updateParams = [$total, $userId, $payload['PRID']];
                    $exec = $this->db->query($sql, $updateParams);
                }

                $this->db->trans_commit();

                $result = array("total" => 1, "records" => array("xId" => 0));
                $this->sys_ok($result);
            } else {
                $errors = array();
                if ($row != 0) {
                    array_push($errors, array('msg' => 'Data sudah ada'));
                }

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

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

            $this->db->trans_begin();

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $PRDTotalPrice = intval($payload["PRDAmountRequest"]) * intval($payload["PRDEstimationPrice"]);

            // Gunakan parameter untuk query update
            $sql = "UPDATE purchase_request_direct_detail SET
                    PurchaseRequestDirectDescription = ?,
                    PurchaseRequestDirectDetailAmountRequest = ?,
                    PurchaseRequestDirectDetailEstimationPrice = ?,
                    PurchaseRequestDirectDetailTotalEstimationPrice = ?,
                    PurchaseRequestDirectDetailLastUpdated = NOW(),
                    PurchaseRequestDirectDetailLastUpdatedUserID = ?
                    WHERE PurchaseRequestDirectDetailID = ?";

            $updateParams = [
                $payload["PRDDescriptionDetail"],
                $payload["PRDAmountRequest"],
                $payload["PRDEstimationPrice"],
                $PRDTotalPrice,
                $userId,
                $payload["PRDID"]
            ];

            $exec = $this->db->query($sql, $updateParams);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("request update error", $this->db);
                exit;
            } else {
                // Gunakan parameter untuk query total harga
                $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total
                                  FROM purchase_request_direct_detail
                                  WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ?
                                  AND PurchaseRequestDirectDetailIsActive = 'Y'";
                $totalPriceParams = [$payload["PRID"]];
                $exec = $this->db->query($sqlTotalPrice, $totalPriceParams);
                $total = 0;

                if (!$exec) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("order purchase request error", $this->db);
                    exit;
                } else {
                    $total = $exec->result_array()[0]["Total"];
                }

                // Gunakan parameter untuk query update total
                $sql = "UPDATE purchase_request_direct SET
                        PurchaseRequestDirectTotalEstimation = ?,
                        PurchaseRequestLastUpdated = NOW(),
                        PurchaseRequestLastUpdatedUserID = ?
                        WHERE PurchaseRequestDirectID = ?
                        AND PurchaseRequestDirectIsActive = 'Y'";
                $updateTotalParams = [$total, $userId, $payload["PRID"]];
                $exec = $this->db->query($sql, $updateTotalParams);
            }

            $this->db->trans_commit();

            $result = array("total" => 1, "records" => array("xId" => $payload["PRDID"]));
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $this->db->trans_begin();

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Gunakan parameter untuk query delete
            $sql = "UPDATE purchase_request_direct_detail SET
                    PurchaseRequestDirectDetailDeleted = NOW(),
                    PurchaseRequestDirectDetailDeletedUserID = ?,
                    PurchaseRequestDirectDetailIsActive = 'N'
                    WHERE PurchaseRequestDirectDetailID = ?";
            $deleteParams = [$userId, $payload["PRDID"]];
            $exec = $this->db->query($sql, $deleteParams);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("request delete error", $this->db);
                exit;
            } else {
                // Gunakan parameter untuk query total harga
                $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total
                                  FROM purchase_request_direct_detail
                                  WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ?
                                  AND PurchaseRequestDirectDetailIsActive = 'Y'";
                $totalPriceParams = [$payload["PRID"]];
                $exec = $this->db->query($sqlTotalPrice, $totalPriceParams);
                $total = 0;

                if (!$exec) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("order purchase request error", $this->db);
                    exit;
                } else {
                    $total = $exec->result_array()[0]["Total"] ?? 0;
                }

                // Gunakan parameter untuk query update total
                $sql = "UPDATE purchase_request_direct SET
                        PurchaseRequestDirectTotalEstimation = ?,
                        PurchaseRequestLastUpdated = NOW(),
                        PurchaseRequestLastUpdatedUserID = ?
                        WHERE PurchaseRequestDirectID = ?
                        AND PurchaseRequestDirectIsActive = 'Y'";
                $updateTotalParams = [$total, $userId, $payload["PRID"]];
                $exec = $this->db->query($sql, $updateTotalParams);
            }

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

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

            $this->db->trans_begin();

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Gunakan parameter untuk query update detail
            $sqlDetail = "UPDATE purchase_request_direct_detail SET
                          PurchaseRequestDirectDetailLastUpdated = NOW(),
                          PurchaseRequestDirectDetailLastUpdatedUserID = ?
                          WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ?
                          AND PurchaseRequestDirectDetailIsActive = 'Y'
                          AND PurchaseRequestDirectDetailStatus = 'Pending'";
            $detailParams = [$userId, $payload["PRID"]];
            $exec = $this->db->query($sqlDetail, $detailParams);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("order purchase request error", $this->db);
                exit;
            }

            // Gunakan parameter untuk query update status
            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDirectStatus = 'Pending',
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = ?
                    WHERE PurchaseRequestDirectID = ?
                    AND PurchaseRequestDirectIsActive = 'Y'";
            $updateParams = [$userId, $payload["PRID"]];
            $exec = $this->db->query($sql, $updateParams);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("order purchase request error", $this->db);
                exit;
            }

            $this->db->trans_commit();

            // Gunakan parameter untuk query select
            $sql = "SELECT *, 
                    ROW_NUMBER() OVER(ORDER BY PurchaseRequestDirectNumber) RowNumber 
                    FROM purchase_request_direct 
                    WHERE PurchaseRequestDirectIsActive = 'Y' 
                    AND PurchaseRequestCreatedUserID = ?
                    AND PurchaseRequestDirectID = ?";
            $selectParams = [$userId, $payload["PRID"]];
            $exec = $this->db->query($sql, $selectParams);

            $row = [];
            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("order purchase request error", $this->db);
                exit;
            } else {
                $row = $exec->result_array();
            }
            $result = array("total" => 1, "records" => $row);
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            // $userId = $this->sys_user["M_UserID"];
            $prm = $this->sys_input;
            $userId = $prm["userId"];

            $rows = [];

            $query = "SELECT DISTINCT
                      DivisionID,
                      DivisionCode,
                      DivisionName
                      FROM division
                      WHERE DivisionIsActive = 'Y'
                      ORDER BY DivisionName ASC";
            $exec = $this->db->query($query);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select division", $this->db);
                exit;
            }

            if ($prm["act"] == "edit") {
                $sql = "SELECT DISTINCT
                      DivisionID,
                      DivisionCode,
                      DivisionName
                    FROM division 
                    JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID
                    WHERE DivisionIsActive = 'Y'
                    AND DivisionID = ?
                    ORDER BY M_UserDivisionID DESC
                    LIMIT 1";
                $exec = $this->db->query($sql, [$prm["DivisionID"]]);
                if ($exec) {
                    $row = $exec->result_array();
                } else {
                    $this->sys_error_db("select division", $this->db);
                    exit;
                }
            } else {
                $sql = "SELECT DISTINCT
                      DivisionID,
                      DivisionCode,
                      DivisionName
                    FROM division 
                    JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID AND M_UserDivisionM_UserID = ?
                    WHERE DivisionIsActive = 'Y'
                    ORDER BY M_UserDivisionID DESC
                    LIMIT 1";
                $exec = $this->db->query($sql, [$userId]);
                if ($exec) {
                    $row = $exec->result_array();
                } else {
                    $this->sys_error_db("select division by user", $this->db);
                    exit;
                }
            }

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

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

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

            $prm = $this->sys_input;
            $division = isset($prm["division"]) ? $prm["division"] : "";

            $rows = [];
            $rows[] = array("Nat_GroupID" => "", "Nat_GroupCode" => "", "Nat_GroupName" => "Semua Grup", "subGroups" => [
                array("Nat_SubGroupID" => "", "Nat_SubGroupCode" => "", "Nat_SubGroupName" => "Semua Sub Grup")
            ]);

            $sql = "SELECT DISTINCT
                    Nat_GroupID,
                    Nat_GroupCode,
                    Nat_GroupName,
                    '' as subGroups
                    FROM nat_group
                    JOIN m_item ON M_ItemNat_GroupID = Nat_GroupID AND M_ItemIsActive = 'Y'
                    JOIN m_itemdivision ON M_ItemDivisionM_ItemID = M_ItemID AND M_ItemDivisionIsActive = 'Y' AND (M_ItemDivisionDivisionID = ? OR ? = '')
                    WHERE Nat_GroupIsActive = 'Y'
                    ORDER BY Nat_GroupID ASC";

            $query = $this->db->query($sql, [$division, $division]);

            if (!$query) {
                $this->sys_error_db("item group list", $this->db);
                exit;
            }

            $rst = $query->result_array();
            foreach ($rst as $key => $row) {
                $row["subGroups"] = array(
                    array("Nat_SubGroupID" => "", "Nat_SubGroupCode" => "", "Nat_SubGroupName" => "Semua Sub Grup")
                );
                if ($row["Nat_GroupID"] != "") {
                    $sqlSubGroup = "SELECT DISTINCT
                                Nat_SubGroupID,
                                Nat_SubGroupCode,
                                Nat_SubGroupName
                                FROM nat_subgroup
                                WHERE Nat_SubGroupIsActive = 'Y'
                                AND Nat_SubGroupNat_GroupID = ?
                                ORDER BY Nat_SubGroupID ASC";
                    $querySubGroup = $this->db->query($sqlSubGroup, [$row["Nat_GroupID"]]);
                    if (!$querySubGroup) {
                        $this->sys_error_db("item sub group list", $this->db);
                        exit;
                    }
                    $subGroups = $querySubGroup->result_array();
                    foreach ($subGroups as $keySubGroup => $subGroup) {
                        $row["subGroups"][] = $subGroup;
                    }
                }
                $rows[] = $row;
            }

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

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




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

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";
            $division = isset($prm["division"]) ? $prm["division"] : "";
            $itemGroup = isset($prm["itemGroup"]) ? $prm["itemGroup"] : "";
            $itemSubGroup = isset($prm["itemSubGroup"]) ? $prm["itemSubGroup"] : "";
            $unitPurchase = isset($prm["unitPurchase"]) ? $prm["unitPurchase"] : "purchase";
            $currentPage = isset($prm["currentPage"]) ? $prm["currentPage"] : 1;
            $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : 0;

            $params = [];
            // Menambahkan parameter untuk unitPurchase
            $params[] = $unitPurchase;
            $params[] = $unitPurchase;

            $filterDivision = "";
            if ($division != "") {
                $filterDivision = "JOIN m_itemdivision ON M_ItemDivisionM_ItemID = M_ItemID AND M_ItemDivisionIsActive = 'Y' AND (M_ItemDivisionDivisionID = ? OR ? = '')";
                $params[] = $division;
                $params[] = $division;
            }

            $filterItemGroup = "";
            if ($itemGroup != "") {
                $filterItemGroup = "JOIN nat_group ON M_ItemNat_GroupID = Nat_GroupID AND Nat_GroupIsActive = 'Y' AND (Nat_GroupID = ? OR ? = '')";
                $params[] = $itemGroup;
                $params[] = $itemGroup;
            }

            $filterItemSubGroup = "";
            if ($itemSubGroup != "") {
                $filterItemSubGroup = "JOIN nat_subgroup ON M_ItemNat_SubGroupID = Nat_SubGroupID AND Nat_SubGroupIsActive = 'Y' AND (Nat_SubGroupID = ? OR ? = '')";
                $params[] = $itemSubGroup;
                $params[] = $itemSubGroup;
            }


            $params[] = '%' . $search . '%';

            $limit = 10;
            $offset = ($currentPage - 1) * $limit;


            $sql = "SELECT COUNT(*) as total FROM (
                        SELECT
                        DISTINCT M_ItemID 
                        FROM m_item
                        JOIN itemunitmap ON ItemUnitMapM_ItemID = M_ItemID AND 
                            ((ItemUnitMapIsPurchase = 'Y' AND ? = 'purchase') OR
                            (ItemUnitMapIsBase = 'Y' AND ? = 'base')) AND 
                            ItemUnitMapIsActive = 'Y'
                        JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND 
                            ItemUnitIsActive = 'Y'
                        $filterDivision
                        $filterItemGroup
                        $filterItemSubGroup
                        WHERE M_ItemIsActive = 'Y' AND 
                        M_ItemItem_CategoryID = '1'
                        AND M_ItemDesc LIKE ?
                    ) as item";

            $query = $this->db->query($sql, $params);
            if (!$query) {
                $this->sys_error_db("item list", $this->db);
                exit;
            }

            $row = $query->row_array();
            $total = ceil($row["total"] / $limit);

            $params[] = $limit;
            $params[] = $offset;

            $sql = "SELECT
                    DISTINCT M_ItemID as itemId,
                    M_ItemCode as itemCode,
                    M_ItemDesc as itemDesc,
                    0 as qty,
                    ItemUnitID as unitId,
                    ItemUnitCode as unitCode,
                    ItemUnitName as unitName,
                    0 as detailId,
                    'draft' as status,
                    0 as stockDivisi,
                    0 as stockWarehouse
                    FROM m_item
                    JOIN itemunitmap ON ItemUnitMapM_ItemID = M_ItemID AND 
                        ((ItemUnitMapIsPurchase = 'Y' AND ? = 'purchase') OR
                        (ItemUnitMapIsBase = 'Y' AND ? = 'base')) AND 
                        ItemUnitMapIsActive = 'Y'
                    JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND 
                        ItemUnitIsActive = 'Y'
                    $filterDivision
                    $filterItemGroup
                    $filterItemSubGroup
                    WHERE M_ItemIsActive = 'Y' AND 
                    M_ItemItem_CategoryID = '1'
                    AND M_ItemDesc LIKE ?
                    ORDER BY M_ItemDesc ASC
                    LIMIT ? OFFSET ?";

            // Parameter akhir yang digunakan untuk query
            $searchParam = $params;

            $query = $this->db->query($sql, $searchParam);

            if (!$query) {
                $this->sys_error_db("item list", $this->db);
                //$this->sys_error($this->db->error());
                exit;
            }
            // echo $this->db->last_query();
            // exit;

            $rows = $query->result_array();
            if (count($rows) > 0) {
                foreach ($rows as $key => $row) {
                    $rows[$key]["isSelected"] = $row["isSelected"] == "Y" ? true : false;

                    $sqldivisi = "SELECT StockID,
                            StockItemPrice,
                            StockBatchNo,
                            StockWarehouseID,
                            StockItemID,
                            SUM(StockQty) as stockDivisi
                            FROM stock
                            JOIN m_item ON StockItemID = M_ItemID
                                AND M_ItemIsActive = 'Y'
                            JOIN m_itemdivision ON M_ItemID = M_ItemDivisionM_ItemID AND M_ItemDivisionIsActive = 'Y' 
                            AND M_ItemDivisionDivisionID = ?
                            WHERE StockItemID = ?
                            AND StockItemUnitID = ?";
                    $qrydivisi = $this->db->query($sqldivisi, [
                        $division,
                        $row['itemId'],
                        $row['unitId']
                    ]);
                    if (!$qrydivisi) {
                        $this->sys_error_db("get stock divisi error", $this->db);
                        exit;
                    }

                    $rowstokdivisi = $qrydivisi->row_array();
                    $rows[$key]["stockDivisi"] = $rowstokdivisi["stockDivisi"];

                    $sqlwarehouse = "SELECT StockID,
                            StockItemPrice,
                            StockBatchNo,
                            StockWarehouseID,
                            StockItemID,
                            SUM(StockQty) as stockWarehouse
                            FROM stock
                            WHERE StockItemID = ?
                            AND StockItemUnitID = ?
                            AND StockWarehouseID = ?";
                    $qrywarehouse = $this->db->query($sqlwarehouse, [
                        $row['itemId'],
                        $row['unitId'],
                        $warehouseID
                    ]);
                    if (!$qrywarehouse) {
                        $this->sys_error_db("get stock gudang error", $this->db);
                        exit;
                    }

                    $rowstokwarehouse = $qrywarehouse->row_array();
                    $rows[$key]["stockWarehouse"] = $rowstokwarehouse["stockWarehouse"];
                }
            }

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

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

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

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";

            // Menggunakan parameter query untuk pencarian unit
            $sql = "SELECT 
                    ItemUnitID,
                    ItemUnitCode,
                    ItemUnitName,
                    ItemUnitCreated,
                    ItemUnitLastUpdated,
                    ItemUnitIsActive,
                    ItemUnitUserID
                    FROM itemunit 
                    WHERE ItemUnitIsActive = 'Y'
                    AND ItemUnitName LIKE ?
                    ORDER BY ItemUnitName ASC";

            $searchParam = ['%' . $search . '%'];

            $query = $this->db->query($sql, $searchParam);

            if (!$query) {
                $this->sys_error_db("item unit list", $this->db);
                exit;
            }

            $rows = $query->result_array();

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

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

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

            $prm = $this->sys_input;
            $prId = isset($prm["prId"]) ? $prm["prId"] : "";

            if ($prId == "") {
                $this->sys_error("Invalid PR ID");
                exit;
            }


            $sql = "SELECT PurchaseRequestDetailID as detailId,
                    PurchaseRequestDetailM_ItemID as itemId,
                    M_ItemCode as itemCode,
                    M_ItemDesc as itemDesc,
                    PurchaseRequestDetailItemUnitID as unitId,
                    ItemUnitCode as unitCode,
                    ItemUnitName as unitName,
                    PurchaseRequestDetailQty as qty,
                    PurchaseRequestDetailStatus as status,
                    PurchaseRequestDetailNote as note
                    FROM purchase_request_detail 
                    JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID AND M_ItemIsActive = 'Y'
                    JOIN itemunit ON ItemUnitID = PurchaseRequestDetailItemUnitID AND ItemUnitIsActive = 'Y'
                    WHERE 
                        PurchaseRequestDetailPurchaseRequestID = ? AND
                        PurchaseRequestDetailIsActive = 'Y'";
            $query = $this->db->query($sql, [$prId]);

            if (!$query) {
                $this->sys_error_db("item list", $this->db);
                exit;
            }

            $rows = $query->result_array();

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

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

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

            $prm = $this->sys_input;
            $itemId = isset($prm["itemId"]) ? $prm["itemId"] : "";

            if ($itemId == "") {
                $this->sys_error("Invalid Item ID");
                exit;
            }

            $sql = "SELECT 
                    DISTINCT ItemUnitID as unitId,
                    ItemUnitCode as unitCode,
                    ItemUnitName as unitName
                    FROM itemunitmap 
                    JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND ItemUnitIsActive = 'Y'
                    WHERE ItemUnitMapM_ItemID = ?
                    AND ItemUnitMapIsActive = 'Y'";
            $query = $this->db->query($sql, [$itemId]);

            if (!$query) {
                $this->sys_error_db("item unit list", $this->db);
                exit;
            }

            $rows = $query->result_array();

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

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

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

            $userId = $this->sys_user["M_UserID"];
            $prm = $this->sys_input;
            $itemCategory = isset($prm["itemcategory"]) ? $prm["itemcategory"] : "1";
            $rioDateUse = isset($prm["RIODateUse"]) ? $prm["RIODateUse"] : "";
            $rioDateUse = date("Y-m-d", strtotime($rioDateUse));
            if ($rioDateUse == "" || $rioDateUse == null) {
                $this->sys_error("Invalid Date Use");
                exit;
            }
            $rioRegional = isset($prm["RIORegional"]) ? $prm["RIORegional"] : "";
            if ($rioRegional == "" || $rioRegional == null) {
                $this->sys_error("Invalid Regional");
                exit;
            }
            $rioBranch = isset($prm["RIOBranch"]) ? $prm["RIOBranch"] : "";
            if ($rioBranch == "" || $rioBranch == null) {
                $this->sys_error("Invalid Branch");
                exit;
            }
            $rioWarehouse = isset($prm["RIOWarehouse"]) ? $prm["RIOWarehouse"] : "";
            if ($rioWarehouse == "" || $rioWarehouse == null) {
                $this->sys_error("Warehouse masih kosong");
                exit;
            }
            $rioDivision = isset($prm["RIODivision"]) ? $prm["RIODivision"] : "";
            if ($rioDivision == "" || $rioDivision == null) {
                $this->sys_error("Division masih kosong");
                exit;
            }
            $rioDescription = isset($prm["RIODescription"]) ? $prm["RIODescription"] : "";
            $items = isset($prm["items"]) ? $prm["items"] : [];
            if (count($items) == 0) {
                $this->sys_error("PR Items cannot be empty");
                exit;
            }

            $this->db->trans_begin();

            $sql = "INSERT INTO request_item_out ( 
                                    RequestItemOutNumber,
                                    RequestItemOutDate,
                                    RequestItemOutWarehouseID,
                                    RequestItemOutS_RegionalID, 
                                    RequestItemOutM_BranchCode, 
                                    RequestItemOutNote, 
                                    RequestItemOutDivisionID,
                                    RequestItemOutStatus,
                                    RequestItemOutCreated, 
                                    RequestItemOutUserID) 
                    VALUES (fn_numbering('RIO'), ?, ?, ?, ?, ?, ?, 'Draft', ?, ?)";
            $query = $this->db->query($sql, [
                $rioDateUse,
                $rioWarehouse,
                $rioRegional,
                $rioBranch,
                $rioDescription,
                $rioDivision,
                date("Y-m-d H:i:s"),
                $userId
            ]);

            if (!$query) {
                $this->db->trans_rollback();
                $this->sys_error_db("request item out", $this->db);
                exit;
            }

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

            foreach ($items as $key => $item) {
                $sql = "INSERT INTO request_item_out_detail (
                                RequestItemOutDetailRequestItemOutID, 
                                RequestItemOutDetailM_ItemID, 
                                RequestItemOutDetailItemUnitID, 
                                RequestItemOutDetailQty, 
                                RequestItemOutDetailStatus,
                                RequestItemOutDetailCreated,
                                RequestItemOutDetailUserID) 
                        VALUES (?, ?, ?, ?, 'Draft', ?, ?)";
                $query = $this->db->query($sql, [
                    $rioId,
                    $item["itemId"],
                    $item["unitId"],
                    intval($item["qty"]),
                    date("Y-m-d H:i:s"),
                    $userId
                ]);
                if (!$query) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("request detail item out", $this->db);
                    exit;
                }
            }

            // insert log
            $id = $rioId;
            $sql_json = "SELECT request_item_out.*, '' as detail
                    FROM request_item_out
                    WHERE RequestItemOutIsActive = 'Y'
                    AND RequestItemOutID = ?";
            $qry_json = $this->db->query($sql_json, [$id]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json rio");
                exit;
            }
            $row_json = $qry_json->row_array();

            $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah dibuat";

            $sql_json_detail = "SELECT request_item_out_detail.* 
                FROM request_item_out_detail
                WHERE RequestItemOutDetailIsActive = 'Y'
                AND RequestItemOutDetailRequestItemOutID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$id]);
            if ($qry_json_detail) {
                $row_json["detail"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail rio", $this->db);
                exit;
            }

            $data_json = $row_json;

            $sql_log = "INSERT INTO user_activity(
                    UserActivityCode,
                    UserActivityStatus,
                    UserActivityDescription,
                    UserActivityRefID,
                    UserActivityData,
                    UserActivityUserID,
                    UserActivityCreated
                    ) VALUES('RIO','Draft',?,?,?,?,NOW())";
            $qry_log = $this->db->query($sql_log, [
                $userdesc,
                $id,
                json_encode($data_json),
                $userId
            ]);
            if (!$qry_log) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert log", $this->db);
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok("Request item out created successfully");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }


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

            $userId = $this->sys_user["M_UserID"];
            $prm = $this->sys_input;
            $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : 0;
            $division = isset($prm["division"]) ? $prm["division"] : "";
            $requestId = isset($prm["requestId"]) ? $prm["requestId"] : "";
            if ($requestId == "" || $requestId == null) {
                $this->sys_error("Invalid Request ID");
                exit;
            }

            $sql = "SELECT
                    RequestItemOutDetailID as detailId,
                    RequestItemOutDetailM_ItemID as itemId,
                    M_ItemCode as itemCode,
                    M_ItemDesc as itemDesc,
                    RequestItemOutDetailItemUnitID as unitId,
                    ItemUnitCode as unitCode,
                    ItemUnitName as unitName,
                    RequestItemOutDetailQty as qty,
                    RequestItemOutDetailStatus as status,
                    0 as stockDivisi,
                    0 as stockWarehouse
                    FROM request_item_out_detail
                    JOIN m_item ON M_ItemID = RequestItemOutDetailM_ItemID AND M_ItemIsActive = 'Y'
                    JOIN itemunit ON ItemUnitID = RequestItemOutDetailItemUnitID AND ItemUnitIsActive = 'Y'
                    WHERE RequestItemOutDetailRequestItemOutID = ? AND RequestItemOutDetailIsActive = 'Y'";
            $query = $this->db->query($sql, [$requestId]);
            if (!$query) {
                $this->sys_error_db("request item out detail", $this->db);
                exit;
            }

            $rows = $query->result_array();
            if (count($rows) > 0) {
                foreach ($rows as $key => $row) {
                    $sqldivisi = "SELECT StockID,
                            StockItemPrice,
                            StockBatchNo,
                            StockWarehouseID,
                            StockItemID,
                            SUM(StockQty) as stockDivisi
                            FROM stock
                            JOIN m_item ON StockItemID = M_ItemID
                                AND M_ItemIsActive = 'Y'
                            JOIN m_itemdivision ON M_ItemID = M_ItemDivisionM_ItemID AND M_ItemDivisionIsActive = 'Y' 
                            AND M_ItemDivisionDivisionID = ?
                            WHERE StockItemID = ?
                            AND StockItemUnitID = ?";
                    $qrydivisi = $this->db->query($sqldivisi, [
                        $division,
                        $row['itemId'],
                        $row['unitId']
                    ]);
                    if (!$qrydivisi) {
                        $this->sys_error_db("get stock divisi error", $this->db);
                        exit;
                    }

                    $rowstokdivisi = $qrydivisi->row_array();
                    $rows[$key]["stockDivisi"] = $rowstokdivisi["stockDivisi"];

                    $sqlwarehouse = "SELECT StockID,
                            StockItemPrice,
                            StockBatchNo,
                            StockWarehouseID,
                            StockItemID,
                            SUM(StockQty) as stockWarehouse
                            FROM stock
                            WHERE StockItemID = ?
                            AND StockItemUnitID = ?
                            AND StockWarehouseID = ?";
                    $qrywarehouse = $this->db->query($sqlwarehouse, [
                        $row['itemId'],
                        $row['unitId'],
                        $warehouseID
                    ]);
                    if (!$qrywarehouse) {
                        $this->sys_error_db("get stock gudang error", $this->db);
                        exit;
                    }

                    $rowstokwarehouse = $qrywarehouse->row_array();
                    $rows[$key]["stockWarehouse"] = $rowstokwarehouse["stockWarehouse"];
                }
            }

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

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

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

            $userId = $this->sys_user["M_UserID"];
            $prm = $this->sys_input;
            $rioId = isset($prm["RIOID"]) ? $prm["RIOID"] : "";
            $itemCategory = isset($prm["itemcategory"]) ? $prm["itemcategory"] : "1";
            $rioDateUse = isset($prm["RIODateUse"]) ? $prm["RIODateUse"] : "";
            $rioDateUse = date("Y-m-d", strtotime($rioDateUse));
            $dateRequest = date("Y-m-d");
            if ($rioDateUse == "" || $rioDateUse == null) {
                $this->sys_error("Invalid Date Use");
                exit;
            }
            $rioRegional = isset($prm["RIORegional"]) ? $prm["RIORegional"] : "";
            if ($rioRegional == "" || $rioRegional == null) {
                $this->sys_error("Invalid Regional");
                exit;
            }
            $rioBranch = isset($prm["RIOBranch"]) ? $prm["RIOBranch"] : "";
            if ($rioBranch == "" || $rioBranch == null) {
                $this->sys_error("Invalid Branch");
                exit;
            }
            $rioWarehouse = isset($prm["RIOWarehouse"]) ? $prm["RIOWarehouse"] : "";
            if ($rioWarehouse == "" || $rioWarehouse == null) {
                $this->sys_error("Warehouse masih kosong");
                exit;
            }
            $rioDivision = isset($prm["RIODivision"]) ? $prm["RIODivision"] : "";
            if ($rioDivision == "" || $rioDivision == null) {
                $this->sys_error("Division masih kosong");
                exit;
            }
            $rioDescription = isset($prm["RIODescription"]) ? $prm["RIODescription"] : "";
            $items = isset($prm["items"]) ? $prm["items"] : [];
            if (count($items) == 0) {
                $this->sys_error("PR Items cannot be empty");
                exit;
            }

            $this->db->trans_begin();
            $status = '';
            $statusdetail = '';
            if ($prm["act"] == "sendrequest") {
                $status = ", RequestItemOutStatus = 'Send Request'";
                $statusdetail = ", RequestItemOutDetailStatus = 'Send Request'";
            }

            $sql = "UPDATE request_item_out SET 
                        RequestItemOutDate = ?,
                        RequestItemOutWarehouseID = ?,
                        RequestItemOutS_RegionalID = ?, 
                        RequestItemOutM_BranchCode = ?, 
                        RequestItemOutNote = ?, 
                        RequestItemOutDivisionID = ?,  
                        RequestItemOutLastUpdated = ?, 
                        RequestItemOutUserID = ?
                        $status
                    WHERE RequestItemOutID = ?";
            $params = [
                $rioDateUse,
                $rioWarehouse,
                $rioRegional,
                $rioBranch,
                $rioDescription,
                $rioDivision,
                date("Y-m-d H:i:s"),
                $userId,
                $rioId
            ];

            $query = $this->db->query($sql, $params);

            if (!$query) {
                $this->db->trans_rollback();
                $this->sys_error_db("request item out update", $this->db);
                exit;
            }

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

            foreach ($items as $key => $item) {
                if ($item["detailId"] == 0 || $item["detailId"] == "0") {
                    $sql = "INSERT INTO request_item_out_detail (
                        RequestItemOutDetailRequestItemOutID, 
                        RequestItemOutDetailM_ItemID, 
                        RequestItemOutDetailItemUnitID, 
                        RequestItemOutDetailQty, 
                        RequestItemOutDetailStatus,
                        RequestItemOutDetailCreated,
                        RequestItemOutDetailUserID) 
                        VALUES (?, ?, ?, ?, 'Draft', ?, ?)";
                    $query = $this->db->query($sql, [
                        $rioId,
                        $item["itemId"],
                        $item["unitId"],
                        $item["qty"],
                        date("Y-m-d H:i:s"),
                        $userId
                    ]);
                    if (!$query) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("request detail item out", $this->db);
                        exit;
                    }
                } else {
                    $sql = "UPDATE request_item_out_detail 
                            SET 
                            RequestItemOutDetailM_ItemID = ?,
                            RequestItemOutDetailItemUnitID = ?,
                            RequestItemOutDetailQty = ?,
                            RequestItemOutDetailLastUpdated = ?,
                            RequestItemOutDetailUserID = ?
                            $statusdetail
                            WHERE RequestItemOutDetailID = ?";
                    $query = $this->db->query($sql, [
                        $item["itemId"],
                        $item["unitId"],
                        $item["qty"],
                        date("Y-m-d H:i:s"),
                        $userId,
                        $item["detailId"]
                    ]);
                    if (!$query) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("request item out detail update", $this->db);
                        exit;
                    }
                }
            }

            // insert log
            $sql_json = "SELECT request_item_out.*, '' as detail
            FROM request_item_out
            WHERE RequestItemOutIsActive = 'Y'
            AND RequestItemOutID = ?";
            $qry_json = $this->db->query($sql_json, [$rioId]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json rio");
                exit;
            }
            $row_json = $qry_json->row_array();

            $sql_json_detail = "SELECT request_item_out_detail.* 
            FROM request_item_out_detail
            WHERE RequestItemOutDetailIsActive = 'Y'
            AND RequestItemOutDetailRequestItemOutID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$rioId]);
            if ($qry_json_detail) {
                $row_json["detail"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail rio", $this->db);
                exit;
            }

            $data_json = $row_json;

            if ($prm["act"] == "sendrequest") {
                $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " mengirimkan permintaan request";
                $sql_log = "INSERT INTO user_activity(
                    UserActivityCode,
                    UserActivityStatus,
                    UserActivityDescription,
                    UserActivityRefID,
                    UserActivityData,
                    UserActivityUserID,
                    UserActivityCreated
                    ) VALUES('RIO','Send Request',?,?,?,?,NOW())";
                $qry_log = $this->db->query($sql_log, [
                    $userdesc,
                    $rioId,
                    json_encode($data_json),
                    $userId
                ]);
                if (!$qry_log) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("insert log sendrequest", $this->db);
                    exit;
                }
            } else {
                $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah diedit";
                $sql_log = "INSERT INTO user_activity(
                    UserActivityCode,
                    UserActivityStatus,
                    UserActivityDescription,
                    UserActivityRefID,
                    UserActivityData,
                    UserActivityUserID,
                    UserActivityCreated
                    ) VALUES('RIO','UPDATE',?,?,?,?,NOW())";
                $qry_log = $this->db->query($sql_log, [
                    $userdesc,
                    $rioId,
                    json_encode($data_json),
                    $userId
                ]);
                if (!$qry_log) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("insert log update", $this->db);
                    exit;
                }
            }

            if ($prm["act"] == "sendrequest") {
                // tambahan fungsi notif ke approver
                $this->saveNotification($userId, $dateRequest, $row_json['RequestItemOutNumber'], $rioId, $rioBranch, $rioDivision);
            }

            $this->db->trans_commit();
            if ($prm["act"] == "sendrequest") {
                $this->sys_ok("Send request successfully");
            } else {
                $this->sys_ok("Request item out updated successfully");
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            $regionalId = $prm["regionalId"];
            $branchCode = $prm["branchCode"];
            $filterBranch = "";
            if (!$branchCode == "") {
                $filterBranch .= " AND M_BranchCode = '{$branchCode}'";
            }

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

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("get warehouse", $this->db);
                exit;
            }
            $rows = $qry->row_array();
            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $payload = $this->sys_input;
            $user = $this->sys_user;
            $regionalID = $user['S_RegionalID'];
            $branchCode = $user['M_BranchCode'];
            $loginType = $user['M_UserLocationFlag'];
            $userID = $user['M_UserID'];
            $sql = "SELECT m_approve_level.* FROM m_user
                JOIN m_approve_level
                ON M_UserM_ApproveLevelID = M_ApproveLevelID
                WHERE M_UserID = ?";
            $qry = $this->db->query($sql, [$userID]);
            if (!$qry) {
                $this->sys_error_db("Error cek approval level");
                exit;
            }
            $approvalLevel = $qry->result_array();
            if (count($approvalLevel) == 0) {
                $result = array(
                    'total' => 0,
                    'records' => []
                );
                $this->sys_ok($result);
                exit;
            } else {
                $result = array(
                    "total" => 1,
                    "records" => $approvalLevel,
                    "sql" => $this->db->last_query()
                );

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

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

            $payload = $this->sys_input;
            $user = $this->sys_user;
            $regionalID = $user['S_RegionalID'];
            $branchCode = $user['M_BranchCode'];
            $loginType = $user['M_UserLocationFlag'];
            $userID = $user['M_UserID'];
            $sql = "SELECT M_UserDivisionID,
                        M_UserDivisionM_UserID,
                        M_UserDivisionDivisionID,
                        M_UserUsername,
                        DivisionName
                        FROM m_user  
                        JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID
                        AND M_UserDivisionIsActive = 'Y'
                        JOIN division ON M_UserDivisionDivisionID = DivisionID
                        AND DivisionIsActive = 'Y'
                        WHERE M_UserIsActive = 'Y'
                        AND M_UserDivisionM_UserID = ?";
            $qry = $this->db->query($sql, [$userID]);
            if (!$qry) {
                $this->sys_error_db("Error cek approval level");
                exit;
            }
            $approvalDivision = $qry->result_array();
            if (count($approvalDivision) == 0) {
                $result = array(
                    'total' => 0,
                    'records' => []
                );
                $this->sys_ok($result);
                exit;
            } else {
                $result = array(
                    "total" => 1,
                    "records" => $approvalDivision,
                    "sql" => $this->db->last_query()
                );

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

    function approveRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];


            if ($prm["categoryApprove"] == 'K') {
                $sql = "UPDATE request_item_out SET
                        RequestItemOutStatus = 'Process',
                        RequestItemOutApprovedDate = NOW(),
                        RequestItemOutApprovedUserID = ?,
                        RequestItemOutLastUpdated = NOW()
                        WHERE RequestItemOutID = ?";
                $qry = $this->db->query($sql, [
                    $userId,
                    $prm["RIOID"]
                ]);
                if (!$qry) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Approve request item out kacab error", $this->db);
                    exit;
                }

                $sqlDetail = "UPDATE request_item_out_detail SET
                        RequestItemOutDetailStatus = 'Process',
                        RequestItemOutDetailLastUpdated = NOW(),
                        RequestItemOutDetailUserID = ?
                        WHERE RequestItemOutDetailRequestItemOutID = ?";
                $qryDetail = $this->db->query($sqlDetail, [
                    $userId,
                    $prm["RIOID"]
                ]);
                if (!$qryDetail) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("update request item out detail error", $this->db);
                    exit;
                }
            } else if ($prm["categoryApprove"] == "M") {
                $sql = "UPDATE request_item_out SET
                        RequestItemOutVerifiedDate = NOW(),
                        RequestItemOutVerifiedUserID = ?,
                        RequestItemOutLastUpdated = NOW()
                        WHERE RequestItemOutID = ?";
                $qry = $this->db->query($sql, [
                    $userId,
                    $prm["RIOID"]
                ]);
                if (!$qry) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Approve request item out manager error", $this->db);
                    exit;
                }
            }

            // insert log
            $sql_json = "SELECT request_item_out.*, '' as detail
                    FROM request_item_out
                    WHERE RequestItemOutIsActive = 'Y'
                    AND RequestItemOutID = ?";
            $qry_json = $this->db->query($sql_json, [$prm["RIOID"]]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json rio error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di approve";

            $sql_json_detail = "SELECT request_item_out_detail.* 
                        FROM request_item_out_detail
                        WHERE RequestItemOutDetailIsActive = 'Y'
                        AND RequestItemOutDetailRequestItemOutID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$prm["RIOID"]]);
            if ($qry_json_detail) {
                $row_json["detail"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail rio error", $this->db);
                exit;
            }

            $data_json = $row_json;

            $sql_log = "INSERT INTO user_activity(
                        UserActivityCode,
                        UserActivityStatus,
                        UserActivityDescription,
                        UserActivityRefID,
                        UserActivityData,
                        UserActivityUserID,
                        UserActivityCreated
                    ) VALUES('RIO','Process',?,?,?,?,NOW())";
            $qry_log = $this->db->query($sql_log, [
                $userdesc,
                $prm["RIOID"],
                json_encode($data_json),
                $userId
            ]);
            if (!$qry_log) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert user activity error", $this->db);
                exit;
            }

            $this->readNotif($userId, $prm["RIOID"]);

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

    function rejectRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];


            $sql = "UPDATE request_item_out SET
                        RequestItemOutStatus = 'Rejected',
                        RequestItemOutUserID = ?,
                        RequestItemOutLastUpdated = NOW()
                        WHERE RequestItemOutID = ?";
            $qry = $this->db->query($sql, [
                $userId,
                $prm["RIOID"]
            ]);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("update request item out error", $this->db);
                exit;
            }

            $sqlDetail = "UPDATE request_item_out_detail SET
                        RequestItemOutDetailStatus = 'Rejected',
                        RequestItemOutDetailLastUpdated = NOW(),
                        RequestItemOutDetailUserID = ?
                        WHERE RequestItemOutDetailRequestItemOutID = ?";
            $qryDetail = $this->db->query($sqlDetail, [
                $userId,
                $prm["RIOID"]
            ]);
            if (!$qryDetail) {
                $this->db->trans_rollback();
                $this->sys_error_db("update request item out detail error", $this->db);
                exit;
            }


            // insert log
            $sql_json = "SELECT request_item_out.*, '' as detail
                    FROM request_item_out
                    WHERE RequestItemOutIsActive = 'Y'
                    AND RequestItemOutID = ?";
            $qry_json = $this->db->query($sql_json, [$prm["RIOID"]]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json rio error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di reject";

            $sql_json_detail = "SELECT request_item_out_detail.* 
                        FROM request_item_out_detail
                        WHERE RequestItemOutDetailIsActive = 'Y'
                        AND RequestItemOutDetailRequestItemOutID = ?";
            $qry_json_detail = $this->db->query($sql_json_detail, [$prm["RIOID"]]);
            if ($qry_json_detail) {
                $row_json["detail"] = $qry_json_detail->result_array();
            } else {
                $this->sys_error_db("select detail rio error", $this->db);
                exit;
            }

            $data_json = $row_json;

            $sql_log = "INSERT INTO user_activity(
                        UserActivityCode,
                        UserActivityStatus,
                        UserActivityDescription,
                        UserActivityRefID,
                        UserActivityData,
                        UserActivityUserID,
                        UserActivityCreated
                    ) VALUES('RIO','Process',?,?,?,?,NOW())";
            $qry_log = $this->db->query($sql_log, [
                $userdesc,
                $prm["RIOID"],
                json_encode($data_json),
                $userId
            ]);
            if (!$qry_log) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert user activity error", $this->db);
                exit;
            }

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

    // read notification
    function readNotif($userId, $refID)
    {

        $this->db->trans_begin();

        // cari user penerima notifikasi
        $sql_get = "SELECT RequestItemOutID,
                M_UserID,
                M_UserUsername,
                NotificationID,
                NotificationDetailID,
                NotificationDetailStatus,
                NotificationDetailM_UserID,
                NotificationDetailM_ApproveLevelID
                FROM notification  
                JOIN request_item_out ON NotificationRefID = RequestItemOutID
                AND RequestItemOutIsActive = 'Y'
                JOIN notification_detail ON NotificationID = NotificationDetailNotificationID
                JOIN m_user ON NotificationUserID = M_UserID
                WHERE RequestItemOutID = ?
                AND NotificationDetailStatus = 'unread'";
        $qry = $this->db->query($sql_get, [$refID]);
        if (!$qry) {
            $this->sys_error_db("select user notification error", $this->db);
            exit;
        }
        $rowsuser = $qry->result_array();


        foreach ($rowsuser as $user) {

            $sql = "UPDATE notification_detail SET 
                        NotificationDetailStatus = 'read',
                        NotificationDetailLastUpdated = NOW(),
                        NotificationDetailUserID = ?
                        WHERE NotificationDetailNotificationID = ?";
            $qry = $this->db->query($sql, [$userId, $user["NotificationID"]]);
            if (!$qry) {
                $this->sys_error_db("update notification error", $this->db);
                exit;
            }
        }

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

    // notifications
    function saveNotification($userId, $dateRequest, $number, $refID, $branchId, $divisionId)
    {
        try {
            $this->db->trans_begin();

            $xdate = date('d-m-Y');

            $sql_user = "SELECT M_UserID, M_UserUsername
                FROM m_user
                WHERE M_UserIsActive = 'Y'
                AND M_UserID = ?";
            $qry_user = $this->db->query($sql_user, [$userId]);
            if ($qry_user) {
                $username = $qry_user->row_array();
            } else {
                $this->sys_error_db("select user error", $this->db);
                exit;
            }

            $description = "Request <strong>Pengeluaran Barang</strong> pada tanggal <strong>" . $xdate . "</strong> oleh <strong>" . $username['M_UserUsername'] . "</strong> dengan nomor <strong>" . $number . "</strong>";

            $sql_menu = "SELECT S_MenuID,
                S_MenuName,
                S_MenuUrl,
                S_MenuLevel
                FROM s_menu
                WHERE S_MenuID = 68";
            $qry_menu = $this->db->query($sql_menu, []);
            if ($qry_menu) {
                $rowurl = $qry_menu->row_array();
            } else {
                $this->sys_error_db("select menu error", $this->db);
                exit;
            }

            $url = $rowurl['S_MenuUrl'] . "?flag=N&status=SendRequest&startdate=" . $dateRequest . "&search=" . $number;

            // cari user penerima notifikasi
            $sql_receive_user = "SELECT * FROM m_user
                JOIN m_branch ON  M_UserM_BranchID = M_BranchID
                    AND M_BranchIsActive = 'Y'
                    AND M_BranchCode = ?
                JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID
                    AND M_UserDivisionDivisionID != ?
                AND M_UserDivisionIsActive = 'Y'
                    WHERE M_UserIsActive = 'Y'
                    AND M_UserM_ApproveLevelID IN (2)

                UNION

                SELECT * FROM m_user
                JOIN m_branch ON  M_UserM_BranchID = M_BranchID
                    AND M_BranchIsActive = 'Y'
                    AND M_BranchCode = ?
                JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID
                    AND M_UserDivisionDivisionID = ?
                    AND M_UserDivisionIsActive = 'Y'
                    WHERE M_UserIsActive = 'Y'
                    AND M_UserM_ApproveLevelID IN (1)";
            $qry_receive_user = $this->db->query($sql_receive_user, [$branchId, $divisionId, $branchId, $divisionId]);
            if ($qry_receive_user) {
                $rowsuser = $qry_receive_user->result_array();
            } else {
                $this->sys_error_db("select receive user error", $this->db);
                exit;
            }

            $sql = "INSERT INTO notification(
                NotificationRefID,
                NotificationType,
                NotificationDescription,
                NotificationUrl,
                NotificationUserID,
                NotificationCreated) VALUES(?,?,?,?,?,NOW())";
            $qry = $this->db->query($sql, [
                $refID,
                'Pengeluaran Barang',
                $description,
                $url,
                $userId
            ]);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert notification error", $this->db);
                exit;
            }

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

            // insert ke detail notification
            foreach ($rowsuser as $row) {
                $sql_detail = "INSERT INTO notification_detail(
                    NotificationDetailNotificationID,
                    NotificationDetailM_UserID,
                    NotificationDetailM_ApproveLevelID,
                    NotificationDetailStatus,
                    NotificationDetailCreated,
                    NotificationDetailUserID) VALUES(?,?,?,?,NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, [
                    $lastid,
                    $row['M_UserID'], // user penerima notifikasi
                    $row['M_UserM_ApproveLevelID'],
                    'unread',
                    $userId
                ]);
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("insert notification detail error", $this->db);
                    exit;
                }
            }

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