<?php
include __DIR__ . '/../db.php';

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

try {
    $store_id = $_SESSION['current_store_id'] ?? 1;
    
    // Fetch delivery orders with item counts and KDS status
    $query = "
        SELECT 
            ho.id,
            ho.customer_name,
            ho.total_amount,
            ho.created_at,
            ho.updated_at,
            CONCAT('DEL-', LPAD(ho.id, 6, '0')) as reference,
            COUNT(hi.id) as item_count,
            GROUP_CONCAT(DISTINCT hi.item_name SEPARATOR ', ') as items_summary,
            ho.updated_at as last_item_added,
            CASE 
                WHEN EXISTS (
                    SELECT 1 FROM kds_orders ko 
                    WHERE ko.hold_id = ho.id 
                    AND ko.order_status IN ('pending', 'preparing', 'ready')
                ) THEN 1 
                ELSE 0 
            END as has_running_orders
        FROM hold_orders ho
        LEFT JOIN hold_items hi ON ho.id = hi.hold_id
        WHERE ho.order_mode = 'delivery' 
        AND ho.store_id = ?
        GROUP BY ho.id, ho.customer_name, ho.total_amount, ho.created_at, ho.updated_at
        ORDER BY ho.created_at DESC
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $store_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $orders = [];
    while ($row = $result->fetch_assoc()) {
        $orders[] = [
            'id' => $row['id'],
            'reference' => $row['reference'],
            'customer_name' => $row['customer_name'],
            'total_amount' => $row['total_amount'],
            'item_count' => $row['item_count'],
            'items_summary' => $row['items_summary'],
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at'],
            'last_item_added' => $row['last_item_added'],
            'has_running_orders' => $row['has_running_orders']
        ];
    }
    
    // Get statistics
    $stats_query = "
        SELECT 
            COUNT(*) as total_orders,
            SUM(total_amount) as total_amount,
            COUNT(CASE WHEN has_running_orders = 1 THEN 1 END) as active_orders
        FROM (
            SELECT 
                ho.id,
                ho.total_amount,
                CASE 
                    WHEN EXISTS (
                        SELECT 1 FROM kds_orders ko 
                        WHERE ko.hold_id = ho.id 
                        AND ko.order_status IN ('pending', 'preparing', 'ready')
                    ) THEN 1 
                    ELSE 0 
                END as has_running_orders
            FROM hold_orders ho
            WHERE ho.order_mode = 'delivery' 
            AND ho.store_id = ?
        ) as delivery_stats
    ";
    
    $stats_stmt = $conn->prepare($stats_query);
    $stats_stmt->bind_param("i", $store_id);
    $stats_stmt->execute();
    $stats_result = $stats_stmt->get_result();
    $stats = $stats_result->fetch_assoc();
    
    echo json_encode([
        'success' => true,
        'orders' => $orders,
        'stats' => [
            'total_orders' => $stats['total_orders'] ?? 0,
            'total_amount' => $stats['total_amount'] ?? 0,
            'active_orders' => $stats['active_orders'] ?? 0
        ]
    ]);
    
} catch (Exception $e) {
    error_log("Error fetching delivery orders: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
