<?php
include 'db.php'; // ✅ Include DB connection

// ------------------------
// 1. Prepare Invoice Data
// ------------------------
$data = [
    "InvoiceNumber" => "",
    "POSID" => 110014, // Replace with your actual POSID
    "USIN" => "USIN1001",
    "DateTime" => date('Y-m-d H:i:s'),
    "BuyerNTN" => "1234567-8",
    "BuyerCNIC" => "1234512345671",
    "BuyerName" => "Shahzad Ahmed",
    "BuyerPhoneNumber" => "03001234567",
    "TotalBillAmount" => 1519.00,
    "TotalQuantity" => 15.0,
    "TotalSaleValue" => 1298.00,
    "TotalTaxCharged" => 221.00,
    "Discount" => 380.00,
    "FurtherTax" => 0.00,
    "PaymentMode" => 1, // 1 = Cash
    "RefUSIN" => null,
    "InvoiceType" => 1,
    "Items" => [
        [
            "ItemCode" => "0001",
            "ItemName" => "Blanket",
            "PCTCode" => "01011000",
            "Quantity" => 1.00,
            "TaxRate" => 17.00,
            "SaleValue" => 1298.00,
            "Discount" => 380.00,
            "FurtherTax" => 0.00,
            "TaxCharged" => 221.00,
            "TotalAmount" => 1519.00,
            "InvoiceType" => 1,
            "RefUSIN" => null
        ]
    ]
];

$jsonData = json_encode($data);

// ------------------------
// 2. Send to FBR IMS
// ------------------------
$url = "http://localhost:8524/api/IMSFiscal/GetInvoiceNumberByModel";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
    exit;
}

curl_close($ch);

// ------------------------
// 3. Handle Response
// ------------------------
$data = json_decode($response, true);

echo "<pre>";
print_r($data);
echo "</pre>";

// ------------------------
// 4. Save Invoice Number (optional)
// ------------------------
if ($data['Code'] == '100') {
    $fbr_invoice = $data['InvoiceNumber'];
    $usin = "USIN1001"; // Match this with the one in the invoice

    $sql = "UPDATE sales SET fbr_invoice_number = '$fbr_invoice' WHERE usin = '$usin'";
    if ($conn->query($sql)) {
        echo "<p>✅ FBR Invoice saved to DB successfully.</p>";
    } else {
        echo "<p>❌ DB Error: " . $conn->error . "</p>";
    }
}

?>
