<?php
include '../db.php';
include '../auth.php';
require_right('Access POS');

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

// Get filter parameters
$category_filter = isset($_GET['category']) ? intval($_GET['category']) : 0;
$station_filter = isset($_GET['station']) ? intval($_GET['station']) : 0;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

try {
    // Build the query
    $query = "
        SELECT 
            i.id,
            i.name,
            i.prep_time,
            c.name as category_name,
            GROUP_CONCAT(DISTINCT ksi.station_id) as assigned_station_ids
        FROM items i
        LEFT JOIN categories c ON i.category_id = c.id
        LEFT JOIN kds_station_items ksi ON i.id = ksi.item_id
        WHERE i.item_role != 'material'
    ";
    
    $params = [];
    $types = '';
    
    // Add category filter
    if ($category_filter > 0) {
        $query .= " AND i.category_id = ?";
        $params[] = $category_filter;
        $types .= 'i';
    }
    
    // Add search filter
    if (!empty($search)) {
        $query .= " AND (i.name LIKE ? OR c.name LIKE ?)";
        $search_param = "%$search%";
        $params[] = $search_param;
        $params[] = $search_param;
        $types .= 'ss';
    }
    
    $query .= " GROUP BY i.id ORDER BY i.name";
    
    // Prepare and execute query
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Get all stations for dropdown
    $stations_result = $conn->query("SELECT id, name FROM kds_stations WHERE is_active = 1 ORDER BY name");
    $stations = [];
    while ($station = $stations_result->fetch_assoc()) {
        $stations[] = $station;
    }
    
    // Process results
    $assignments = [];
    while ($item = $result->fetch_assoc()) {
        $assigned_station_ids = $item['assigned_station_ids'] ? explode(',', $item['assigned_station_ids']) : [];
        
        // Add station options
        $item['stations'] = [];
        foreach ($stations as $station) {
            $item['stations'][] = [
                'id' => $station['id'],
                'name' => $station['name'],
                'assigned' => in_array($station['id'], $assigned_station_ids)
            ];
        }
        
        // Apply station filter if specified
        if ($station_filter > 0) {
            if (!in_array($station_filter, $assigned_station_ids)) {
                continue; // Skip items not assigned to this station
            }
        }
        
        unset($item['assigned_station_ids']); // Remove from output
        $assignments[] = $item;
    }
    
    echo json_encode(['success' => true, 'assignments' => $assignments]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
