<?php
// Delete Hold Order Handler
header('Content-Type: application/json');

// Prevent any output before JSON
ob_start();

// Error handling
error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    include '../db.php';
    
    // Test database connection
    if ($conn->connect_error) {
        throw new Exception('Database connection failed: ' . $conn->connect_error);
    }

    // Clear any previous output
    ob_clean();

    // Get JSON input
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON input: ' . json_last_error_msg());
    }

    // Validate required fields
    if (empty($data['order_id'])) {
        throw new Exception('Order ID is required');
    }

    $order_id = intval($data['order_id']);

    // Begin transaction
    $conn->begin_transaction();

    try {
        // Get order details first
        $order_stmt = $conn->prepare("SELECT table_id, order_mode FROM hold_orders WHERE id = ?");
        $order_stmt->bind_param("i", $order_id);
        $order_stmt->execute();
        $order_result = $order_stmt->get_result();
        
        if ($order_result->num_rows === 0) {
            throw new Exception('Order not found');
        }
        
        $order_data = $order_result->fetch_assoc();
        $order_stmt->close();

        // Delete hold items first
        $delete_items_stmt = $conn->prepare("DELETE FROM hold_items WHERE hold_id = ?");
        $delete_items_stmt->bind_param("i", $order_id);
        $delete_items_stmt->execute();
        $delete_items_stmt->close();

        // Delete hold order
        $delete_order_stmt = $conn->prepare("DELETE FROM hold_orders WHERE id = ?");
        $delete_order_stmt->bind_param("i", $order_id);
        $delete_order_stmt->execute();
        $delete_order_stmt->close();

        // Update table status if it was a dine-in order
        if ($order_data['order_mode'] === 'dine_in' && $order_data['table_id']) {
            // Check if there are other orders for this table
            $check_table_stmt = $conn->prepare("
                SELECT COUNT(*) as order_count 
                FROM hold_orders 
                WHERE table_id = ? AND id != ?
            ");
            $check_table_stmt->bind_param("ii", $order_data['table_id'], $order_id);
            $check_table_stmt->execute();
            $check_result = $check_table_stmt->get_result();
            $check_data = $check_result->fetch_assoc();
            $check_table_stmt->close();

            // If no other orders for this table, mark it as available
            if ($check_data['order_count'] == 0) {
                $update_table_stmt = $conn->prepare("UPDATE dinein_tables SET status = 'available' WHERE id = ?");
                $update_table_stmt->bind_param("i", $order_data['table_id']);
                $update_table_stmt->execute();
                $update_table_stmt->close();
            }
        }

        // Commit transaction
        $conn->commit();

        // Return success response
        echo json_encode([
            'success' => true,
            'message' => 'Order deleted successfully'
        ]);

    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {
    // Log error
    error_log('Delete hold order error: ' . $e->getMessage());
    
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

// Close database connection
if (isset($conn)) {
    $conn->close();
}
?>
