<?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'] ?? '');
$paymentMode = trim($_POST['payment_mode'] ?? 'CASH');

if ($tableId <= 0) {
    die('Please select a table.');
}

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 ORDER
    */
    $stmt = $db->prepare("
        INSERT INTO orders
        (
            table_id,
            customer_name,
            subtotal,
            gst,
            total,
            payment_mode,
            status,
            order_date
        )
        VALUES
        (?, ?, ?, ?, ?, ?, 'PAID', NOW())
    ");

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

    $orderId = $db->lastInsertId();

    /*
        ORDER ITEMS
    */
    $orderItemStmt = $db->prepare("
        INSERT INTO order_items
        (
            order_id,
            item_id,
            quantity,
            price,
            gst
        )
        VALUES
        (?, ?, ?, ?, ?)
    ");

    /*
        STOCK OUT ENTRY
    */
    $stockStmt = $db->prepare("
        INSERT INTO stock_entries
        (
            item_id,
            qty,
            rate,
            total,
            type,
            reference,
            remarks,
            unit_id,
            stock_date
        )
        VALUES
        (?, ?, ?, ?, 'OUT', ?, ?, ?, CURDATE())
    ");

    /*
        UPDATE ITEM STOCK
    */
    $updateStockStmt = $db->prepare("
        UPDATE items
        SET stock = stock - ?
        WHERE id = ?
    ");

    /*
        ITEM DETAILS
    */
    $itemStmt = $db->prepare("
        SELECT stock, unit_id
        FROM items
        WHERE id = ?
        LIMIT 1
    ");

    foreach ($cart as $item) {

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

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

        /*
            Save order item
        */
        $orderItemStmt->execute([
            $orderId,
            $itemId,
            $qty,
            $price,
            $lineGst
        ]);

        /*
            Load stock info
        */
        $itemStmt->execute([$itemId]);
        $itemInfo = $itemStmt->fetch(PDO::FETCH_ASSOC);

        if (!$itemInfo) {
            throw new Exception('Item not found.');
        }

        if ((float)$itemInfo['stock'] < $qty) {
            throw new Exception(
                'Insufficient stock for item ID: ' . $itemId
            );
        }

        /*
            Deduct stock
        */
        $updateStockStmt->execute([
            $qty,
            $itemId
        ]);

        /*
            Create stock OUT history
        */
        $stockStmt->execute([
            $itemId,
            $qty,
            $price,
            $lineSubtotal,
            'ORDER #' . $orderId,
            'POS Sale',
            $itemInfo['unit_id']
        ]);
    }

    /*
        Mark table occupied
    */
    $stmt = $db->prepare("
        UPDATE tables
        SET status = 'OCCUPIED'
        WHERE id = ?
    ");
    $stmt->execute([$tableId]);

    unset($_SESSION['pos_cart']);

    $db->commit();

    header(
        'Location: ../invoices/print_invoice.php?id=' . $orderId
    );
    exit;

} catch (Exception $e) {

    $db->rollBack();

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