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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['modifier_ids']) || !isset($input['group_ids'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$modifier_ids = $input['modifier_ids'];
$group_ids = $input['group_ids'];

if (empty($modifier_ids) || empty($group_ids)) {
    echo json_encode(['success' => false, 'message' => 'No modifiers or groups selected']);
    exit;
}

try {
    $conn->begin_transaction();
    
    $success_count = 0;
    $error_count = 0;
    $errors = [];
    
    foreach ($modifier_ids as $modifier_id) {
        // Verify modifier exists
        $check_modifier_stmt = $conn->prepare("SELECT id, name FROM item_modifiers WHERE id = ?");
        $check_modifier_stmt->bind_param("i", $modifier_id);
        $check_modifier_stmt->execute();
        $modifier_result = $check_modifier_stmt->get_result();
        
        if ($modifier_result->num_rows === 0) {
            $error_count++;
            $errors[] = "Modifier ID {$modifier_id} not found";
            continue;
        }
        
        $modifier = $modifier_result->fetch_assoc();
        
        foreach ($group_ids as $group_id) {
            // Check if assignment already exists
            $check_assignment_stmt = $conn->prepare("
                SELECT COUNT(*) as count 
                FROM modifier_group_assignments 
                WHERE modifier_id = ? AND modifier_group_id = ?
            ");
            $check_assignment_stmt->bind_param("ii", $modifier_id, $group_id);
            $check_assignment_stmt->execute();
            $check_result = $check_assignment_stmt->get_result()->fetch_assoc();
            
            if ($check_result['count'] > 0) {
                // Assignment already exists, skip
                continue;
            }
            
            // Create assignment record
            $insert_stmt = $conn->prepare("
                INSERT INTO modifier_group_assignments (modifier_id, modifier_group_id, sort_order) 
                VALUES (?, ?, 0)
            ");
            $insert_stmt->bind_param("ii", $modifier_id, $group_id);
            
            if ($insert_stmt->execute()) {
                $success_count++;
            } else {
                $error_count++;
                $errors[] = "Failed to assign modifier '{$modifier['name']}' to group {$group_id}";
            }
        }
    }
    
    $conn->commit();
    
    $message = "Successfully assigned {$success_count} modifier(s)";
    if ($error_count > 0) {
        $message .= ". {$error_count} assignment(s) failed";
    }
    
    echo json_encode([
        'success' => true, 
        'message' => $message,
        'success_count' => $success_count,
        'error_count' => $error_count,
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
