<?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 id
        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.');
    }

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

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

    $db->commit();

    header('Location: resume_orders.php?cancelled=1');
    exit;

} catch (Exception $e) {

    $db->rollBack();

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