<?php

class PurchaseRequestDirect extends MY_Controller
{
    var $db;

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

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

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

            $payload = $this->sys_input;

            $query = "SELECT prd.*, mu.M_UserFullName as M_RequesterFullName
                      FROM purchase_request_direct as prd
                      JOIN m_user as mu ON prd.PurchaseRequestCreatedUserID = mu.M_UserID
                      WHERE PurchaseRequestDirectStatus != 'Draft'
                      AND PurchaseRequestDirectIsActive = 'Y'
                      AND PurchaseRequestDirectNumber LIKE '%" . $payload["search"] . "%'";
            $queryCount = "SELECT count(*) as total
                           FROM purchase_request_direct as prd
                           JOIN m_user as mu ON prd.PurchaseRequestCreatedUserID = mu.M_UserID
                           WHERE PurchaseRequestDirectStatus != 'Draft'
                           AND PurchaseRequestDirectIsActive = 'Y'
                           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 = 20;
            $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 = $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 {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $payload = $this->sys_input;

            $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 = "SELECT *, 
                      ROW_NUMBER() OVER(ORDER BY PurchaseRequestDirectDetailID) RowNumber 
                      FROM purchase_request_direct_detail 
                      WHERE PurchaseRequestDirectDetailIsActive = 'Y' 
                      AND PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload['PRID']}
                      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 deleteDetail()
    {
        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
                          PurchaseRequestDirectDetailIsActive = 'N',
                          PurchaseRequestDirectDetailDeleted = NOW(),
                          PurchaseRequestDirectDetailDeletedUserID = {$userId}
                          WHERE PurchaseRequestDirectDetailStatus = 'Pending'
                          AND PurchaseRequestDirectDetailID = {$payload['PRDID']}
                          AND PurchaseRequestDirectDetailIsActive = 'Y'";
            $exec = $this->db->query($sqlDetail, []);
            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("reject request error", $this->db);
                exit;
            } else {
                $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total
                                  FROM purchase_request_direct_detail
                                  WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload['PRID']}
                                  AND PurchaseRequestDirectDetailIsActive = '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_direct SET
                        PurchaseRequestDirectTotalEstimation = {$total},
                        PurchaseRequestLastUpdated = NOW(),
                        PurchaseRequestLastUpdatedUserID = {$userId}
                        WHERE PurchaseRequestDirectID = {$payload['PRID']}
                        AND PurchaseRequestDirectIsActive = 'Y'";
                $exec = $this->db->query($sql, []);
                $this->db->trans_commit();
                $result = array("total" => 1, "records" => array("xPRDID" => $payload['PRDID']));
                $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");
            }

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

            $sqlDetail = "UPDATE purchase_request_direct_detail SET
                          PurchaseRequestDirectDetailStatus = 'Ordered',
                          PurchaseRequestDirectDetailLastUpdated = NOW(),
                          PurchaseRequestDirectDetailLastUpdatedUserID = {$userId}
                          WHERE PurchaseRequestDirectDetailStatus = 'Pending'
                          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;
            }

            $total = 0;
            $query = "SELECT SUM(IF(PurchaseRequestDirectDetailTotalRealitationPrice IS NULL, PurchaseRequestDirectDetailTotalEstimationPrice,PurchaseRequestDirectDetailTotalRealitationPrice)) as total
                      FROM purchase_request_direct_detail
                      WHERE PurchaseRequestDirectDetailIsActive = 'Y'
                      AND PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload['PRID']}";
            $exec = $this->db->query($query);
            if ($exec) {
                $total = $exec->row()->total;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select purchase_request_direct_detail", $this->db);
                exit;
            }

            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDirectNote = '{$payload['PRNote']}',
                    PurchaseRequestDirectStatus = 'Approved',
                    PurchaseRequestDirectApprovedDate = NOW(),
                    PurchaseRequestDirectApprovedBy = {$userId},
                    PurchaseRequestDirectTotalRealitation = {$total},
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = {$userId}
                    WHERE PurchaseRequestDirectStatus = 'Pending'
                    AND PurchaseRequestDirectID = {$payload['PRID']}
                    AND PurchaseRequestDirectIsActive = 'Y'";
            $exec = $this->db->query($sql, []);

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

            $rowQuery = "SELECT prd.*,
                         mu.M_UserFullName AS M_RequesterFullName
                         FROM purchase_request_direct AS prd
                         INNER JOIN m_user AS mu ON prd.PurchaseRequestCreatedUserID = mu.M_UserID
                         WHERE PurchaseRequestDirectID = {$payload['PRID']}
                         AND PurchaseRequestDirectIsActive = 'Y'";
            $exec = $this->db->query($rowQuery, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("approve request 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 rejectRequest()
    {
        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 = 'Draft',
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = {$userId}
                    WHERE PurchaseRequestDirectStatus = 'Pending'
                    AND PurchaseRequestDirectID = {$payload["PRID"]}
                    AND PurchaseRequestDirectIsActive = 'Y'";
            $exec = $this->db->query($sql, []);

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

            $this->db->trans_commit();
            $result = array("total" => 1, "records" => array("xPRID" => $payload["PRID"]));
            $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");
            }

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
           /* $price = 0;

            $sqlPrice = "SELECT PurchaseRequestDirectDetailEstimationPrice AS Price
                         FROM purchase_request_direct_detail
                         WHERE PurchaseRequestDirectDetailID = {$payload['PRDID']}";
            $exec = $this->db->query($sqlPrice, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("update amount error", $this->db);
                exit;
            } else {
                $price = $exec->result_array()[0]["Price"];
            }
            */

            $PRDTotal = $payload['PRDAmount'] * $payload['PRDPrice'];

            $sqlDetail = "UPDATE purchase_request_direct_detail SET
                          PurchaseRequestDirectDetailAmount = {$payload['PRDAmount']},
                          PurchaseRequestDirectDetailRealitationPrice = {$payload['PRDPrice']},
                          PurchaseRequestDirectDetailTotalRealitationPrice = {$PRDTotal},
                          PurchaseRequestDirectDetailLastUpdated = NOW(),
                          PurchaseRequestDirectDetailLastUpdatedUserID = {$userId}
                          WHERE PurchaseRequestDirectDetailID = {$payload['PRDID']}
                          AND PurchaseRequestDirectDetailIsActive = 'Y'";
            $exec = $this->db->query($sqlDetail, []);

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

            $total = 0;
            $query = "SELECT SUM(IF(PurchaseRequestDirectDetailTotalRealitationPrice IS NULL, PurchaseRequestDirectDetailTotalEstimationPrice,PurchaseRequestDirectDetailTotalRealitationPrice)) as total
                      FROM purchase_request_direct_detail
                      WHERE PurchaseRequestDirectDetailIsActive = 'Y'
                      AND PurchaseRequestDirectDetailPurchaseRequestDirectID = {$payload['PRID']}";
            $exec = $this->db->query($query);
            if ($exec) {
                $total = $exec->row()->total;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select purchase_request_direct_detail", $this->db);
                exit;
            }

            $sql = "UPDATE purchase_request_direct SET
                    PurchaseRequestDirectTotalRealitation = {$total},
                    PurchaseRequestLastUpdated = NOW(),
                    PurchaseRequestLastUpdatedUserID = {$userId}
                    WHERE  PurchaseRequestDirectID = {$payload['PRID']}";
            $exec = $this->db->query($sql, []);

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

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