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

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

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$item_id = isset($input['item_id']) ? intval($input['item_id']) : 0;
$assignments = isset($input['assignments']) ? $input['assignments'] : [];

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

try {
    // Start transaction
    $conn->autocommit(false);
    
    // Delete existing assignments for this item
    $delete_stmt = $conn->prepare("DELETE FROM item_modifier_group_assignments WHERE item_id = ?");
    $delete_stmt->bind_param("i", $item_id);
    $delete_stmt->execute();
    
    // Insert new assignments
    if (!empty($assignments)) {
        $insert_stmt = $conn->prepare("
            INSERT INTO item_modifier_group_assignments 
            (item_id, modifier_group_id, is_required, sort_order) 
            VALUES (?, ?, ?, 0)
        ");
        
        foreach ($assignments as $assignment) {
            $modifier_group_id = intval($assignment['modifier_group_id']);
            $is_required = intval($assignment['is_required']);
            
            $insert_stmt->bind_param("iii", $item_id, $modifier_group_id, $is_required);
            $insert_stmt->execute();
        }
    }
    
    // Commit transaction
    $conn->commit();
    $conn->autocommit(true);
    
    echo json_encode(['success' => true, 'message' => 'Group assignments saved successfully']);
    
} catch (Exception $e) {
    // Rollback transaction
    $conn->rollback();
    $conn->autocommit(true);
    
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
