<?php

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

            $startdate = $payload["startdate"];
            $enddate = $payload["enddate"];

            $query = "SELECT pv.*,
                        M_BranchID,
                      M_BranchCode,
                      M_BranchName,
                      CONCAT(cs.coaAccountNo, ' | ', cs.coaDescription) as CoaSource,
                      -- CONCAT(ce.coaAccountNo, ' | ', ce.coaDescription) as CoaExpense,
                      CONCAT(ct.coaAccountNo, ' | ', ct.coaDescription) as CoaTemporary,
                      cs.coaDescription coaDescriptionSource,
                      -- ce.coaDescription coaDescriptionExpense,
                      ct.coaDescription coaDescriptionTemporary,
                      cs.coaAccountNo coaAccountNoSource,
                      -- ce.coaAccountNo coaAccountNoExpense,
                      ct.coaAccountNo coaAccountNoTemporary
                      FROM payment_voucher as pv
                      LEFT JOIN m_branch ON M_BranchCode = PaymentVoucherM_BranchCode
                      JOIN coa cs ON cs.coaID = PaymentVoucherCoaSourceID
                      -- JOIN coa ce ON ce.coaID = PaymentVoucherCoaExpenseID
                      JOIN coa ct ON ct.coaID = PaymentVoucherCoaTemporaryID
                      WHERE PaymentVoucherIsActive = 'Y' 
                      AND DATE(PaymentVoucherDate) BETWEEN '{$startdate}' AND '{$enddate}'
                      AND (PaymentVoucherNumber LIKE '%" . $payload["search"] . "%')";
            $queryCount = "SELECT count(*) as total
                           FROM payment_voucher as pv
                           WHERE PaymentVoucherIsActive = 'Y' 
                           AND DATE(PaymentVoucherDate) BETWEEN '{$startdate}' AND '{$enddate}'
                           AND (PaymentVoucherNumber LIKE '%" . $payload["search"] . "%')";

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

            if ($payload["status"] !== 'All') {
                $query .= " AND PaymentVoucherStatus = '{$payload["status"]}'";
                $queryCount .= " AND PaymentVoucherStatus = '{$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 payment voucher", $this->db);;
                exit;
            }

            $query .= " ORDER BY PaymentVoucherDate 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 payment voucher", $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 payment_voucher_detail
                           WHERE PaymentVoucherDetailIsActive = 'Y' 
                           AND PaymentVoucherDetailPaymentVoucherID = {$payload['ID']}";
            $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 payment voucher detail", $this->db);;
                exit;
            }

            $query = "SELECT payment_voucher_detail.*, 
                      ROW_NUMBER() OVER(ORDER BY PaymentVoucherDetailID) RowNumber,
                      PurchaseRequestDirectID,
                      PurchaseRequestDirectNumber,
                      PurchaseRequestDirectTotalRealitation,
                      PurchaseRequestDirectAccountFilled
                      FROM payment_voucher_detail 
                      LEFT JOIN purchase_request_direct ON PurchaseRequestDirectID = PaymentVoucherDetailPurchaseRequestDirectID
                      WHERE PaymentVoucherDetailIsActive = 'Y' 
                      AND PaymentVoucherDetailPaymentVoucherID = {$payload['ID']}";
            $exec = $this->db->query($query, []);

            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select payment voucher 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 voucherDetailItem() {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $para = $this->sys_input;

            $sql = "SELECT 
                PurchaseDirectCategoryID,
                PurchaseDirectCategoryName,
                PurchaseRequestDirectDescription,
                PurchaseRequestDirectDetailID,
                PurchaseRequestDirectDetailItemUnitID,
                PurchaseRequestDirectDetailTotalEstimationPrice,
                PurchaseRequestDirectDetailPurchaseRequestDirectID,
                IFNULL(PurchaseRequestDirectDetailAccount, '') as account_number,
                '' as err_message
            FROM purchase_request_direct_detail
            JOIN purchase_direct_category ON PurchaseDirectCategoryID = PurchaseRequestDirectDetailPurchaseRequestDirectCategoryID
            WHERE PurchaseRequestDirectDetailIsActive = 'Y'
            AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ?";
            $que = $this->db->query($sql, [$para['PRDirectID']]);
            if (!$que) {
                $this->sys_error_db("[Error] get detail item voucher purchase request direct");
                exit;
            }
            $data = $que->result_array();

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

    function getBranch()
    {
        try {
            $payload = $this->sys_input;
            $query = "SELECT DISTINCT
                      M_BranchCode,
                      M_BranchName
                      FROM m_branch
                      WHERE M_BranchIsActive = 'Y'
                      AND (M_BranchCode LIKE '%" . $payload["search"] . "%' OR M_BranchName LIKE '%" . $payload["search"] . "%')
                      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 getCoa()
    {
        try {
            $payload = $this->sys_input;
            $query = "SELECT * FROM coa
                      WHERE coaIsActive = 'Y' AND coaIsInput = 'Y'
                      AND (coaAccountNo LIKE '%" . $payload["search"] . "%' OR coaDescription LIKE '%" . $payload["search"] . "%')
                      ORDER BY coaAccountNo ASC";
            $exec = $this->db->query($query, []);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select coa", $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 getPurchase()
    {
        try {
            $payload = $this->sys_input;
            $query = "SELECT prd.*, u.M_UserUsername as user_request
                      FROM purchase_request_direct prd
                      JOIN m_user u ON prd.PurchaseRequestCreatedUserID = u.M_UserID
                      WHERE prd.PurchaseRequestDirectIsActive = 'Y'
                      AND prd.PurchaseRequestDirectApprovedBy IS NOT NULL
                      AND prd.PurchaseRequestDirectM_BranchCode = '{$payload["branchcode"]}'
                      AND prd.PurchaseRequestDirectID not in ( 
            select PaymentVoucherDetailPurchaseRequestDirectID from payment_voucher
            JOIN payment_voucher_detail ON PaymentVoucherDetailPaymentVoucherID = PaymentVoucherID AND PaymentVoucherDetailIsActive = 'Y'
            where PaymentVoucherIsActive = 'Y')
                      ORDER BY prd.PurchaseRequestDirectNumber 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 getTotalApproved()
    {
        try {
            $payload = $this->sys_input;
            $total = 0;
            $query = "SELECT COUNT(*) as total
                      FROM purchase_request_direct
                      WHERE PurchaseRequestDirectIsActive = 'Y'
                      AND PurchaseRequestDirectApprovedBy IS NOT NULL
                      AND PurchaseRequestDirectM_BranchCode = '{$payload["branchcode"]}'
                      AND PurchaseRequestDirectID not in ( 
            select PaymentVoucherDetailPurchaseRequestDirectID from payment_voucher
            JOIN payment_voucher_detail ON PaymentVoucherDetailPaymentVoucherID = PaymentVoucherID AND PaymentVoucherDetailIsActive = 'Y'
            where PaymentVoucherIsActive = 'Y')";
            $exec = $this->db->query($query);
            if ($exec) {
                $total = $exec->row()->total;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch", $this->db);
                exit;
            }

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

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

    function save()
    {
        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`('PV') AS PV";
            $exec = $this->db->query($pdSql, []);
            $pd = "";
            $dateNow = date('Y-m-d');

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

            $sql = "INSERT INTO payment_voucher(
                    PaymentVoucherDate,
                    PaymentVoucherNumber,
                    PaymentVoucherM_BranchCode,	
                    PaymentVoucherCoaSourceID,	
                    PaymentVoucherCoaExpenseID,	
                    PaymentVoucherCoaTemporaryID,
                    PaymentVoucherTotal,
                    PaymentVoucherStatus,
                    PaymentVoucherUserID,	
                    PaymentVoucherCreated,	
                    PaymentVoucherLastUpdated)
                     VALUES ('{$dateNow}', 
                     '{$pd}', 
                     '{$payload['BranchCode']}', 
                     '{$payload['CoaSourceID']}',
                     '{$payload['CoaExpenseID']}',
                     '{$payload['CoaTemporaryID']}',
                     '{$payload['total']}',
                     'Draft',
                     {$userId}, 
                     now(),
                     now())";
            $exec = $this->db->query($sql);
            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("payment voucher insert error", $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();
            foreach ($payload['details'] as $k => $v) {
                $sql = "INSERT INTO payment_voucher_detail(
                    PaymentVoucherDetailPaymentVoucherID,	
                    PaymentVoucherDetailPurchaseRequestDirectID,	
                    PaymentVoucherDetailTotal,	
                    PaymentVoucherDetailUserID,	
                    PaymentVoucherDetailCreated,	
                    PaymentVoucherDetailLastUpdated)
                     VALUES ('{$last_id}', 
                     '{$v['PurchaseRequestDirectID']}', 
                     '{$v['PurchaseRequestDirectTotalRealitation']}',
                     {$userId}, 
                     now(),
                     now())";
                $exec = $this->db->query($sql);
                if (!$exec) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("payment voucher detail insert error", $this->db);
                    exit;
                }
            }
            $this->db->trans_commit();

            $newInsert = "SELECT * FROM payment_voucher WHERE PaymentVoucherNumber = '{$pd}' AND PaymentVoucherIsActive = '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 update()
    {
        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 payment_voucher SET
                    PaymentVoucherM_BranchCode = '{$payload['BranchCode']}', 	
                    PaymentVoucherCoaSourceID = '{$payload['CoaSourceID']}', 	
                    PaymentVoucherCoaExpenseID = '{$payload['CoaExpenseID']}', 
                    PaymentVoucherCoaTemporaryID = '{$payload['CoaTemporaryID']}', 
                    PaymentVoucherTotal = '{$payload['total']}', 
                    PaymentVoucherUserID = {$userId},
                    PaymentVoucherLastUpdated = now()
                    WHERE PaymentVoucherID = {$payload['ID']}";
            $exec = $this->db->query($sql, []);

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

            $sql = "DELETE FROM payment_voucher_detail WHERE PaymentVoucherDetailPaymentVoucherID = {$payload['ID']}";
            $exec = $this->db->query($sql, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("payment voucher detail delete error", $this->db);
                exit;
            }
            foreach ($payload['details'] as $k => $v) {
                $sql = "INSERT INTO payment_voucher_detail(
                    PaymentVoucherDetailPaymentVoucherID,	
                    PaymentVoucherDetailPurchaseRequestDirectID,	
                    PaymentVoucherDetailTotal,	
                    PaymentVoucherDetailUserID,	
                    PaymentVoucherDetailCreated,	
                    PaymentVoucherDetailLastUpdated)
                     VALUES ('{$payload['ID']}', 
                     '{$v['PurchaseRequestDirectID']}', 
                     '{$v['PurchaseRequestDirectTotalRealitation']}',
                     {$userId}, 
                     now(),
                     now())";
                $exec = $this->db->query($sql);
                if (!$exec) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("payment voucher detail insert error", $this->db);
                    exit;
                }
            }
            $this->db->trans_commit();

            $newUpdate = "SELECT * FROM payment_voucher WHERE PaymentVoucherID = {$payload['ID']} AND PaymentVoucherIsActive = '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 delete()
    {
        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 payment_voucher SET
                    PaymentVoucherIsActive = 'N'
                    WHERE PaymentVoucherID = {$payload['ID']}";
            $exec = $this->db->query($sql, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("payment voucher delete error", $this->db);
                exit;
            }
            $sql = "UPDATE payment_voucher_detail SET
                    PaymentVoucherDetailIsActive = 'N'
                    WHERE PaymentVoucherDetailPaymentVoucherID = {$payload['ID']}";
            $exec = $this->db->query($sql, []);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("payment voucher detail 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 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 payment_voucher_detail SET
                          PaymentVoucherDetailLastUpdated = NOW(),
                          PaymentVoucherDetailLastUpdatedUserID = {$userId}
                          WHERE PaymentVoucherDetailPaymentVoucherID = {$payload["ID"]}
                          AND PaymentVoucherDetailIsActive = 'Y'
                          AND PaymentVoucherDetailStatus = 'Pending'";
            $exec = $this->db->query($sqlDetail, []);

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

            $sql = "UPDATE payment_voucher SET
                PaymentVoucherStatus = 'Pending',
                PurchaseRequestLastUpdated = NOW(),
                PurchaseRequestLastUpdatedUserID = {$userId}
                WHERE PaymentVoucherID = {$payload["ID"]}
                AND PaymentVoucherIsActive = 'Y'";
            $exec = $this->db->query($sql, []);

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

            $this->db->trans_commit();

            $sql = "SELECT *, 
                    ROW_NUMBER() OVER(ORDER BY PaymentVoucherNumber) RowNumber 
                    FROM payment_voucher 
                    WHERE PaymentVoucherIsActive = 'Y' 
                    AND PaymentVoucherUserID = {$userId}
                    AND PaymentVoucherID = {$payload["ID"]}";
            $exec = $this->db->query($sql, []);

            $row = [];
            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("order payment voucher 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 saveAccountDetail() {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db->trans_begin();
            $param = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            foreach ($param['detail'] as $key => $obj) {
                $sql = "UPDATE purchase_request_direct_detail SET 
                    PurchaseRequestDirectDetailAccount = ?, 
                    PurchaseRequestDirectDetailLastUpdatedUserID = ?, 
                    PurchaseRequestDirectDetailLastUpdated = NOW() 
                WHERE PurchaseRequestDirectDetailID = ? ";
                $que = $this->db->query($sql, [
                    $obj['account_number'], $userId,
                    $obj['PurchaseRequestDirectDetailID']
                ]);
                if (!$que) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] update account item voucher", $this->db);
                    exit;
                }
            }

            $sqlheader = "UPDATE purchase_request_direct SET 
                PurchaseRequestDirectAccountFilled = 'Y'
            WHERE PurchaseRequestDirectID = ?";
            $queheader = $this->db->query($sqlheader, [$param['PRDID']]);
            if (!$queheader) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update header status account is filled", $this->db);
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok("[Success]");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

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

            $query = "SELECT *, 'N' as flag_isadd
                      FROM purchase_request_direct
                      WHERE PurchaseRequestDirectIsActive = 'Y'
                      AND PurchaseRequestDirectApprovedBy IS NOT NULL
                      AND PurchaseRequestDirectM_BranchCode = '{$payload["branchcode"]}'";
            $exec = $this->db->query($query, []);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select request", $this->db);
                exit;
            }

            // print_r($rows);
            // exit;

            foreach ($rows as $k => $v) {
                $PurchaseRequestDirectID = $v["PurchaseRequestDirectID"];
                $sql = "SELECT * 
                    FROM payment_voucher_detail
                    WHERE PaymentVoucherDetailIsActive = 'Y'
                    AND PaymentVoucherDetailPurchaseRequestDirectID = {$PurchaseRequestDirectID}";
                $qry = $this->db->query($sql, []);
                if ($qry) {
                    $rows_detail = $qry->result_array();
                } else {
                    $this->db->trans_rollback();
                    $this->sys_error_db("select detail", $this->db);
                    exit;
                }

                // print_r($rows_detail);
                // exit;

                if (count($rows_detail) > 0) {
                    $rows[$k]['flag_isadd'] = 'Y';
                }
            }

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

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

            $query = "SELECT *, 'N' as flag_isadd
                      FROM purchase_request_direct
                      WHERE PurchaseRequestDirectIsActive = 'Y'
                      AND PurchaseRequestDirectApprovedBy IS NOT NULL
                      AND PurchaseRequestDirectM_BranchCode = '{$payload["branchcode"]}'
                      AND PurchaseRequestDirectID not in ( 
            select PaymentVoucherDetailPurchaseRequestDirectID 
            from payment_voucher
            JOIN payment_voucher_detail ON PaymentVoucherDetailPaymentVoucherID = PaymentVoucherID AND PaymentVoucherDetailIsActive = 'Y'
            where PaymentVoucherIsActive = 'Y' AND
            PaymentVoucherDetailPaymentVoucherID <> '{$payload["ID"]}' AND
            PaymentVoucherM_BranchCode = '{$payload["branchcode"]}'

            union
            select PaymentVoucherDetailPurchaseRequestDirectID 
            from payment_voucher
            JOIN payment_voucher_detail ON PaymentVoucherDetailPaymentVoucherID = PaymentVoucherID AND PaymentVoucherDetailIsActive = 'Y'
            where PaymentVoucherIsActive = 'Y' AND
            PaymentVoucherDetailPaymentVoucherID = '{$payload["ID"]}' AND
            PaymentVoucherM_BranchCode = '{$payload["branchcode"]}'

            
            )
                      UNION
                      SELECT purchase_request_direct.*, 'Y' as flag_isadd
                      FROM payment_voucher_detail
                      JOIN purchase_request_direct ON PurchaseRequestDirectID = PaymentVoucherDetailPurchaseRequestDirectID
                      WHERE PaymentVoucherDetailIsActive = 'Y' AND PaymentVoucherDetailPaymentVoucherID = '{$payload["ID"]}'";
            $exec = $this->db->query($query, []);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select request", $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 moveToKasir() {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db->trans_begin();
            $param = $this->sys_input;

            $sql = "UPDATE payment_voucher SET
                PaymentVoucherStatus = 'Draft' 
                WHERE PaymentVoucherID = ?";
            $que = $this->db->query($sql, $param['ID']);
            if (!$que) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] edit voucher status to draft");
                exit;
            }

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