<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'db.php';

function post_fbr_digital_invoice($conn, $sale_id)
{
    $errors = [];

    // 🔧 Load config
    $fbr = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM fbr_digital LIMIT 1"));
    if (!$fbr || !$fbr['is_enabled']) {
        return ['success' => false, 'error' => 'FBR Digital integration is disabled.'];
    }

    // 🔎 Fetch sale
    $sale = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM sales WHERE id = $sale_id"));
    if (!$sale) return ['success' => false, 'error' => 'Sale not found.'];

    // 🔎 Branch info
    $branch = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM branch_info LIMIT 1"));
    if (!$branch || empty($branch['ntn'])) return ['success' => false, 'error' => 'Branch NTN missing.'];

    $seller_province = $branch['province'] ?? 'Punjab';

    // 🔎 Customer info
    $customer_name = $sale['customer_name'] ?: 'Walk-in Customer';
    $customer = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM customers WHERE name = '" . mysqli_real_escape_string($conn, $customer_name) . "' LIMIT 1")) ?? [];
    $is_walk_in = ($customer['is_walk_in'] ?? 1) == 1;

    $buyer_ntn     = $is_walk_in ? '' : ($customer['ntn'] ?? '');
    $buyer_province = $customer['province'] ?? 'Punjab';
    $buyer_address = $customer['address'] ?? '';

    // 🔎 Items
    $pct_codes = [];
    $sku_result = $conn->query("SELECT id, sku_number, uom_id FROM items");
    while ($row = $sku_result->fetch_assoc()) {
        $pct_codes[$row['id']] = ['hs' => $row['sku_number'], 'uom' => $row['uom_id']];
    }

    // 🔎 UOM map
    $uoms = [];
    $uom_result = $conn->query("SELECT id, name FROM uoms");
    while ($row = $uom_result->fetch_assoc()) {
        $uoms[$row['id']] = $row['name'];
    }

    // 🧾 Sale items
    $items = [];
    $res = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    while ($row = $res->fetch_assoc()) {
        $item_id = $row['item_id'];
        $sku     = $pct_codes[$item_id]['hs'] ?? '0000.0000';
        $uom_id  = $pct_codes[$item_id]['uom'] ?? null;
        $uom     = $uoms[$uom_id] ?? null;

        if (!$uom) $errors[] = "Missing UOM for item ID: {$item_id}";
        if (!$sku || strlen($sku) < 4) $errors[] = "Missing HS Code for item ID: {$item_id}";

        $unit_price = $row['unit_price'];
        $qty        = $row['quantity'];
        $tax_rate   = $row['tax_rate'];
        $exclusive  = $unit_price / (1 + ($tax_rate / 100));
        $tax        = $unit_price - $exclusive;

        $items[] = [
            "hsCode"                         => $sku,
            "productDescription"            => $row['item_name'],
            "rate"                          => round($tax_rate, 2) . '%',
            "uoM"                           => $uom,
            "quantity"                      => (int)$qty,
            "totalValues"                   => number_format(($exclusive + $tax) * $qty, 2, '.', ''),
            "valueSalesExcludingST"         => number_format($exclusive * $qty, 2, '.', ''),
            "fixedNotifiedValueOrRetailPrice" => number_format(0, 2, '.', ''),
            "salesTaxApplicable"            => number_format($tax * $qty, 2, '.', ''),
            "salesTaxWithheldAtSource"      => number_format(0, 2, '.', ''),
            "extraTax"                      => number_format(0, 2, '.', ''),
            "furtherTax"                    => number_format(0, 2, '.', ''),
            "fedPayable"                    => number_format(0, 2, '.', ''),
            "discount"                      => number_format(0, 2, '.', ''),
            "saleType"                      => "Goods at standard rate (default)",
            "sroScheduleNo"                 => "",
            "sroItemSerialNo"               => ""
        ];
    }

    if (empty($items)) return ['success' => false, 'error' => 'No sale items found.'];
    if ($errors) return ['success' => false, 'error' => implode(" | ", $errors)];

    // ✅ Build payload
    $payload = [
        "invoiceType"          => "Sale Invoice",
        "invoiceDate"          => date('Y-m-d', strtotime($sale['sale_date'])),
        "sellerNTNCNIC"        => $branch['ntn'],
        "sellerBusinessName"   => $branch['branch_name'] ?? 'Branch',
        "sellerProvince"       => $seller_province,
        "sellerAddress"        => $branch['branch_address'],
        "buyerNTNCNIC"         => $buyer_ntn,
        "buyerBusinessName"    => $customer_name,
        "buyerProvince"        => $buyer_province,
        "buyerAddress"         => $buyer_address,
        "buyerRegistrationType"=> $is_walk_in ? "Unregistered" : "Registered",
        "invoiceRefNo"         => "",
        "scenarioId"           => $fbr['mode'] === 'sandbox' ? "SN001" : "PRD001",
        "items"                => $items
    ];

    // 📤 CURL request
    $ch = curl_init($fbr['api_url']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . trim($fbr['token'])
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        return ['success' => false, 'error' => 'CURL Error: ' . curl_error($ch)];
    }
    curl_close($ch);

    file_put_contents("fbr_digital_raw_response_$sale_id.txt", $response);

    $data = json_decode($response, true);

    // Log formatted response & payload
    file_put_contents("fbr_digital_log_$sale_id.json", json_encode([
        'payload'  => $payload,
        'response' => $data
    ], JSON_PRETTY_PRINT));

    if (isset($data['validationResponse']) && $data['validationResponse']['statusCode'] === '00') {
        return ['success' => true, 'data' => $data];
    } else {
        $error = $data['validationResponse']['error'] ?? 'Unknown FBR response error.';
        return ['success' => false, 'error' => $error];
    }
}
?>
