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

// KDS endpoints don't require full authentication but should be protected
// Check for a simple KDS access token or allow direct access for now
// In production, you might want to implement a proper KDS authentication system

// For now, allow direct access to KDS endpoints

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

// Get filter parameters
$station_filter = isset($_GET['station']) ? intval($_GET['station']) : 0;
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

try {
    // Build the query
    $query = "
        SELECT 
            ko.id,
            ko.order_number,
            ko.sale_id,
            ko.customer_name,
            ko.table_number,
            ko.order_type,
            ko.order_status,
            ko.priority,
            ko.estimated_time,
            ko.notes,
            ko.created_at,
            ko.updated_at,
            dt.table_name,
            df.name as floor_name,
            COUNT(koi.id) as item_count,
            SUM(CASE WHEN koi.item_status = 'pending' THEN 1 ELSE 0 END) as pending_items,
            SUM(CASE WHEN koi.item_status = 'preparing' THEN 1 ELSE 0 END) as in_progress_items,
            SUM(CASE WHEN koi.item_status = 'ready' THEN 1 ELSE 0 END) as ready_items,
            SUM(CASE WHEN koi.item_status = 'served' THEN 1 ELSE 0 END) as completed_items
        FROM kds_orders ko
        LEFT JOIN dinein_tables dt ON ko.table_number = dt.table_name
        LEFT JOIN dinein_floors df ON dt.floor_id = df.id
        LEFT JOIN kds_order_items koi ON ko.id = koi.kds_order_id
        WHERE ko.order_status != 'served' AND ko.order_status != 'ready'
    ";
    
    $params = [];
    $types = '';
    
    // Add station filter - only show orders that have items for the selected station
    if ($station_filter > 0) {
        $query .= " AND EXISTS (
            SELECT 1 FROM kds_order_items koi_filter
            LEFT JOIN kds_station_items ksi ON koi_filter.item_id = ksi.item_id AND ksi.is_active = 1
            WHERE koi_filter.kds_order_id = ko.id
            AND ksi.station_id = ?
        )";
        $params[] = $station_filter;
        $types .= 'i';
    }
    
    // Add status filter
    if (!empty($status_filter)) {
        $query .= " AND ko.order_status = ?";
        $params[] = $status_filter;
        $types .= 's';
    }
    
    $query .= " GROUP BY ko.id ORDER BY ko.created_at ASC";
    
    // Prepare and execute query
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Process results
    $orders = [];
    while ($order = $result->fetch_assoc()) {
        // Check if this is a running order (additional items for same table)
        $running_order_query = "
            SELECT COUNT(*) as running_count
            FROM kds_orders ko2
            WHERE ko2.table_number = ? 
            AND ko2.order_type = 'dine_in'
            AND ko2.id != ?
            AND ko2.order_status != 'served'
            AND ko2.order_status != 'ready'
            AND ko2.created_at < ?
        ";
        
        $running_stmt = $conn->prepare($running_order_query);
        $running_stmt->bind_param("sis", $order['table_number'], $order['id'], $order['created_at']);
        $running_stmt->execute();
        $running_result = $running_stmt->get_result();
        $running_data = $running_result->fetch_assoc();
        $running_stmt->close();
        
        // Mark as running order if there are previous orders for same table
        $is_running_order = $running_data['running_count'] > 0;
        
        // Get order items - filter by station if station filter is applied
        $items_query = "
            SELECT 
                koi.id,
                koi.item_id,
                koi.item_name,
                koi.quantity,
                koi.unit_price,
                koi.total_price,
                koi.item_status,
                koi.special_instructions,
                koi.preparation_notes,
                koi.created_at,
                i.prep_time,
                ks.name as station_name,
                ks.color as station_color
            FROM kds_order_items koi
            LEFT JOIN items i ON koi.item_id = i.id
            LEFT JOIN kds_station_items ksi ON koi.item_id = ksi.item_id AND ksi.is_active = 1
            LEFT JOIN kds_stations ks ON ksi.station_id = ks.id
            WHERE koi.kds_order_id = ?
        ";
        
        // Add station filter to items query if station is selected
        $items_params = [$order['id']];
        $items_types = 'i';
        if ($station_filter > 0) {
            $items_query .= " AND ksi.station_id = ?";
            $items_params[] = $station_filter;
            $items_types .= 'i';
        }
        
        $items_query .= " ORDER BY koi.created_at";
        
        $items_stmt = $conn->prepare($items_query);
        $items_stmt->bind_param($items_types, ...$items_params);
        $items_stmt->execute();
        $items_result = $items_stmt->get_result();
        
        $order['items'] = [];
        while ($item = $items_result->fetch_assoc()) {
            $order['items'][] = $item;
        }
        $items_stmt->close();
        
        // Skip orders that have no items for the selected station
        if ($station_filter > 0 && empty($order['items'])) {
            continue;
        }
        
        // Calculate order progress
        $total_items = $order['item_count'];
        $completed_items = $order['completed_items'];
        $order['progress_percentage'] = $total_items > 0 ? round(($completed_items / $total_items) * 100) : 0;
        
        // Determine overall order status based on items
        if ($completed_items == $total_items && $total_items > 0) {
            $order['calculated_status'] = 'ready';
        } elseif ($order['in_progress_items'] > 0 || $order['ready_items'] > 0) {
            $order['calculated_status'] = 'preparing';
        } else {
            $order['calculated_status'] = 'new';
        }
        
        // Format timestamps
        $order['created_at_formatted'] = date('H:i', strtotime($order['created_at']));
        $order['time_elapsed'] = time() - strtotime($order['created_at']);
        
        // Add running order flag
        $order['is_running_order'] = $is_running_order;
        
        $orders[] = $order;
    }
    
    echo json_encode(['success' => true, 'orders' => $orders]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
