<?php

/**
 * PurchaseInvoiceInstallmentInsert
 *
 * Endpoint khusus untuk menyimpan supplier_invoice dan supplier_invoice_detail
 * dari payload yang dikirim controller generator via cURL.
 */
class PurchaseInvoiceInstallmentInsert extends MY_Controller
{
    var $db;

    public function index()
    {
        echo "Purchase Invoice Installment Insert";
    }

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

    public function InsertSupplierInvoice()
    {
        try {
            $para = $this->sys_input;

            $required = [
                "nomorPI",
                "tanggalPI",
                "tanggalJatuhTempo",
                "jumlahCicilan",
                "catatan",
                "deskripsi",
                "userID",
                "purchaseOrderAssetContractID",
                "purchaseOrderID",
                "receiveOrderPoID",
                "supplierID",
                "purchaseOrderSummaryID",
                "purchaseOrderSummaryItemID",
                "purchaseOrderSummaryItemUnitID"
            ];

            foreach ($required as $field) {
                if (!isset($para[$field]) || $para[$field] === "" || $para[$field] === null) {
                    throw new Exception("Field wajib belum lengkap: " . $field);
                }
            }

            $tanggalPI = $para["tanggalPI"];
            $tanggalJatuhTempo = $para["tanggalJatuhTempo"];
            if (!$this->isValidDate($tanggalPI) || !$this->isValidDate($tanggalJatuhTempo)) {
                throw new Exception("Format tanggal tidak valid. Gunakan YYYY-MM-DD.");
            }

            $jumlahCicilan = (float) $para["jumlahCicilan"];
            if ($jumlahCicilan <= 0) {
                throw new Exception("jumlahCicilan harus lebih besar dari 0.");
            }

            $receiveOrderPoID = (int) $para["receiveOrderPoID"];
            $monthKey = date("Y-m", strtotime($tanggalPI));

            $sqlDuplikat = "SELECT SupplierInvoiceID, SupplierInvoiceNumber
                FROM supplier_invoice
                WHERE SupplierInvoiceIsActive = 'Y'
                    AND SupplierInvoiceStatus = 'Draft'
                    AND SupplierInvoiceReceiveOrderPoID = ?
                    AND DATE_FORMAT(SupplierInvoiceDate, '%Y-%m') = ?
                LIMIT 1";

            $qryDuplikat = $this->db->query($sqlDuplikat, [$receiveOrderPoID, $monthKey]);
            if (!$qryDuplikat) {
                $this->sys_error_db("Gagal mengecek duplikasi supplier_invoice.");
                exit;
            }

            if ($qryDuplikat->num_rows() > 0) {
                $existing = $qryDuplikat->row_array();
                $this->sys_ok([
                    "duplicate" => true,
                    "supplierInvoiceID" => $existing["SupplierInvoiceID"],
                    "supplierInvoiceNumber" => $existing["SupplierInvoiceNumber"]
                ]);
                return;
            }

            $this->db->trans_begin();

            $sqlHeader = "INSERT INTO supplier_invoice (
                    SupplierInvoiceNumber,
                    SupplierInvoiceReceiveOrderPoID,
                    SupplierInvoiceDate,
                    SupplierInvoiceDueDate,
                    SupplierInvoiceDraftPaymentDate,
                    SupplierInvoiceSupplierID,
                    SupplierInvoiceSupplierInvoiceNumber,
                    SupplierInvoiceSupplierInvoiceDate,
                    SupplierInvoiceSubTotal,
                    SupplierInvoiceDiscountPercent,
                    SupplierInvoiceDiscountAmount,
                    SupplierInvoiceTaxPercentPph,
                    SupplierInvoiceTaxAmountPph,
                    SupplierInvoiceTaxPercentPpn,
                    SupplierInvoiceTaxAmountPpn,
                    SupplierInvoiceShippingCost,
                    SupplierInvoiceAdjustmentAmount,
                    SupplierInvoiceAdjustmentNote,
                    SupplierInvoiceGrandTotal,
                    SupplierInvoiceUnpaid,
                    SupplierInvoiceNote,
                    SupplierInvoiceStatus,
                    SupplierInvoiceCreatedUserID
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

            $qryHeader = $this->db->query($sqlHeader, [
                $para["nomorPI"],
                $receiveOrderPoID,
                $tanggalPI,
                $tanggalJatuhTempo,
                $tanggalPI,
                (int) $para["supplierID"],
                null,
                null,
                $jumlahCicilan,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                null,
                $jumlahCicilan,
                $jumlahCicilan,
                $para["catatan"],
                "Draft",
                (int) $para["userID"]
            ]);

            if (!$qryHeader) {
                $this->db->trans_rollback();
                $this->sys_error_db("Gagal insert header supplier_invoice.");
                exit;
            }

            $supplierInvoiceID = $this->db->insert_id();

            $sqlDetail = "INSERT INTO supplier_invoice_detail (
                    SupplierInvoiceDetailSupplierInvoiceID,
                    SupplierInvoiceDetailPurchaseOrderID,
                    SupplierInvoiceDetailReceiveOrderPoID,
                    SupplierInvoiceDetailPurchaseOrderSummaryID,
                    SupplierInvoiceDetailItemID,
                    SupplierInvoiceDetailItemUnitID,
                    SupplierInvoiceDetailDescription,
                    SupplierInvoiceDetailQty,
                    SupplierInvoiceDetailPrice,
                    SupplierInvoiceDetailDiscountPercent,
                    SupplierInvoiceDetailDiscountDiscountRupiah,
                    SupplierInvoiceDetailDiscountDiscountType,
                    SupplierInvoiceDetailDiscountPoProrata,
                    SupplierInvoiceDetailDiscountAmount,
                    SupplierInvoiceDetailTotal,
                    SupplierInvoiceDetailUnpaid,
                    SupplierInvoiceDetailCreatedUserID
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

            $qryDetail = $this->db->query($sqlDetail, [
                $supplierInvoiceID,
                (int) $para["purchaseOrderID"],
                $receiveOrderPoID,
                (int) $para["purchaseOrderSummaryID"],
                (int) $para["purchaseOrderSummaryItemID"],
                (int) $para["purchaseOrderSummaryItemUnitID"],
                $para["deskripsi"],
                1,
                $jumlahCicilan,
                0,
                0,
                "R",
                0,
                0,
                $jumlahCicilan,
                $jumlahCicilan,
                (int) $para["userID"]
            ]);

            if (!$qryDetail) {
                $this->db->trans_rollback();
                $this->sys_error_db("Gagal insert detail supplier_invoice_detail.");
                exit;
            }

            if ($this->db->trans_status() === false) {
                $this->db->trans_rollback();
                $this->sys_error_db("Transaksi insert supplier_invoice gagal.");
                exit;
            }

            $this->db->trans_commit();

            $this->sys_ok([
                "duplicate" => false,
                "supplierInvoiceID" => $supplierInvoiceID,
                "supplierInvoiceNumber" => $para["nomorPI"]
            ]);
        } catch (Exception $exc) {
            $this->sys_error($exc->getMessage());
        }
    }

    private function isValidDate($tanggal)
    {
        $d = DateTime::createFromFormat("Y-m-d", $tanggal);
        return $d && $d->format("Y-m-d") === $tanggal;
    }
}
