<?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 all available modifier groups
    $groups_query = "
        SELECT 
            id,
            name,
            display_name,
            description,
            is_required,
            is_multiple_choice
        FROM item_modifier_groups 
        WHERE is_active = 1
        ORDER BY sort_order, display_name
    ";
    
    $groups_result = $conn->query($groups_query);
    $groups = [];
    
    while ($group = $groups_result->fetch_assoc()) {
        $groups[] = $group;
    }
    
    // Get currently assigned groups for this item
    $assignments_query = "
        SELECT 
            modifier_group_id,
            is_required as assignment_required
        FROM item_modifier_group_assignments 
        WHERE item_id = ?
    ";
    
    $assignments_stmt = $conn->prepare($assignments_query);
    $assignments_stmt->bind_param("i", $item_id);
    $assignments_stmt->execute();
    $assignments_result = $assignments_stmt->get_result();
    
    $assigned_group_ids = [];
    $assignment_details = [];
    
    while ($assignment = $assignments_result->fetch_assoc()) {
        $assigned_group_ids[] = intval($assignment['modifier_group_id']);
        $assignment_details[$assignment['modifier_group_id']] = $assignment;
    }
    
    // Add assignment details to groups
    foreach ($groups as &$group) {
        if (in_array($group['id'], $assigned_group_ids)) {
            $group['assignment_required'] = $assignment_details[$group['id']]['assignment_required'];
        } else {
            $group['assignment_required'] = 0;
        }
    }
    
    echo json_encode([
        'success' => true, 
        'groups' => $groups,
        'assigned_group_ids' => $assigned_group_ids
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
