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

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

try {
    $group_filter = isset($_GET['group_filter']) ? intval($_GET['group_filter']) : 0;
    $search_filter = isset($_GET['search']) ? trim($_GET['search']) : '';
    $status_filter = isset($_GET['status']) ? intval($_GET['status']) : -1;
    
    // Build the query with conditional joins and filters
    $query = "
        SELECT 
            im.id,
            im.name,
            im.short_name,
            im.price_adjustment,
            im.cost_adjustment,
            im.is_default,
            im.is_active,
            im.sort_order,
            im.prep_time_adjustment,
            GROUP_CONCAT(img.display_name ORDER BY img.sort_order SEPARATOR ', ') as group_name
        FROM item_modifiers im
        LEFT JOIN modifier_group_assignments mga ON im.id = mga.modifier_id
        LEFT JOIN item_modifier_groups img ON mga.modifier_group_id = img.id
    ";
    
    $conditions = [];
    $params = [];
    $param_types = "";
    
    // Group filter
    if ($group_filter > 0) {
        $conditions[] = "mga.modifier_group_id = ?";
        $params[] = $group_filter;
        $param_types .= "i";
    }
    
    // Search filter
    if (!empty($search_filter)) {
        $conditions[] = "(im.name LIKE ? OR im.short_name LIKE ?)";
        $search_term = "%{$search_filter}%";
        $params[] = $search_term;
        $params[] = $search_term;
        $param_types .= "ss";
    }
    
    // Status filter
    if ($status_filter !== -1) {
        $conditions[] = "im.is_active = ?";
        $params[] = $status_filter;
        $param_types .= "i";
    }
    
    // Add WHERE clause if conditions exist
    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
    }
    
    $query .= " GROUP BY im.id ORDER BY im.sort_order, im.name";
    
    $stmt = $conn->prepare($query);
    
    // Bind parameters if any
    if (!empty($params)) {
        $stmt->bind_param($param_types, ...$params);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    $modifiers = [];
    while ($modifier = $result->fetch_assoc()) {
        $modifiers[] = $modifier;
    }
    
    echo json_encode(['success' => true, 'modifiers' => $modifiers]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
