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


$user_id = $_SESSION['user_id'] ?? null;

// Get current open shift ID for the user
$current_shift_id = null;
if ($user_id) {
    $shift_stmt = $conn->prepare("SELECT id FROM shifts WHERE user_id = ? AND status = 'open' ORDER BY id DESC LIMIT 1");
    $shift_stmt->bind_param("i", $user_id);
    $shift_stmt->execute();
    $shift_result = $shift_stmt->get_result();
    if ($shift_row = $shift_result->fetch_assoc()) {
        $current_shift_id = $shift_row['id'];
    }
    $shift_stmt->close();
}


/// 🧾 Input Data
$customer_name   = $_POST['customer_name'] ?? 'Walk-in';
$table_id = !empty($_POST['table_id']) ? intval($_POST['table_id']) : null;

// 🔍 Get customer info from DB
$customer_id = null;
$is_walk_in = 1; // assume walk-in by default

$customer_stmt = $conn->prepare("SELECT id, is_walk_in FROM customers WHERE name = ?");
$customer_stmt->bind_param("s", $customer_name);
$customer_stmt->execute();
$customer_result = $customer_stmt->get_result();

if ($customer = $customer_result->fetch_assoc()) {
    $customer_id = $customer['id'];
    $is_walk_in = $customer['is_walk_in'];
}
$customer_stmt->close();

// ✅ Get payment method early
$payment_method  = $_POST['payment_method'] ?? 'cash';


// ❌ Don't allow credit for walk-in customers
if (strtolower($payment_method) === 'credit' && $is_walk_in == 1) {
    echo "error: Credit sales are not allowed for Walk-in customers.";
    exit;
}
$order_mode = $_POST['order_mode'] ?? null;


// ✅ Continue with rest of the logic
$cart_json       = $_POST['cart_json'] ?? '[]';
$tax_amount      = floatval($_POST['tax_amount'] ?? 0);
$total_amount    = floatval($_POST['total_amount'] ?? 0);
$discount_amount = 0.00;

$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;
}

$stmt = $conn->prepare("INSERT INTO sales (invoice_number, customer_name, total_amount, tax_amount, discount_amount, net_amount, payment_method, shift_id, table_id, order_mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssddddsiis", $invoice_number, $customer_name, $total_amount, $tax_amount, $discount_amount, $net_amount, $payment_method, $current_shift_id, $table_id, $order_mode);

$stmt->execute();
$sale_id = $stmt->insert_id;
$stmt->close();

// ✅ Log payment into account_transactions
$account_id = !empty($_POST['bank_account_id']) ? intval($_POST['bank_account_id']) : null;
$account_type = $payment_method;

// 👉 If bank/card/upi and no account ID provided, use default
if (in_array($payment_method, ['card', 'upi', 'bank']) && !$account_id) {
    $bank_result = $conn->query("SELECT id FROM bank_accounts WHERE is_active = 1 LIMIT 1");
    if ($bank_result && $bank_row = $bank_result->fetch_assoc()) {
        $account_id = $bank_row['id'];
    }
}

if ($payment_method !== 'credit') {
    $desc = ucfirst($payment_method) . " payment for invoice $invoice_number";
    $insert_txn = $conn->prepare("
        INSERT INTO account_transactions (sale_id, account_type, account_id, amount, description)
        VALUES (?, ?, ?, ?, ?)
    ");
    $insert_txn->bind_param("isids", $sale_id, $account_type, $account_id, $total_amount, $desc);
    $insert_txn->execute();
    $insert_txn->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();

// 🔁 Deduct BOM Materials from Inventory
foreach ($cart as $item) {
    $item_id = intval($item['id']);
    $qty_sold = intval($item['qty']);

    // Step 1: Check if this item is a stock item
    $check = $conn->prepare("SELECT item_role FROM items WHERE id = ?");
    $check->bind_param("i", $item_id);
    $check->execute();
    $role = $check->get_result()->fetch_assoc();
    $check->close();

    if (!$role || $role['item_role'] !== 'stock') {
        continue; // Skip non-stock items
    }

    // Step 2: Get BOM components for this item
    $bom_sql = $conn->prepare("
        SELECT bc.component_item_id, bc.quantity
        FROM bom_master bm
        JOIN bom_components bc ON bm.id = bc.bom_id
        WHERE bm.item_id = ?
    ");
    $bom_sql->bind_param("i", $item_id);
    $bom_sql->execute();
    $bom_result = $bom_sql->get_result();

    // Step 3: Deduct each material based on sold quantity
    while ($bom = $bom_result->fetch_assoc()) {
        $component_id = $bom['component_item_id'];
        $deduct_qty = $bom['quantity'] * $qty_sold;

        $insert = $conn->prepare("
            INSERT INTO inventory_movements (item_id, movement_type, reference_type, reference_id, quantity)
            VALUES (?, 'out', 'sale', ?, ?)
        ");
        $insert->bind_param("iid", $component_id, $sale_id, $deduct_qty);
        $insert->execute();
        $insert->close();
    }

    $bom_sql->close();
}



$_SESSION['last_sale_id'] = $sale_id;

// 💰 Add to outstanding if it's a credit sale for a real customer
if ($payment_method === 'credit' && $is_walk_in == 0 && $customer_id) {
    $status = 'unpaid';
    $insert_outstanding = $conn->prepare("INSERT INTO cus_outstanding (sale_id, customer_id, amount, status) VALUES (?, ?, ?, ?)");
    $insert_outstanding->bind_param("iids", $sale_id, $customer_id, $total_amount, $status);
    $insert_outstanding->execute();
    $insert_outstanding->close();
}



// digital fbr
include 'digital_save_sale.php';
$fbr_digital_row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM fbr_digital LIMIT 1"));
$is_fbr_digital_enabled = $fbr_digital_row && $fbr_digital_row['is_enabled'];

if ($is_fbr_digital_enabled) {
    $response = post_fbr_digital_invoice($conn, $sale_id);

    if (!$response['success']) {
        error_log("FBR Digital Error: " . $response['error']);
        echo "FBR Digital Failed: " . $response['error'];
        exit;
    }
}

// digital fbr

// 🔍 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()) {
            $unit_price_inclusive = $row['unit_price'];
$qty = $row['quantity'];
$tax_rate = $row['tax_rate'];

$unit_price_exclusive = $unit_price_inclusive / (1 + ($tax_rate / 100));
$tax_per_unit = $unit_price_inclusive - $unit_price_exclusive;

$sale_value = $unit_price_exclusive * $qty;
$tax_charged = $tax_per_unit * $qty;
$total = $unit_price_inclusive * $qty;

            $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)$qty,
    "TaxRate"      => (float)$tax_rate,
    "SaleValue"    => round($sale_value, 2),
    "Discount"     => 0.00,
    "FurtherTax"   => 0.00,
    "TaxCharged"   => round($tax_charged, 2),
    "TotalAmount"  => round($total, 2),
    "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";

    // 🧹 If this was an unheld order, clean up hold record
if (isset($_POST['unhold_order_id'])) {
    $unhold_id = intval($_POST['unhold_order_id']);
    $conn->query("DELETE FROM hold_items WHERE hold_id = $unhold_id");
    $conn->query("DELETE FROM hold_orders WHERE id = $unhold_id");
}

}
?>
