<?php
session_start();
include 'db.php';

// 🧾 Input Data
$customer_name   = $_POST['customer_name'] ?? 'Walk-in';
$cart_json       = $_POST['cart_json'] ?? '[]';
$tax_amount      = floatval($_POST['tax_amount'] ?? 0);
$total_amount    = floatval($_POST['total_amount'] ?? 0);
$discount_amount = 0.00;
$payment_method  = 'cash';

$cart = json_decode($cart_json, true);
$invoice_number = 'INV' . time();
$net_amount = 0;

// 💵 Calculate net amount
foreach ($cart as $item) {
    $price = floatval($item['price']);
    $qty   = intval($item['qty']);
    $item_total = $price * $qty;
    $net_amount += $item_total;
}

// 🧾 Insert into `sales`
$stmt = $conn->prepare("INSERT INTO sales (invoice_number, customer_name, total_amount, tax_amount, discount_amount, net_amount, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssdddds", $invoice_number, $customer_name, $total_amount, $tax_amount, $discount_amount, $net_amount, $payment_method);
$stmt->execute();
$sale_id = $stmt->insert_id;
$stmt->close();

// 🧾 Insert into `sale_items`
$item_stmt = $conn->prepare("INSERT INTO sale_items (sale_id, item_id, item_name, unit_price, quantity, total_price, tax_rate) VALUES (?, ?, ?, ?, ?, ?, ?)");
foreach ($cart as $item) {
    $item_id   = intval($item['id'] ?? 0);
    $name      = $item['name'];
    $price     = floatval($item['price']);
    $qty       = intval($item['qty']);
    $total     = $price * $qty;
    $tax_rate  = isset($item['tax_rate']) ? floatval($item['tax_rate']) : 0.00;

    $item_stmt->bind_param("iisdidd", $sale_id, $item_id, $name, $price, $qty, $total, $tax_rate);
    $item_stmt->execute();
}
$item_stmt->close();

$_SESSION['last_sale_id'] = $sale_id;

// 🔍 Fetch PCT Codes (sku_number) from items table
$pct_codes = [];
$result = $conn->query("SELECT id, sku_number FROM items");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $pct_codes[$row['id']] = $row['sku_number'];
    }
}

// 🔍 Fetch FBR configuration
$fbr_config = [
    'enabled' => false,
    'api_url' => '',
    'pos_id' => '',
    'usin' => ''
];

$result = $conn->query("SELECT * FROM fbr_config LIMIT 1");
if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $fbr_config = [
        'enabled' => $row['is_enabled'] == 1,
        'api_url' => $row['api_url'],
        'pos_id' => $row['pos_id'],
        'usin' => $row['usin']
    ];
}

if ($fbr_config['enabled']) {
    // 📦 Prepare FBR Items
    $items_for_fbr = [];
    $item_result = $conn->query("SELECT item_id, item_name, unit_price, quantity, tax_rate FROM sale_items WHERE sale_id = $sale_id");
    if ($item_result) {
        while ($row = $item_result->fetch_assoc()) {
            $tax_charged = ($row['unit_price'] * $row['quantity']) * ($row['tax_rate'] / 100);
            $pct_code = isset($pct_codes[$row['item_id']]) ? $pct_codes[$row['item_id']] : '00000000';

            $items_for_fbr[] = [
                "ItemCode"     => (string)$row['item_id'],
                "ItemName"     => $row['item_name'],
                "PCTCode"      => $pct_code,
                "Quantity"     => (float)$row['quantity'],
                "TaxRate"      => (float)$row['tax_rate'],
                "SaleValue"    => (float)($row['unit_price'] * $row['quantity']),
                "Discount"     => 0.00,
                "FurtherTax"   => 0.00,
                "TaxCharged"   => $tax_charged,
                "TotalAmount"  => (float)(($row['unit_price'] * $row['quantity']) + $tax_charged),
                "InvoiceType"  => 1,
                "RefUSIN"      => null
            ];
        }
    }

    // 📤 FBR Payload
    $fbr_data = [
        "InvoiceNumber"    => "",
        "POSID"            => $fbr_config['pos_id'],
        "USIN"             => $invoice_number,
        "DateTime"         => date('Y-m-d H:i:s'),
        "BuyerNTN"         => "",
        "BuyerCNIC"        => "",
        "BuyerName"        => $customer_name,
        "BuyerPhoneNumber" => "",
        "TotalBillAmount"  => $total_amount,
        "TotalQuantity"    => (float)array_sum(array_column($cart, 'qty')),
        "TotalSaleValue"   => $net_amount,
        "TotalTaxCharged"  => $tax_amount,
        "Discount"         => $discount_amount,
        "FurtherTax"       => 0.00,
        "PaymentMode"      => 1,
        "RefUSIN"          => null,
        "InvoiceType"      => 1,
        "Items"            => $items_for_fbr
    ];

    $jsonData = json_encode($fbr_data);
    file_put_contents('fbr_last_payload.json', $jsonData);

    $ch = curl_init($fbr_config['api_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)) {
        error_log("Curl error: " . curl_error($ch));
        echo "Failed to connect to FBR API.";
        exit;
    }
    curl_close($ch);
    file_put_contents('fbr_last_response.json', $response);

    $fbr_response = json_decode($response, true);

    // 🔒 Log FBR response
    $stmt = $conn->prepare("INSERT INTO fbr_logs (sale_id, response) VALUES (?, ?)");
    $response_json = json_encode($fbr_response, JSON_UNESCAPED_UNICODE);
    $stmt->bind_param("is", $sale_id, $response_json);
    $stmt->execute();
    $stmt->close();

    if (!empty($fbr_response['InvoiceNumber']) && $fbr_response['InvoiceNumber'] !== "Not Available") {
        $fbr_invoice = $fbr_response['InvoiceNumber'];
        $qr_data = $fbr_response['QRData'] ?? null;

        $stmt = $conn->prepare("INSERT INTO fbr_invoices (sale_id, fbr_invoice_number, qr_code) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $sale_id, $fbr_invoice, $qr_data);
        $stmt->execute();
        $stmt->close();

        $stmt = $conn->prepare("UPDATE sales SET is_fbr_enabled = 1, fbr_invoice_number = ?, fbr_qr_data = ? WHERE id = ?");
        $stmt->bind_param("ssi", $fbr_invoice, $qr_data, $sale_id);
        $stmt->execute();
        $stmt->close();

        echo "success";
    } else {
        error_log("FBR API error. Response: " . $response);
        echo "FBR invoice generation failed.";
    }
} else {
    // FBR is disabled — just update sales table to reflect it
    $stmt = $conn->prepare("UPDATE sales SET is_fbr_enabled = 0 WHERE id = ?");
    $stmt->bind_param("i", $sale_id);
    $stmt->execute();
    $stmt->close();

    echo "success";
}
?>
