<?php
session_start();

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

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

$orderId = (int)($_GET['id'] ?? 0);

if ($orderId <= 0) {
    die('Invalid order ID.');
}

try {

    $db->beginTransaction();

    /*
        Verify HOLD order
    */
    $stmt = $db->prepare("
        SELECT *
        FROM orders
        WHERE id = ?
        AND status = 'HOLD'
        LIMIT 1
    ");
    $stmt->execute([$orderId]);

    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        throw new Exception('Held order not found.');
    }

    /*
        Load held items
    */
    $stmt = $db->prepare("
        SELECT
            oi.*,
            i.name
        FROM order_items oi
        INNER JOIN items i ON oi.item_id = i.id
        WHERE oi.order_id = ?
    ");
    $stmt->execute([$orderId]);

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

    if (empty($items)) {
        throw new Exception('No items found.');
    }

    /*
        Clear existing cart
    */
    $_SESSION['pos_cart'] = [];

    /*
        Restore cart
    */
    foreach ($items as $item) {

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

        /*
            Rebuild GST %
            order_items.gst stores amount, not %
        */
        $lineSubtotal = $qty * $price;

        $gstPercent = 0;

        if ($lineSubtotal > 0 && $item['gst'] > 0) {
            $gstPercent = ($item['gst'] / $lineSubtotal) * 100;
        }

        $_SESSION['pos_cart'][$item['item_id']] = [
            'item_id' => $item['item_id'],
            'name'    => $item['name'],
            'price'   => $price,
            'gst'     => $gstPercent,
            'qty'     => $qty
        ];
    }

    /*
        Delete held order items
    */
    $stmt = $db->prepare("
        DELETE FROM order_items
        WHERE order_id = ?
    ");
    $stmt->execute([$orderId]);

    /*
        Delete held order
    */
    $stmt = $db->prepare("
        DELETE FROM orders
        WHERE id = ?
    ");
    $stmt->execute([$orderId]);

    $db->commit();

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

} catch (Exception $e) {

    $db->rollBack();

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