<?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');

/**
 * Calculate station-wise timing for an order
 * New Logic:
 * - BAR-only orders: Show BAR timing (10 min)
 * - KITCHEN-only orders: Show KITCHEN timing (22 min)
 * - BAR + KITCHEN orders: Show KITCHEN timing (22 min) on BAR side (bar man waits for kitchen)
 * - BAR + KITCHEN orders: Show KITCHEN timing (22 min) on KITCHEN side
 */
function calculateOrderStationTiming($items, $current_station_filter = 0) {
    global $conn;
    
    if (empty($items)) {
        return 10; // Default timing
    }
    
    // Get unique stations for this order
    $station_ids = [];
    $station_names = [];
    foreach ($items as $item) {
        if (!empty($item['station_name'])) {
            // Get station ID from station name
            $station_query = "SELECT id, preparation_time, name FROM kds_stations WHERE name = ? AND is_active = 1";
            $station_stmt = $conn->prepare($station_query);
            $station_stmt->bind_param("s", $item['station_name']);
            $station_stmt->execute();
            $station_result = $station_stmt->get_result();
            if ($station_data = $station_result->fetch_assoc()) {
                $station_ids[] = $station_data;
                $station_names[] = $station_data['name'];
            }
            $station_stmt->close();
        }
    }
    
    if (empty($station_ids)) {
        return 10; // Default timing if no stations found
    }
    
    // Remove duplicates from station names
    $station_names = array_unique($station_names);
    
    // Check if order has both BAR and KITCHEN items
    $has_bar = in_array('BAR', $station_names);
    $has_kitchen = in_array('KITCHEN', $station_names);
    
    // If filtering by specific station, apply the new logic
    if ($current_station_filter > 0) {
        // Apply the new timing logic based on order composition
        if ($has_bar && $has_kitchen) {
            // Mixed order: Always show KITCHEN timing (22 min) on both stations
            // because bar man waits for kitchen items
            return 22;
        } elseif ($has_bar && !$has_kitchen) {
            // BAR-only order: Show BAR timing
            return 10;
        } elseif (!$has_bar && $has_kitchen) {
            // KITCHEN-only order: Show KITCHEN timing
            return 22;
        } else {
            // Fallback: return the station's own timing
            foreach ($station_ids as $station) {
                if ($station['id'] == $current_station_filter) {
                    return $station['preparation_time'] ?? 10;
                }
            }
            return 10;
        }
    }
    
    // For "All Stations" view, use the new logic
    if ($has_bar && $has_kitchen) {
        // Mixed order: Use KITCHEN timing (22 min) because bar man waits for kitchen
        return 22;
    } elseif ($has_bar && !$has_kitchen) {
        // BAR-only order: Use BAR timing
        return 10;
    } elseif (!$has_bar && $has_kitchen) {
        // KITCHEN-only order: Use KITCHEN timing
        return 22;
    } else {
        // Fallback: Use the highest timing
        $max_timing = 0;
        foreach ($station_ids as $station) {
            $timing = $station['preparation_time'] ?? 10;
            if ($timing > $max_timing) {
                $max_timing = $timing;
            }
        }
        return $max_timing;
    }
}

// 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.order_sequence,
            ko.parent_order_id,
            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
    // and hide orders where ALL items for this station are already served
    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 = ?
            AND koi_filter.served_quantity < koi_filter.quantity
        )";
        $params[] = $station_filter;
        $types .= 'i';
    } else {
        // For "All Stations" view, only show items that are assigned to stations
        // This prevents unassigned items from appearing in "All Stations"
        $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 IS NOT NULL
            AND koi_filter.served_quantity < koi_filter.quantity
        )";
    }
    
    // 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.item_status_type,
                koi.total_quantity,
                koi.served_quantity,
                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';
        } else {
            // For "All Stations" view, only show items that are assigned to stations
            $items_query .= " AND ksi.station_id IS NOT NULL";
        }
        
        $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 station-wise timing - get ALL items for timing calculation
        // regardless of station filter to ensure correct mixed order detection
        $all_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.item_status_type,
                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 = ? AND ksi.station_id IS NOT NULL
            ORDER BY koi.created_at
        ";
        
        $all_items_stmt = $conn->prepare($all_items_query);
        $all_items_stmt->bind_param("i", $order['id']);
        $all_items_stmt->execute();
        $all_items_result = $all_items_stmt->get_result();
        
        $all_order_items = [];
        while ($all_item = $all_items_result->fetch_assoc()) {
            $all_order_items[] = $all_item;
        }
        $all_items_stmt->close();
        
        // Calculate station-wise timing using ALL items
        $order['station_timing'] = calculateOrderStationTiming($all_order_items, $station_filter);
        
        // 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()]);
}
?>
