<?php

class PurchaseRequestPo extends MY_Controller
{
    var $db;

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

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

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

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

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

            $sql = "SELECT SupplierID,
                    SupplierCode,
                    SupplierName
                    FROM supplier
                    WHERE SupplierIsActive = 'Y'
                    AND SupplierName LIKE '{$search}'
                    ORDER BY SupplierID ASC ";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("select supplier", $this->db);;
                exit;
            }

            $rows = $qry->result_array();

            if ($rows) {
                array_push($rows, ["SupplierID" => "0", "SupplierCode" => "All", "SupplierName" => "All"]);
            }

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

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

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

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

            $sql = "SELECT SupplierID,
                    SupplierCode,
                    SupplierName
                    FROM supplier
                    WHERE SupplierIsActive = 'Y'
                    ORDER BY SupplierID ASC ";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("select supplier", $this->db);;
                exit;
            }

            $rows = $qry->result_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 getItemType()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

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

            $sql = "SELECT ItemTypeID,
                    ItemTypeName
                    FROM item_type
                    WHERE ItemTypeIsActive = 'Y'
                    AND ItemTypeName LIKE '{$search}'
                    ORDER BY ItemTypeID ASC";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("select supplier", $this->db);;
                exit;
            }

            $rows = $qry->result_array();

            if ($rows) {
                array_push($rows, ["ItemTypeID" => "0", "ItemTypeName" => "All"]);
            }

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

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

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

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

            $sql = "SELECT ItemTypeID,
                    ItemTypeName
                    FROM item_type
                    WHERE ItemTypeIsActive = 'Y'
                    ORDER BY ItemTypeID ASC";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("select supplier", $this->db);;
                exit;
            }

            $rows = $qry->result_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 search()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

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

            $filterSuplier = "";
            $filterType = "";
            if (intval($supplierId) > 0) {
                $filterSuplier .= " AND SupplierID = {$supplierId}";
            }
            if (intval($typeId) > 0) {
                $filterType .= " AND ItemTypeID = {$typeId}";
            }

            $sql = "SELECT purchase_request.*,
                    SupplierID,
                    SupplierCode,
                    SupplierName,
                    ItemTypeID,
                    ItemTypeName,
                    S_RegionalID,
                    S_RegionalName,
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM purchase_request
                    JOIN supplier ON PurchaseRequestSupplierID = SupplierID AND SupplierIsActive = 'Y'
                    JOIN item_type ON PurchaseRequestItemTypeID = ItemTypeID AND ItemTypeIsActive = 'Y'
                    JOIN s_regional ON PurchaseRequestS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON PurchaseRequestM_BranchCode = M_BranchCode AND  M_BranchIsActive = 'Y'
                    WHERE PurchaseRequestIsActive = 'Y'
                    AND (PurchaseRequestDate BETWEEN '{$startDate} 00:00:00' AND '{$endDate} 23:59:59')
                    AND (PurchaseRequestNumber LIKE '{$search}')
                    $filterSuplier $filterType
                    ORDER BY PurchaseRequestNumber DESC";

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

            $number_offset = 0;
            $number_limit = 10;

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

            $totalCount = 0;
            $totalPage = 0;
            if ($qryTotal) {
                $totalCount = $qryTotal->result_array()[0]["total"];
                $totalPage = ceil($totalCount / $number_limit);
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select purcahse request count error", $this->db);;
                exit;
            }

            $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset";
            $qry = $this->db->query($sql_select);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select purcahse request error", $this->db);
                exit;
            }

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

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

            $sql = "SELECT S_RegionalID,
                S_RegionalName
                FROM s_regional
                WHERE S_RegionalIsActive = 'Y'
                ORDER BY S_RegionalName ASC";
            $qry = $this->db->query($sql, []);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select regional", $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 getBranch()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $payload = $this->sys_input;

            $regionalId = $payload["regionalId"];
            $query = "SELECT DISTINCT
                      M_BranchCode,
                      M_BranchName
                      FROM m_branch
                      WHERE M_BranchIsActive = 'Y'
                      AND M_BranchS_RegionalID = ?
                      ORDER BY M_BranchName ASC";
            $exec = $this->db->query($query, [$regionalId]);
            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 searchItem()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $payload = $this->sys_input;

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

            $number_limit = 10;
            $sql = "SELECT 
                    M_ItemID,
                    M_ItemCode,
                    IF(M_ItemDesc = '', '-', M_ItemDesc) AS M_ItemDesc
                    FROM m_item
                    WHERE (M_ItemCode LIKE ? OR M_ItemDesc LIKE ?)
                    ORDER BY M_ItemDesc ASC
                    LIMIT ?";
            $qry = $this->db->query($sql, array($search, $search, $number_limit));
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select item error", $this->db);
                exit;
            }

            $result = array(
                "records" => $rows,
                "total_filter" => sizeof($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;

            $queryCount = "SELECT count(*) as total
                           FROM purchase_request_detail
                           JOIN m_item ON PurchaseRequestDetailM_ItemID = M_ItemID
                           LEFT JOIN itemunit ON PurchaseRequestDetailItemUnitID = ItemUnitID
                           WHERE PurchaseRequestDetailIsActive = 'Y' 
                           AND PurchaseRequestDetailPurchaseRequestID = {$payload['POID']}";
            $exec = $this->db->query($queryCount, []);

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

            $query = "SELECT purchase_request_detail.*, 
                        M_ItemID, M_ItemCode, M_ItemDesc,
                        ItemUnitID, ItemUnitName,
                      ROW_NUMBER() OVER(ORDER BY PurchaseRequestDetailID) RowNumber 
                      FROM purchase_request_detail
                      JOIN m_item ON PurchaseRequestDetailM_ItemID = M_ItemID
                      LEFT JOIN itemunit ON PurchaseRequestDetailItemUnitID = ItemUnitID
                      WHERE PurchaseRequestDetailIsActive = 'Y' 
                      AND PurchaseRequestDetailPurchaseRequestID = {$payload['POID']}
                      ORDER BY PurchaseRequestDetailStatus ASC, 
                      PurchaseRequestDetailID ASC";
            $exec = $this->db->query($query, []);

            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,
                "sql" => $this->db->last_query()
            );

            $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`('PR') AS PR";
            $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]["PR"];
            }

            $sql = "INSERT INTO purchase_request(
                    PurchaseRequestDate,
                    PurchaseRequestNumber,
                    PurchaseRequestRefNumber,
                    PurchaseRequestSupplierID,
                    PurchaseRequestS_RegionalID,
                    PurchaseRequestM_BranchCode,
                    PurchaseRequestNote,
                    PurchaseRequestStatus,
                    PurchaseRequestItemTypeID,
                    PurchaseRequestRequestedBy,
                    PurchaseRequestIsActive,
                    PurchaseRequestUserID,
                    PurchaseRequestCreated
                    ) VALUES ('{$payload['PODate']}', '{$pd}', '{$payload['PONoReferensi']}', '{$payload['POVendor']}', '{$payload['PORegional']}', '{$payload['POBranch']}', '{$payload['PODescription']}', 'Draft', '{$payload['POItemType']}', {$userId}, 'Y', {$userId}, NOW())";
            $exec = $this->db->query($sql, []);

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

            $this->db->trans_commit();

            $newInsert = "SELECT * FROM purchase_request WHERE PurchaseRequestNumber = '{$pd}' AND PurchaseRequestIsActive = 'Y'";
            $records = $this->db->query($newInsert, [])->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"];

            $sql = "UPDATE purchase_request SET
                    PurchaseRequestDate	 = '{$payload['PODate']}',
                    PurchaseRequestRefNumber = '{$payload['PONoReferensi']}',
                    PurchaseRequestSupplierID = '{$payload['POVendor']}',
                    PurchaseRequestM_BranchCode = '{$payload['POBranch']}',
                    PurchaseRequestNote = '{$payload['PODescription']}',
                    PurchaseRequestItemTypeID = '{$payload['POItemType']}',
                    PurchaseRequestUserID = {$userId},
                    PurchaseRequestLastUpdated = NOW()
                    WHERE PurchaseRequestID = {$payload['POID']}";
            $exec = $this->db->query($sql, []);

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

            $this->db->trans_commit();

            $newUpdate = "SELECT * FROM purchase_request WHERE PurchaseRequestID = {$payload['POID']} AND PurchaseRequestIsActive = 'Y'";
            $records = $this->db->query($newUpdate, [])->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"];

            $sql = "UPDATE purchase_request SET
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestUserID = {$userId},
                    PurchaseRequestIsActive = 'N'
                    WHERE PurchaseRequestID = {$payload['POID']}";
            $exec = $this->db->query($sql, []);

            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']);

            $query = "SELECT COUNT(*) as exist 
                      FROM purchase_request_detail 
                      WHERE PurchaseRequestDetailIsActive = 'Y' 
                      AND PurchaseRequestDetailM_ItemID = '{$payload['POItem']}' 
                      AND PurchaseRequestDetailPurchaseRequestID = {$payload['POID']}";
            $exist = $this->db->query($query, []);
            if ($exist) {
                $row = $exist->row()->exist;
            } else {
                $this->sys_error_db("exist error", $this->db);
                exit;
            }

            if ($row == 0) {
                $sql = "INSERT INTO purchase_request_detail(
                        PurchaseRequestDetailPurchaseRequestID,
                        PurchaseRequestDetailM_ItemID,
                        PurchaseRequestDetailItemUnitID,
                        PurchaseRequestDetailQty,
                        PurchaseRequestDetailPrice,
                        PurchaseRequestDetailStatus,
                        PurchaseRequestDetailIsCito,
                        PurchaseRequestDetailIsActive,
                        PurchaseRequestDetailUserID,
                        PurchaseRequestDetailCreated
                        ) VALUES ({$payload['POID']}, {$payload['POItem']}, {$payload['POItemUnit']}, {$payload['POQty']}, {$payload['POPrice']}, 'Draft', '{$payload['POIsCito']}', 'Y', {$userId}, NOW())";
                $exec = $this->db->query($sql, []);

                if (!$exec) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("request insert error", $this->db);
                    exit;
                } else {
                    $sqlTotalPriceQty = "SELECT SUM(PurchaseRequestDetailPrice * PurchaseRequestDetailQty) as Total 
                                        FROM purchase_request_detail 
                                        WHERE PurchaseRequestDetailPurchaseRequestID = {$payload['POID']}
                                        AND PurchaseRequestDetailIsActive = 'Y'";
                    $execTotal = $this->db->query($sqlTotalPriceQty, []);

                    if (!$execTotal) {
                        $this->db->trans_rollback();
                        $this->sys_error_db("calculate total price error", $this->db);
                        exit;
                    }
                    $total = 0;

                    $total = $execTotal->row()->Total;

                    $sql = "UPDATE purchase_request SET
                    PurchaseRequestTotal = {$total},
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestUserID = {$userId}
                    WHERE PurchaseRequestID	 = {$payload['POID']}
                    AND PurchaseRequestIsActive	 = 'Y'";
                    $exec = $this->db->query($sql, []);
                }

                $this->db->trans_commit();

                $result = array("total" => 1, "records" => array("xId" => 0));
                $this->sys_ok($result);
            } else {
                $errors = array();
                $select = "SELECT M_ItemDesc FROM m_item WHERE M_ItemID = '{$payload['POItem']}'";
                $qry = $this->db->query($select, []);
                if ($qry) {
                    $rowdata = $qry->row()->M_ItemDesc;
                } else {
                    $this->sys_error_db("select nat item error", $this->db);
                    exit;
                }
                if ($row != 0) {
                    array_push($errors, array('msg' => 'Data dengan item ' . $rowdata . ' 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"]);


            $sql = "UPDATE purchase_request_detail SET
                    PurchaseRequestDetailM_ItemID = {$payload["POItem"]},
                    PurchaseRequestDetailItemUnitID = {$payload["POItemUnit"]},
                    PurchaseRequestDetailQty = {$payload["POQty"]},
                    PurchaseRequestDetailPrice = {$payload["POPrice"]},
                    PurchaseRequestDetailIsCito = '{$payload['POIsCito']}',
                    PurchaseRequestDetailLastUpdated = NOW(),
                    PurchaseRequestDetailUserID = {$userId}
                    WHERE PurchaseRequestDetailID = {$payload["PODID"]}";
            $exec = $this->db->query($sql, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("request update error", $this->db);
                exit;
            } else {
                $sqlTotalPrice = "SELECT SUM(PurchaseRequestDetailPrice) AS Total
                                  FROM purchase_request_detail
                                  WHERE PurchaseRequestDetailPurchaseRequestID = {$payload["POID"]}
                                  AND PurchaseRequestDetailIsActive = 'Y'";
                $exec = $this->db->query($sqlTotalPrice, []);
                $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"];
                }

                $sql = "UPDATE purchase_request SET
                        PurchaseRequestTotal = {$total},
                        PurchaseRequestLastUpdated = NOW(),
                        PurchaseRequestUserID = {$userId}
                        WHERE PurchaseRequestID = {$payload["POID"]}
                        AND PurchaseRequestIsActive = 'Y'";
                $exec = $this->db->query($sql, []);
            }

            $this->db->trans_commit();

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

            $sql = "UPDATE purchase_request_detail SET
                    PurchaseRequestDetailLastUpdated = NOW(),
                    PurchaseRequestDetailUserID = {$userId},
                    PurchaseRequestDetailIsActive = 'N'
                    WHERE PurchaseRequestDetailID = {$payload["PODID"]}";
            $exec = $this->db->query($sql, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("request delete error", $this->db);
                exit;
            } else {
                $sqlTotalPrice = "SELECT SUM(PurchaseRequestDetailPrice) AS Total
                                  FROM purchase_request_detail
                                  WHERE PurchaseRequestDetailPurchaseRequestID = {$payload["POID"]}
                                  AND PurchaseRequestDetailIsActive = 'Y'";
                $exec = $this->db->query($sqlTotalPrice, []);
                $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;
                }

                $sql = "UPDATE purchase_request SET
                        PurchaseRequestTotal = {$total},
                        PurchaseRequestLastUpdated = NOW(),
                        PurchaseRequestUserID = {$userId}
                        WHERE PurchaseRequestID = {$payload["POID"]}
                        AND PurchaseRequestIsActive = 'Y'";
                $exec = $this->db->query($sql, []);
            }

            $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"];

            $sqlDetail = "UPDATE purchase_request_detail SET
                          PurchaseRequestDetailLastUpdated = NOW(),
                          PurchaseRequestDetailStatus = 'Pending',
                          PurchaseRequestDetailUserID = {$userId}
                          WHERE PurchaseRequestDetailPurchaseRequestID = {$payload["POID"]}
                          AND PurchaseRequestDetailIsActive = 'Y'
                          AND PurchaseRequestDetailStatus = 'Draft'";
            $exec = $this->db->query($sqlDetail, []);

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

            $sql = "UPDATE purchase_request SET
                PurchaseRequestStatus = 'Pending',
                PurchaseRequestLastUpdated = NOW(),
                PurchaseRequestUserID = {$userId}
                WHERE PurchaseRequestID = {$payload["POID"]}
                AND PurchaseRequestIsActive = 'Y'";
            $exec = $this->db->query($sql, []);

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

            $this->db->trans_commit();

            $sql = "SELECT *, 
                    ROW_NUMBER() OVER(ORDER BY PurchaseRequestNumber) RowNumber 
                    FROM purchase_request 
                    WHERE PurchaseRequestIsActive = 'Y' 
                    AND PurchaseRequestUserID = {$userId}
                    AND PurchaseRequestID = {$payload["POID"]}";
            $exec = $this->db->query($sql, []);

            $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 getUnit()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $sql = "SELECT 
                    ItemUnitID,
                    ItemUnitCode,
                    ItemUnitName,
                    ItemUnitCreated,
                    ItemUnitLastUpdated,
                    ItemUnitIsActive,
                    ItemUnitUserID,
                    ItemUnitMapM_ItemID,
                    ItemUnitMapIsPurchase,
                    ItemUnitMapIsReport,
                    ItemUnitMapIsBase
                    FROM itemunit 
                    JOIN itemunitmap ON ItemUnitMapItemUnitID = ItemUnitID AND ItemUnitMapIsActive ='Y'
                    AND ItemUnitMapM_ItemID = {$itemID}
                WHERE ItemUnitIsActive = 'Y'
                AND ItemUnitName LIKE '%{$search}%'
                ORDER BY ItemUnitName ASC";

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

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

            $rows = $query->result_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 getPrice()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $itemID = $prm["itemID"];
            $itemUnitID = $prm["itemUnitID"];

            if (!$itemID || !$itemUnitID) {
                $this->sys_error("Parameter itemID dan itemUnitID diperlukan.", $this->db);
                exit;
            }

            $sql = "SELECT 
                        iu.ItemUnitID,
                        iu.ItemUnitCode,
                        iu.ItemUnitName,
                        iu.ItemUnitCreated,
                        iu.ItemUnitLastUpdated,
                        iu.ItemUnitIsActive,
                        iu.ItemUnitUserID,
                        ium.ItemUnitMapM_ItemID,
                        ium.ItemUnitMapIsPurchase,
                        ium.ItemUnitMapIsReport,
                        ium.ItemUnitMapIsBase,
                        sp.MaxPrice AS SupplierPricePrice
                    FROM itemunit iu
                    JOIN itemunitmap ium 
                        ON ium.ItemUnitMapItemUnitID = iu.ItemUnitID 
                        AND ium.ItemUnitMapIsActive = 'Y'
                        AND ium.ItemUnitMapIsPurchase = 'Y'
                    JOIN m_item mi 
                        ON ium.ItemUnitMapM_ItemID = mi.M_ItemID 
                        AND mi.M_ItemIsActive = 'Y'
                    JOIN (
                        SELECT 
                            SupplierPriceM_ItemID, 
                            SupplierPriceItemUnitID, 
                            MAX(SupplierPricePrice) AS MaxPrice
                        FROM supplier_price
                        WHERE SupplierPriceIsActive = 'Y'
                        GROUP BY SupplierPriceM_ItemID, SupplierPriceItemUnitID
                    ) sp 
                        ON sp.SupplierPriceItemUnitID = iu.ItemUnitID 
                        AND sp.SupplierPriceM_ItemID = mi.M_ItemID
                    WHERE iu.ItemUnitIsActive = 'Y'
                    AND mi.M_ItemID = {$itemID}
                    AND iu.ItemUnitID = {$itemUnitID}
                    ";

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

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

            $priceMax = $query->row()->SupplierPricePrice;

            $result = array(
                "price" => $priceMax,
                "sql" => $this->db->last_query()
            );

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