<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';

header('Content-Type: application/json');

if (!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Order ID is required']);
    exit;
}

$order_id = intval($_GET['id']);

try {
    $stmt = $conn->prepare("SELECT * FROM held_orders WHERE id = ? AND status = 'held'");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        // Extract customer details from order_data JSON
        $order_data = json_decode($row['order_data'], true);
        $customer_name = isset($order_data['customer_name']) ? $order_data['customer_name'] : null;
        $table_number = isset($order_data['table_number']) ? $order_data['table_number'] : null;
        
        echo json_encode([
            'success' => true,
            'order' => [
                'id' => $row['id'],
                'order_number' => $row['order_number'],
                'customer_id' => $row['customer_id'],
                'customer_name' => $customer_name,
                'customer_phone' => $row['customer_phone'],
                'table_number' => $table_number,
                'subtotal' => $row['subtotal'],
                'discount' => $row['discount'],
                'discount_amount' => $row['discount_amount'],
                'total_amount' => $row['total_amount'],
                'order_data' => $row['order_data'],
                'created_at' => $row['created_at'],
                'created_by' => $row['created_by'],
                'notes' => $row['notes']
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Held order not found or already processed'
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving held order: ' . $e->getMessage()
    ]);
}

$conn->close();
?>