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

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

try {
    // Get held orders that are still active
    $stmt = $conn->prepare("SELECT * FROM held_orders WHERE status = 'held' ORDER BY created_at DESC LIMIT 50");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $orders = [];
    while ($row = $result->fetch_assoc()) {
        // Extract customer details from order_data JSON (temporary until database columns are added)
        $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;
        $notes = isset($order_data['notes']) ? $order_data['notes'] : null;
        
        $orders[] = [
            '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'],
            'created_at' => date('M j, Y g:i A', strtotime($row['created_at'])),
            'created_by' => $row['created_by'],
            'notes' => $row['notes']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'orders' => $orders
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving held orders: ' . $e->getMessage()
    ]);
}

$conn->close();
?>