<?php
session_start();

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

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

$cart = $_SESSION['pos_cart'] ?? [];

if (empty($cart)) {
    die('Cart is empty.');
}

$tableId = (int)($_POST['table_id'] ?? 0);
$customerName = trim($_POST['customer_name'] ?? '');

try {

    $db->beginTransaction();

    $subtotal = 0;
    $totalGst = 0;
    $grandTotal = 0;

    foreach ($cart as $item) {

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

        $lineSubtotal = $qty * $price;
        $lineGst = ($lineSubtotal * $gstPercent) / 100;
        $lineTotal = $lineSubtotal + $lineGst;

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

    /*
        Save HOLD order
    */
    $stmt = $db->prepare("
        INSERT INTO orders
        (
            table_id,
            customer_name,
            subtotal,
            gst,
            total,
            payment_mode,
            status,
            order_date
        )
        VALUES
        (?, ?, ?, ?, ?, '', 'HOLD', NOW())
    ");

    $stmt->execute([
        $tableId,
        $customerName,
        $subtotal,
        $totalGst,
        $grandTotal
    ]);

    $orderId = $db->lastInsertId();

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

    foreach ($cart as $item) {

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

        $lineSubtotal = $qty * $price;
        $lineGst = ($lineSubtotal * $gstPercent) / 100;

        $stmt->execute([
            $orderId,
            $item['item_id'],
            $qty,
            $price,
            $lineGst
        ]);
    }

    unset($_SESSION['pos_cart']);

    $db->commit();

    header('Location: index.php?held=1');
    exit;

} catch (Exception $e) {

    $db->rollBack();

    die('Error: ' . $e->getMessage());
}
?>