<?php

class PurchaseRequest extends MY_Controller
{
    var $db;

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

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

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

            $payload = $this->sys_input;

            $query = "SELECT prd.*, 
                      ure.M_UserFullName AS M_RequesterFullName, 
                      uap.M_UserFullName AS M_ApproverFullName, 
                      uco.M_UserFullName AS M_ConfirmerFullName
                      FROM purchase_request_direct AS prd
                      INNER JOIN m_user AS ure ON prd.PurchaseRequestCreatedUserID = ure.M_UserID
                      INNER JOIN m_user AS uap ON prd.PurchaseRequestApprovedBy = uap.M_userID
                      LEFT JOIN m_user AS uco ON prd.PurchaseRequestConfirmedBy = uco.M_userID
                      WHERE prd.PurchaseRequestDirectIsActive = 'Y'
                      AND prd.PurchaseRequestDirectStatus NOT IN ('Pending', 'Draft')
                      AND PurchaseRequestDirectNumber LIKE '%" . $payload["search"] . "%'";
            $queryCount = "SELECT count(*) as total
                           FROM purchase_request_direct AS prd
                           INNER JOIN m_user AS ure ON prd.PurchaseRequestCreatedUserID = ure.M_UserID
                           INNER JOIN m_user AS uap ON prd.PurchaseRequestApprovedBy = uap.M_userID
                           LEFT JOIN m_user AS uco ON prd.PurchaseRequestConfirmedBy = uco.M_userID
                           WHERE prd.PurchaseRequestDirectIsActive = 'Y'
                           AND prd.PurchaseRequestDirectStatus NOT IN ('Pending', 'Draft')
                           AND PurchaseRequestDirectNumber LIKE '%" . $payload["search"] . "%'";

            if ((isset($payload["startDate"]) && isset($payload["endDate"])) && (trim($payload["startDate"]) !== "" && trim($payload["endDate"]) !== "")) {
                $query .= " AND (PurchaseRequestDirectDate BETWEEN '{$payload["startDate"]} 00:00:00' AND '{$payload["endDate"]} 23:59:59' OR PurchaseRequestDirectDateUse BETWEEN '{$payload["startDate"]} 00:00:00' AND '{$payload["endDate"]} 23:59:59')";
                $queryCount .= " AND (PurchaseRequestDirectDate BETWEEN '{$payload["startDate"]} 00:00:00' AND '{$payload["endDate"]} 23:59:59' OR PurchaseRequestDirectDateUse BETWEEN '{$payload["startDate"]} 00:00:00' AND '{$payload["endDate"]} 23:59:59')";
            }

            if ($payload["status"]) {
                $query .= " AND PurchaseRequestDirectStatus = {$payload["status"]}";
                $queryCount .= " AND PurchaseRequestDirectStatus = {$payload["status"]}";
            }

            $exec  = $this->db->query($queryCount, []);

            $numberLimit = 30;
            $numberOffset = 0;
            if ($payload["currentPage"] > 0) {
                $numberOffset = ($payload["currentPage"] - 1) * $numberLimit;
            }

            $totalCount = 0;
            $totalPage = 0;

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

            $query .= " ORDER BY PurchaseRequestDirectNumber DESC
                        LIMIT {$numberLimit} OFFSET {$numberOffset}";
            $exec = $this->db->query($query, []);

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

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

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

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

            $payload = $this->sys_input;

            $query = "SELECT *, 
                      ROW_NUMBER() OVER(ORDER BY PurchaseRequestDirectDetailID) RowNumber 
                      FROM purchase_request_direct_detail 
                      WHERE PurchaseRequestDirectDetailIsActive = 'Y' 
                      AND PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload['PRID']}";
            $queryCount = "SELECT count(*) as total
                           FROM purchase_request_direct_detail
                           WHERE PurchaseRequestDirectDetailIsActive = 'Y' 
                           AND PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload['PRID']}";

            $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 .= " ORDER BY PurchaseRequestDirectDetailStatus ASC, 
                        PurchaseRequestDirectDetailID 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 paidRequest()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }

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

            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDirectStatus = 'Paid',
                    PurchaseRequestDirectTotalPaid = {$payload['PRPaid']},
                    PurchaseRequestPaidDate = NOW(),
                    PurchaseRequestPaidBy = {$userId},
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = {$userId}
                    WHERE PurchaseRequestDirectStatus = 'Approved'
                    AND PurchaseRequestDirectID = {$payload['PRID']}
                    AND PurchaseRequestDirectIsActive = 'Y'";
            $exec = $this->db->query($sql, []);

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

            $rowQuery = "SELECT prd.*, 
                         ure.M_UserFullName AS M_RequesterFullName, 
                         uap.M_UserFullName AS M_ApproverFullName, 
                         uco.M_UserFullName AS M_ConfirmerFullName
                         FROM purchase_request_direct AS prd
                         INNER JOIN m_user AS ure ON prd.PurchaseRequestCreatedUserID = ure.M_UserID
                         INNER JOIN m_user AS uap ON prd.PurchaseRequestApprovedBy = uap.M_userID
                         LEFT JOIN m_user AS uco ON prd.PurchaseRequestConfirmedBy = uco.M_userID
                         WHERE prd.PurchaseRequestDirectIsActive = 'Y'
                         AND prd.PurchaseRequestDirectStatus NOT IN ('Pending', 'Draft')
                         AND prd.PurchaseRequestDirectID = {$payload['PRID']}";
            $exec = $this->db->query($rowQuery, []);

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

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

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

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

            $sqlDetail = "UPDATE purchase_request_direct_detail SET
                          PurchaseRequestDirectDetailStatus = 'Received',
                          PurchaseRequestDirectDetailLastUpdated = NOW(),
                          PurchaseRequestDirectDetailLastUpdatedUserID = {$userId}
                          WHERE PurchaseRequestDirectDetailStatus = 'Ordered'
                          AND PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload["PRID"]}
                          AND PurchaseRequestDirectDetailIsActive = 'Y'";
            $exec = $this->db->query($sqlDetail, []);
            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("approve request error", $this->db);
                exit;
            }

            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDirectStatus = 'Completed',
                    PurchaseRequestDirectTotalRealitation = {$payload["PRRealitation"]},
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = {$userId}
                    WHERE PurchaseRequestDirectStatus = 'Paid'
                    AND PurchaseRequestDirectID = {$payload["PRID"]}
                    AND PurchaseRequestDirectIsActive = 'Y'";
            $exec = $this->db->query($sql, []);

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

            $rowQuery = "SELECT prd.*, 
                         ure.M_UserFullName AS M_RequesterFullName, 
                         uap.M_UserFullName AS M_ApproverFullName, 
                         uco.M_UserFullName AS M_ConfirmerFullName
                         FROM purchase_request_direct AS prd
                         INNER JOIN m_user AS ure ON prd.PurchaseRequestCreatedUserID = ure.M_UserID
                         INNER JOIN m_user AS uap ON prd.PurchaseRequestApprovedBy = uap.M_userID
                         LEFT JOIN m_user AS uco ON prd.PurchaseRequestConfirmedBy = uco.M_userID
                         WHERE prd.PurchaseRequestDirectIsActive = 'Y'
                         AND prd.PurchaseRequestDirectStatus NOT IN ('Pending', 'Draft')
                         AND prd.PurchaseRequestDirectID = {$payload["PRID"]}";
            $exec = $this->db->query($rowQuery, []);

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

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