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

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

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

try {
    // Build the query
    $query = "
        SELECT 
            i.id,
            i.name,
            c.name as category_name
        FROM items i
        LEFT JOIN categories c ON i.category_id = c.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_filter)) {
        $query .= " AND i.name LIKE ?";
        $params[] = '%' . $search_filter . '%';
        $types .= 's';
    }
    
    $query .= " 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();
    
    // Process results
    $assignments = [];
    while ($item = $result->fetch_assoc()) {
        // Get assigned modifier groups for this item
        $groups_query = "
            SELECT 
                img.id,
                img.display_name,
                img.is_required as group_required,
                imga.is_required as assignment_required
            FROM item_modifier_group_assignments imga
            JOIN item_modifier_groups img ON imga.modifier_group_id = img.id
            WHERE imga.item_id = ? AND img.is_active = 1
            ORDER BY img.sort_order
        ";
        
        $groups_stmt = $conn->prepare($groups_query);
        $groups_stmt->bind_param("i", $item['id']);
        $groups_stmt->execute();
        $groups_result = $groups_stmt->get_result();
        
        $assigned_groups = [];
        while ($group = $groups_result->fetch_assoc()) {
            // Apply group filter if specified
            if ($group_filter > 0 && $group['id'] != $group_filter) {
                continue;
            }
            $assigned_groups[] = $group;
        }
        $groups_stmt->close();
        
        // If group filter is applied and item has no matching groups, skip it
        if ($group_filter > 0 && empty($assigned_groups)) {
            continue;
        }
        
        $item['assigned_groups'] = $assigned_groups;
        $assignments[] = $item;
    }
    
    echo json_encode(['success' => true, 'assignments' => $assignments]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
