<?php

class PurchaseRequestV2 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"] : "";

            $totalCount = 0;
            $totalPage = 1;

            $sql = "SELECT COUNT(*) as total
                    FROM purchase_request
                    JOIN s_regional ON S_RegionalID = PurchaseRequestS_RegionalID
                    WHERE 
                    PurchaseRequestIsActive = 'Y' AND 
                    PurchaseRequestItemTypeID = '1' AND
                    ( PurchaseRequestDate BETWEEN ? AND ? ) AND 
                    ( PurchaseRequestStatus = ? OR ? = '' ) AND 
                    ( PurchaseRequestNumber LIKE ?)";
            
            $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("select purchase request", $this->db);
                exit;
            }

            $sql = "SELECT DISTINCT PurchaseRequestID as prId, 
                    PurchaseRequestNumber as prNumber, 
                    PurchaseRequestDate as prDate, 
                    PurchaseRequestStatus as prStatus, 
                    requestedBy.M_UserUsername as prRequestedBy, 
                    IF(PurchaseRequestApprovedBy IS NULL, '', approvedBy.M_UserUsername) as prApprovedBy,
                    PurchaseRequestS_RegionalID as prRegionalId,
                    S_RegionalName as prRegionalName,
                    PurchaseRequestM_BranchCode as prBranchCode,
                    M_BranchName as prBranchName,
                    PurchaseRequestNote as prNote,
                    PurchaseRequestStatus as prStatus
                    FROM purchase_request
                    JOIN s_regional ON S_RegionalID = PurchaseRequestS_RegionalID
                    JOIN m_user requestedBy ON requestedBy.M_UserID = PurchaseRequestRequestedBy
                    LEFT JOIN m_user approvedBy ON approvedBy.M_UserID = PurchaseRequestApprovedBy
                    LEFT JOIN m_branch ON M_BranchCode = PurchaseRequestM_BranchCode
                    WHERE 
                    PurchaseRequestIsActive = 'Y' AND 
                    PurchaseRequestItemTypeID = '1' AND
                    ( PurchaseRequestDate BETWEEN ? AND ? ) AND 
                    ( PurchaseRequestStatus = ? OR ? = '' ) AND 
                    ( PurchaseRequestNumber LIKE ?)";
            
            $exec = $this->db->query($sql, [$startDate, $endDate, $status, $status, '%' . $search . '%']);
            if(!$exec) {
                $this->sys_error_db("select purchase request", $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 saveRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }

            $this->db->trans_begin();

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

            $pdSql = "SELECT `fn_numbering`('PD') AS PD";
            $exec = $this->db->query($pdSql, []);
            $pd = "";
            $dateNow = date('Y-m-d');

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

            // Menggunakan parameter query untuk insert
            $sql = "INSERT INTO purchase_request_direct(
                    PurchaseRequestDirectNumber,
                    PurchaseRequestDirectDate,
                    PurchaseRequestDirectDateUse,
                    PurchaseRequestDirectM_BranchCode,
                    PurchaseRequestDirectDescription,
                    PurchaseRequestDirectNote,
                    PurchaseRequestDirectTotalEstimation,
                    PurchaseRequestDirectTotalPaid,
                    PurchaseRequestDirectTotalRealitation,
                    PurchaseRequestDirectStatus,
                    PurchaseRequestApprovedDate,
                    PurchaseRequestApprovedBy,
                    PurchaseRequestConfirmedDate,
                    PurchaseRequestConfirmedBy,
                    PurchaseRequestPaidDate,
                    PurchaseRequestPaidBy,
                    PurchaseRequestDirectIsActive,
                    PurchaseRequestCreated,
                    PurchaseRequestLastUpdated,
                    PurchaseRequestDeleted,
                    PurchaseRequestCreatedUserID,
                    PurchaseRequestLastUpdatedUserID,
                    PurchaseRequestDeletedUserID
                    ) VALUES (?, ?, ?, ?, ?, NULL, 0, 0, 0, 'Draft', NULL, NULL, NULL, NULL, NULL, NULL, 'Y', NOW(), NULL, NULL, ?, NULL, NULL)";
                    
            $insertParams = [
                $pd, 
                $dateNow, 
                $payload['PRDateUse'], 
                $payload['PRBranch'], 
                $payload['PRDescription'], 
                $userId
            ];
            
            $exec = $this->db->query($sql, $insertParams);

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

            $this->db->trans_commit();

            // Menggunakan parameter query untuk select
            $newInsert = "SELECT * FROM purchase_request_direct WHERE PurchaseRequestDirectNumber = ? AND PurchaseRequestDirectIsActive = 'Y'";
            $records = $this->db->query($newInsert, [$pd])->result_array();

            $result = array("total" => 1, "records" => $records);
            $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");
            }

            $this->db->trans_begin();

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

            // Menggunakan parameter query untuk update
            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDirectDateUse = ?,
                    PurchaseRequestDirectM_BranchCode = ?,
                    PurchaseRequestDirectDescription = ?,
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = ?
                    WHERE PurchaseRequestDirectID = ?";
                    
            $updateParams = [
                $payload['PRDateUse'],
                $payload['PRBranch'],
                $payload['PRDescription'],
                $userId,
                $payload['PRID']
            ];
            
            $exec = $this->db->query($sql, $updateParams);

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

            $this->db->trans_commit();

            // Menggunakan parameter query untuk select
            $newUpdate = "SELECT * FROM purchase_request_direct WHERE PurchaseRequestDirectID = ? AND PurchaseRequestDirectIsActive = 'Y'";
            $records = $this->db->query($newUpdate, [$payload['PRID']])->result_array();

            $result = array("total" => 1, "records" => $records);
            $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"];

            // Menggunakan parameter query untuk delete
            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDeleted = NOW(),
                    PurchaseRequestDeletedUserID = ?,
                    PurchaseRequestDirectIsActive = 'N'
                    WHERE PurchaseRequestDirectID = ?";
                    
            $deleteParams = [$userId, $payload['PRID']];
            
            $exec = $this->db->query($sql, $deleteParams);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("purchase request delete error", $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 {
            $userId = $this->sys_user["M_UserID"];

            $rows = [];
            $rows[] = array("DivisionID" => "", "DivisionCode" => "", "DivisionName" => "Semua Divisi");
            $query = "SELECT DISTINCT
                      DivisionID,
                      DivisionCode,
                      DivisionName
                      FROM division
                      WHERE DivisionIsActive = 'Y'
                      ORDER BY DivisionName ASC";
            $exec = $this->db->query($query);
            if ($exec) {
                $rst = $exec->result_array();
                foreach ($rst as $key => $row) {
                    $rows[] = array("DivisionID" => $row["DivisionID"], "DivisionCode" => $row["DivisionCode"], "DivisionName" => $row["DivisionName"]);
                }
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select division", $this->db);
                exit;
            }

            $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) {
                $r_selected = $exec->result_array();
                if (count($r_selected) > 0) {
                    $row = $r_selected[0];
                } else {
                    $row = array("DivisionID" => "", "DivisionCode" => "", "DivisionName" => "Semua Divisi");
                }
            } 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;
            $search = isset($prm["search"]) ? $prm["search"] : "";

            $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
                    WHERE Nat_GroupIsActive = 'Y'
                    ORDER BY Nat_GroupID ASC";

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

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

            $rst = $query->result_array();
            foreach ($rst as $key => $row) {
                if($row["Nat_GroupID"] == "") {
                    $row["subGroups"] = [];
                } else {
                    $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;
                    }
                    $row["subGroups"] = $querySubGroup->result_array();
                }
                $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";
           
            $params = [];

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

            $filterItemGroup = "";
            if($itemGroup != "") {
                $filterItemGroup = "JOIN m_itemgroup ON M_ItemGroupID = Nat_GroupID AND M_ItemGroupIsActive = 'Y' AND (M_ItemGroupID = ? OR ? = '')";
                $params[] = $itemGroup;
                $params[] = $itemGroup;
            }
            
            $filterItemSubGroup = "";
            if($itemSubGroup != "") {
                $filterItemSubGroup = "JOIN m_itemsubgroup ON M_ItemSubGroupID = Nat_SubGroupID AND M_ItemSubGroupIsActive = 'Y' AND (M_ItemSubGroupID = ? OR ? = '')";
                $params[] = $itemSubGroup;
                $params[] = $itemSubGroup;
            }
            
            // Menambahkan parameter untuk unitPurchase
            $params[] = $unitPurchase;
            $params[] = $unitPurchase;
            
            $sql = "SELECT
                    M_ItemID as itemId,
                    M_ItemCode as itemCode,
                    M_ItemDesc as itemDesc,
                    0 as qty,
                    ItemUnitID as unitId,
                    ItemUnitCode as unitCode,
                    ItemUnitName as unitName
                    FROM m_item
                    JOIN itemunitmap ON ItemUnitMapM_ItemID = M_ItemID AND 
                        ((ItemUnitMapUnitPurchase = '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_ItemDesc LIKE ?
                    ORDER BY M_ItemDesc ASC";
            
            // Menambahkan parameter untuk search
            $params[] = '%' . $search . '%';
            
            
            // 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;
            }

            $rows = $query->result_array();

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

            $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);
        }
    }
    
}
