<?php
class Billv2 extends MY_Controller {
    var $db;
    public function index() {
        echo "Bill V2 API";
    }

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

    public function search() {
        try {
            if (!$this->isLogin) {
                throw new Exception("Invalid token", 1);
            }

            $params = $this->sys_input;

            $keyword = "%";
            if ($params['search'] != '') {
                $keyword .= $params['search'] . "%";
            }

            $offset = 0;
            $limit = 5;
            if ($params['currentpage'] > 0) {
                $offset = ($params['currentpage'] - 1) * $limit;
            }

            $sql_base = "SELECT 
                SupplierPaymentID,
                SupplierPaymentDate,
                SupplierPaymentNumber,
                SupplierPaymentAmount,
                SupplierPaymentStatus,
                SupplierPaymentIsVerif,
                SupplierPaymentIsApproved,
                SupplierInvoiceID,
                SupplierInvoiceNumber,
                SupplierInvoiceDraftPaymentDate,
                SupplierCode,
                SupplierName
            FROM supplier_payment 
            JOIN supplier_invoice ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID 
                AND SupplierPaymentNumber LIKE ?
                AND (SupplierPaymentDate BETWEEN DATE(?) AND DATE(?))
                AND (SupplierPaymentStatus = ? OR ? = 'All')
            JOIN supplier ON SupplierID = SupplierInvoiceSupplierID
            WHERE SupplierPaymentIsActive = 'Y' 
            ORDER BY SupplierPaymentID DESC";

            $sql_data = $sql_base . " LIMIT ? OFFSET ? ";
            $que_data = $this->db->query($sql_data, [
                $keyword, $params['startdate'], $params['enddate'],
                $params['status'], $params['status'], $limit, $offset
            ]);
            if (!$que_data) {
                throw new Exception("[Error] failed get data supplier payment", 2);
            }

            $sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) AS x";
            $que_total = $this->db->query($sql_total, [
                $keyword, $params['startdate'], $params['enddate'],
                $params['status'], $params['status']
            ]);
            if (!$que_total) {
                throw new Exception("[Error] failed get total data supplier payment", 2);
            }

            $output = [
                "records" => $que_data->result_array(),
                "total" =>$que_total->row_array()['total']
            ];
            
            $this->sys_ok($output);
            exit;
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $code = $exc->getCode();

            if ($code == 1) {
                $this->sys_error($message);
            } else {
                $this->sys_error_db($message);
            }
            exit;
        }
    }

    public function searchDetail() {
        try {
            if (!$this->isLogin) {
                throw new Exception("invalid token", 1);
            }

            $para = $this->sys_input;

            $sql = "SELECT 
                SupplierInvoiceID, 
                SupplierInvoiceRefNumber,
                SupplierInvoiceDeliveryOrderNumber,
                SupplierInvoiceSupplierInvoiceNumber,
                SupplierInvoiceSupplierInvoiceDate,
                SupplierInvoiceSubTotal,
                SupplierInvoiceTaxPercentPph,
                SupplierInvoiceTaxPercentPpn,
                SupplierInvoiceTaxAmountPpn,
                SupplierInvoiceDiscountAmount,
                SupplierInvoiceDiscountPercent,
                SupplierInvoiceShippingCost,
                SupplierInvoiceGrandTotal,
                SupplierInvoiceAdjustmentAmount,
                SupplierInvoiceAdjustmentNote,
                SupplierInvoiceNote,
                IF (SupplierInvoiceDiscountAmount > 0, 'R', 'P') AS DiscountType
            FROM supplier_payment 
            JOIN supplier_invoice ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID 
                AND SupplierPaymentID = ?
                AND SupplierPaymentIsActive = 'Y'";
            $que = $this->db->query($sql, [$para['paymentID']]);
            if (!$que) {
                throw new Exception("[Error] failed get row data", 2);
            }
            $data = $que->row_array();

            $sql_detail = "SELECT 
                SupplierInvoiceDetailID,
                SupplierInvoiceDetailSupplierInvoiceID,
                SupplierInvoiceDetailPurchaseOrderID,
                SupplierInvoiceDetailPurchaseOrderSummaryID,
                SupplierInvoiceDetailReceiveOrderPoID,
                SupplierInvoiceDetailReceiveOrderPoDetailID,
                SupplierInvoiceDetailItemID,
                SupplierInvoiceDetailItemUnitID,
                SupplierInvoiceDetailDescription,
                SupplierInvoiceDetailQty,
                SupplierInvoiceDetailPrice,
                SupplierInvoiceDetailDiscountPercent,
                SupplierInvoiceDetailDiscountDiscountRupiah,
                SupplierInvoiceDetailDiscountDiscountType,
                SupplierInvoiceDetailDiscountAmount,
                (SupplierInvoiceDetailPrice - SupplierInvoiceDetailDiscountAmount) AS DiscountedPrice,
                SupplierInvoiceDetailDiscountPoProrata,
                SupplierInvoiceDetailTotal,
                M_ItemCode,
                M_ItemDesc
            FROM supplier_payment_detail 
            JOIN supplier_invoice_detail ON SupplierInvoiceDetailIsActive = 'Y'
                AND SupplierPaymentDetailSupplierPaymentID = ?
                AND SupplierInvoiceDetailSupplierInvoiceID = ?
            JOIN m_item ON M_ItemID = SupplierInvoiceDetailItemID 
                AND M_ItemIsActive = 'Y'
            GROUP BY SupplierInvoiceDetailID";
            $que_detail = $this->db->query($sql_detail, [
                $para['paymentID'], $data['SupplierInvoiceID']
            ]);
            if (!$que_detail) {
                throw new Exception("[Error] failed to get item payments", 2);
            }

            $data['detail'] = $que_detail->result_array();

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

            if ($code == 1) {
                $this->sys_error($message);
            } else {
                $this->sys_error_db($message);
            }
            exit;
        }
    }

    public function getUserApproveLevel() {
        try {
            if (!$this->isLogin) {
                throw new Exception("Invalid token", 1);
            }

            $userid = $this->sys_user['M_UserID'];
            $sql_level = "SELECT M_UserM_ApproveLevelID AS level
            FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ? ";
            $que_level = $this->db->query($sql_level, [$userid]);
            if (!$que_level) {
                throw new Exception("[Error] failed get user approve level", 2);
            }
            $data = $que_level->row_array();
            $this->sys_ok($data);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $code = $exc->getCode();

            if ($code == 1) {
                $this->sys_error($message);
            } else {
                $this->sys_error_db($message);
            }
            exit;
        }
    }

    public function updateStatusPayment() {
        try {
            if (!$this->isLogin) {
                throw new Exception("Invalid token", 1);
            }

            $this->db->trans_begin();
            $para = $this->sys_input;
            $user = $this->sys_user;

            if ($para['userlevel'] == '1') {
                $sql = "UPDATE supplier_payment SET 
                    SupplierPaymentIsVerif = 'Y',
                    SupplierPaymentStatus = 'Verified',
                    SupplierPaymentVerifUserID = ?,
                    SupplierPaymentVerifDate = NOW()
                WHERE SupplierPaymentID = ? 
                    AND SupplierPaymentIsActive = 'Y'";
                $query = $this->db->query($sql, [
                    $user['M_UserID'], $para['paymentID']
                ]);
                if (!$query) {
                    $this->db->trans_rollback();
                    throw new Exception("[Error] failed update status verified", 2);
                }
            }

            if ($para['userlevel'] == '2') {
                $sql = "UPDATE supplier_payment SET 
                    SupplierPaymentIsApproved = 'Y',
                    SupplierPaymentStatus = 'Approved',
                    SupplierPaymentApprovedUserID = ?,
                    SupplierPaymentApprovedDate = NOW()
                WHERE SupplierPaymentID = ? 
                    AND SupplierPaymentIsActive = 'Y'";
                $query = $this->db->query($sql, [
                    $user['M_UserID'], $para['paymentID']
                ]);
                if (!$query) {
                    $this->db->trans_rollback();
                    throw new Exception("[Error] failed update status approved", 2);
                }
            }

            $this->db->trans_commit();
            $this->sys_ok("[Success] success update status Payment");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $code = $exc->getCode();

            if ($code == 1) {
                $this->sys_error($message);
            } else {
                $this->sys_error_db($message);
            }
            exit;
        }
    }
}