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

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

$item_id = isset($_GET['item_id']) ? intval($_GET['item_id']) : 0;

if ($item_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid item ID']);
    exit;
}

try {
    // Get modifier groups assigned to this item
    $groups_query = "
        SELECT 
            img.id,
            img.name,
            img.display_name,
            img.description,
            img.is_required,
            img.is_multiple_choice,
            img.max_selections,
            img.min_selections,
            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, img.display_name
    ";
    
    $groups_stmt = $conn->prepare($groups_query);
    $groups_stmt->bind_param("i", $item_id);
    $groups_stmt->execute();
    $groups_result = $groups_stmt->get_result();
    
    $modifier_groups = [];
    
    while ($group = $groups_result->fetch_assoc()) {
        // Override group requirement if assignment specifies
        if ($group['assignment_required']) {
            $group['is_required'] = 1;
        }
        
        // Get modifiers for this group
        $modifiers_query = "
            SELECT 
                id,
                name,
                short_name,
                price_adjustment,
                is_default,
                sort_order
            FROM item_modifiers 
            WHERE modifier_group_id = ? AND is_active = 1
            ORDER BY sort_order, name
        ";
        
        $modifiers_stmt = $conn->prepare($modifiers_query);
        $modifiers_stmt->bind_param("i", $group['id']);
        $modifiers_stmt->execute();
        $modifiers_result = $modifiers_stmt->get_result();
        
        $modifiers = [];
        while ($modifier = $modifiers_result->fetch_assoc()) {
            $modifiers[] = $modifier;
        }
        $modifiers_stmt->close();
        
        // Only include groups that have active modifiers
        if (!empty($modifiers)) {
            $group['modifiers'] = $modifiers;
            $modifier_groups[] = $group;
        }
    }
    
    echo json_encode([
        'success' => true, 
        'modifier_groups' => $modifier_groups
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
