<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
    exit('Cart is empty');
}

$customerName = trim($_POST['customer_name'] ?? '');
$customerMobile = trim($_POST['customer_mobile'] ?? '');
$discount = (float)($_POST['discount'] ?? 0);
$paymentMode = trim($_POST['payment_mode'] ?? 'Cash');

$cart = $_SESSION['cart'];

try {
    $db->beginTransaction();

    $itemIds = array_keys($cart);
    $placeholders = implode(',', array_fill(0, count($itemIds), '?'));

    $stmt = $db->prepare("SELECT * FROM items WHERE id IN ($placeholders)");
    $stmt->execute($itemIds);

    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $itemMap = [];
    foreach ($items as $item) {
        $itemMap[$item['id']] = $item;
    }

    $subtotal = 0;
    $totalGst = 0;

    foreach ($cart as $itemId => $qty) {
        if (!isset($itemMap[$itemId])) {
            continue;
        }

        $item = $itemMap[$itemId];

        $price = (float)$item['price'];
        $gst = (float)$item['gst'];

        $lineTotal = $price * $qty;
        $lineGst = ($lineTotal * $gst) / 100;

        $subtotal += $lineTotal;
        $totalGst += $lineGst;
    }

    $grandTotal = ($subtotal + $totalGst) - $discount;

    if ($grandTotal < 0) {
        $grandTotal = 0;
    }

    /*
      Existing schema:
      orders(id, order_date, total, gst, status)

      Optional customer/payment columns can be added later.
    */

    $stmt = $db->prepare("
        INSERT INTO orders
        (order_date, total, gst, status)
        VALUES
        (NOW(), ?, ?, ?)
    ");

    $stmt->execute([
        $grandTotal,
        $totalGst,
        'Completed'
    ]);

    $orderId = $db->lastInsertId();

    foreach ($cart as $itemId => $qty) {
        if (!isset($itemMap[$itemId])) {
            continue;
        }

        $item = $itemMap[$itemId];

        $price = (float)$item['price'];
        $gst = (float)$item['gst'];

        $stmt = $db->prepare("
            INSERT INTO order_items
            (order_id, item_id, quantity, price, gst)
            VALUES
            (?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $orderId,
            $itemId,
            $qty,
            $price,
            $gst
        ]);

        /*
          Reduce stock
        */
        $stmt = $db->prepare("
            UPDATE items
            SET stock = stock - ?
            WHERE id = ?
        ");

        $stmt->execute([
            $qty,
            $itemId
        ]);
    }

    $_SESSION['last_order_id'] = $orderId;
    $_SESSION['last_customer_name'] = $customerName;
    $_SESSION['last_customer_mobile'] = $customerMobile;
    $_SESSION['last_payment_mode'] = $paymentMode;
    $_SESSION['last_discount'] = $discount;

    $_SESSION['cart'] = [];

    $db->commit();

    echo "Order saved successfully. Order ID: " . $orderId;

} catch (Exception $e) {
    $db->rollBack();
    echo "Error: " . $e->getMessage();
}
?>