<?php
require_once '../db.php';

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

try {
    // Fetch all take-away orders (orders with order_mode = 'take_away' and table_id IS NULL)
    $orders_query = "
        SELECT 
            ho.id,
            ho.customer_name,
            ho.order_mode,
            ho.total_amount,
            ho.created_at,
            ho.updated_at,
            ho.order_taker_id,
            CONCAT('HOLD-', LPAD(ho.id, 6, '0')) as reference,
            (SELECT COUNT(*) FROM kds_orders ko WHERE ko.hold_id = ho.id AND ko.order_status NOT IN ('served', 'ready')) as active_kds_orders
        FROM hold_orders ho
        WHERE ho.order_mode = 'take_away' AND ho.table_id IS NULL
        ORDER BY ho.created_at DESC
    ";
    
    $orders_result = $conn->query($orders_query);
    
    if (!$orders_result) {
        throw new Exception('Database error: ' . $conn->error);
    }
    
    $orders = [];
    $total_amount = 0;
    $total_items = 0;
    
    while ($order = $orders_result->fetch_assoc()) {
        // Fetch order items for each order
        $items_query = "
            SELECT 
                hi.id,
                hi.item_name,
                hi.quantity,
                hi.unit_price,
                hi.tax_rate,
                hi.modifiers,
                hi.remarks,
                (hi.quantity * hi.unit_price) as line_total
            FROM hold_items hi
            WHERE hi.hold_id = ?
            ORDER BY hi.id
        ";
        
        $items_stmt = $conn->prepare($items_query);
        $items_stmt->bind_param('i', $order['id']);
        $items_stmt->execute();
        $items_result = $items_stmt->get_result();
        
        $items = [];
        while ($item = $items_result->fetch_assoc()) {
            // Parse modifiers JSON if exists
            if (!empty($item['modifiers'])) {
                $item['modifiers'] = json_decode($item['modifiers'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $item['modifiers'] = [];
                }
            } else {
                $item['modifiers'] = [];
            }
            
            $items[] = $item;
            $total_items += $item['quantity'];
        }
        
        $order['items'] = $items;
        $order['item_count'] = count($items);
        $order['status'] = 'held';
        $order['has_running_orders'] = $order['active_kds_orders'] > 0;
        
        $orders[] = $order;
        $total_amount += floatval($order['total_amount']);
    }
    
    // Calculate take-away statistics
    $stats = [
        'total_orders' => count($orders),
        'total_items' => $total_items,
        'total_amount' => $total_amount,
        'last_order_time' => !empty($orders) ? $orders[0]['created_at'] : null,
        'has_active_kds' => !empty($orders) && $orders[0]['has_running_orders']
    ];
    
    echo json_encode([
        'success' => true,
        'orders' => $orders,
        'stats' => $stats
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>
