<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../includes/db_connect.php';q

// Check admin session
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit;
}

// Initialize variables with default values
$isEdit = false;
$examId = 0;
$subjectId = 0;
$questions = [];
$admin_name = 'Administrator';
$error = '';
$success = '';
$marksPerQuestion = 1;
$totalQuestions = 0;

// Fetch admin data
try {
    $stmt = $pdo->prepare("SELECT username FROM admins WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($admin) {
        $admin_name = $admin['username'];
    }
} catch (PDOException $e) {
    error_log("Error fetching admin username: " . $e->getMessage());
    $error = "Failed to load admin data";
}

// Check if editing existing questions
if (isset($_GET['exam_id']) && isset($_GET['subject_id']) && is_numeric($_GET['exam_id']) && is_numeric($_GET['subject_id'])) {
    $isEdit = true;
    $examId = (int)$_GET['exam_id'];
    $subjectId = (int)$_GET['subject_id'];
    
    try {
        // Verify exam-subject combination exists and get marks info
        $stmt = $pdo->prepare("
            SELECT total_questions, marks_per_question 
            FROM exam_subjects 
            WHERE exam_id = ? AND subject_id = ?
        ");
        $stmt->execute([$examId, $subjectId]);
        $examSubject = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$examSubject) {
            throw new Exception("Invalid exam-subject combination");
        }

        $marksPerQuestion = $examSubject['marks_per_question'] ?? 1;
        $totalQuestions = $examSubject['total_questions'] ?? 0;

        // Fetch questions
        $stmt = $pdo->prepare("
            SELECT * FROM questions 
            WHERE exam_id = ? AND subject_id = ?
            ORDER BY question_number
        ");
        $stmt->execute([$examId, $subjectId]);
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        error_log("Error loading questions: " . $e->getMessage());
        $error = $e->getMessage();
        $_SESSION['error'] = $error;
        header("Location: questions.php");
        exit;
    }
}

// Fetch active exams and all subjects
$exams = [];
$subjects = [];
try {
    $exams = $pdo->query("
        SELECT id, exam_name 
        FROM exams 
        WHERE is_active = 1 
        ORDER BY exam_date DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $subjects = $pdo->query("
        SELECT id, name 
        FROM subjects 
        ORDER BY name
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching data: " . $e->getMessage());
    $error = "Failed to load required data";
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Use selected values from dropdowns (these are the actual values)
    $examId = (int)($_POST['exam_id_select'] ?? 0);
    $subjectId = (int)($_POST['subject_id_select'] ?? 0);
    $marksPerQuestion = (int)($_POST['marks_per_question'] ?? 1);
    
    // Validate IDs
    if ($examId <= 0 || $subjectId <= 0) {
        $error = "Please select both exam and subject";
    } else {
        try {
            $pdo->beginTransaction();
            
            // Verify or create exam-subject combination
            $stmt = $pdo->prepare("
                SELECT 1 FROM exam_subjects 
                WHERE exam_id = ? AND subject_id = ?
            ");
            $stmt->execute([$examId, $subjectId]);
            
            if ($stmt->fetch()) {
                // Update existing record
                $stmt = $pdo->prepare("
                    UPDATE exam_subjects 
                    SET total_questions = ?, marks_per_question = ?
                    WHERE exam_id = ? AND subject_id = ?
                ");
                $stmt->execute([count($_POST['questions']), $marksPerQuestion, $examId, $subjectId]);
            } else {
                // Create new record
                $stmt = $pdo->prepare("
                    INSERT INTO exam_subjects 
                    (exam_id, subject_id, total_questions, marks_per_question) 
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$examId, $subjectId, count($_POST['questions']), $marksPerQuestion]);
            }
            
            // Delete existing questions if editing
            if ($isEdit) {
                $stmt = $pdo->prepare("
                    DELETE FROM questions 
                    WHERE exam_id = ? AND subject_id = ?
                ");
                $stmt->execute([$examId, $subjectId]);
            }
            
            // Process each question
            $questionStmt = $pdo->prepare("
                INSERT INTO questions (
                    exam_id, subject_id, question_number, 
                    question_text, option_a, option_b, 
                    option_c, option_d, correct_option, 
                    marks, picture_url, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            foreach ($_POST['questions'] as $index => $q) {
                // Handle file upload - only if file was actually uploaded
                $questionImage = $q['existing_image'] ?? '';
                
                if (isset($_FILES['questions']['tmp_name'][$index]['image']) && 
                    $_FILES['questions']['error'][$index]['image'] === UPLOAD_ERR_OK &&
                    is_uploaded_file($_FILES['questions']['tmp_name'][$index]['image'])) {
                    
                    $uploadDir = '../uploads/questions/';
                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0755, true);
                    }
                    
                    $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
                    $mimeType = finfo_file($fileInfo, $_FILES['questions']['tmp_name'][$index]['image']);
                    finfo_close($fileInfo);
                    
                    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
                    if (in_array($mimeType, $allowedTypes)) {
                        $ext = pathinfo($_FILES['questions']['name'][$index]['image'], PATHINFO_EXTENSION);
                        $filename = 'q_' . $examId . '_' . $subjectId . '_' . uniqid() . '.' . $ext;
                        $destination = $uploadDir . $filename;
                        
                        if (move_uploaded_file($_FILES['questions']['tmp_name'][$index]['image'], $destination)) {
                            // Delete old image if it exists
                            if (!empty($questionImage) && file_exists($uploadDir . $questionImage)) {
                                @unlink($uploadDir . $questionImage);
                            }
                            $questionImage = $filename;
                        }
                    }
                }
                
                // Handle image removal
                if (isset($q['remove_image']) && $q['remove_image'] == 'on' && !empty($questionImage)) {
                    $uploadDir = '../uploads/questions/';
                    if (file_exists($uploadDir . $questionImage)) {
                        @unlink($uploadDir . $questionImage);
                    }
                    $questionImage = '';
                }
                
                // Determine marks - use individual if specified, otherwise use exam-subject default
                $questionMarks = isset($q['marks']) && $q['marks'] > 0 ? (int)$q['marks'] : $marksPerQuestion;
                
                // Insert question
                $questionStmt->execute([
                    $examId,
                    $subjectId,
                    $index + 1,
                    $q['text'],
                    $q['options']['A'],
                    $q['options']['B'],
                    $q['options']['C'],
                    $q['options']['D'],
                    $q['correct_option'],
                    $questionMarks,
                    $questionImage
                ]);
            }
            
            $pdo->commit();
            $success = "Questions " . ($isEdit ? 'updated' : 'added') . " successfully";
            $_SESSION['success'] = $success;
            header("Location: questions.php");
            exit;
            
        } catch (Exception $e) {
            $pdo->rollBack();
            error_log("Error saving questions: " . $e->getMessage());
            $error = "Failed to save questions: " . $e->getMessage();
        }
    }
}

// Display any session messages
if (isset($_SESSION['error'])) {
    $error = $_SESSION['error'];
    unset($_SESSION['error']);
}
if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $isEdit ? 'Edit' : 'Add'; ?> Questions - Exam Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        :root {
            --primary: #28a745;
            --secondary: #6c757d;
            --success: #28a745;
            --info: #17a2b8;
            --warning: #ffc107;
            --danger: #dc3545;
            --light: #f8f9fa;
            --dark: #343a40;
        }
        
        body {
            background-color: #f8f9fc;
            font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .dashboard-header {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            border-left: 5px solid var(--primary);
        }
        
        .card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        }
        
        .btn-primary {
            background-color: var(--primary);
            border-color: var(--primary);
        }
        
        .question-row {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        }
        
        .question-number {
            font-weight: bold;
            color: var(--primary);
            margin-right: 10px;
        }
        
        .option-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .option-label {
            font-weight: bold;
            min-width: 20px;
            margin-right: 10px;
        }
        
        .correct-option {
            background-color: rgba(40, 167, 69, 0.1);
            border-left: 4px solid var(--success);
        }
        
        .question-image-preview {
            max-width: 200px;
            max-height: 150px;
            margin-top: 10px;
            border-radius: 5px;
        }
        
        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: var(--primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        
        #questions-container .question-row:nth-child(odd) {
            background-color: #f8f9fa;
        }
        
        .marks-container {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- Top Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
        <div class="container">
            <a class="navbar-brand fw-bold text-primary" href="admin_dashboard.php">
                <i class="bi bi-mortarboard me-2"></i>Exam Portal
            </a>
            <div class="d-flex align-items-center">
                <div class="me-3">
                    <span class="text-muted small">Welcome,</span>
                    <span class="fw-bold ms-1 small"><?php echo htmlspecialchars($admin_name); ?></span>
                </div>
                <div class="user-avatar me-2">
                    <?php echo strtoupper(substr($admin_name, 0, 1)); ?>
                </div>
                <a href="../logout.php" class="btn btn-sm btn-outline-danger">
                    <i class="bi bi-box-arrow-right"></i>
                </a>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <!-- Dashboard Header -->
        <div class="dashboard-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h1 class="h3 fw-bold text-dark mb-2">
                        <i class="bi bi-question-circle me-2 text-primary"></i>
                        <?php echo $isEdit ? 'Edit' : 'Add'; ?> Questions
                    </h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="admin_dashboard.php"><i class="bi bi-house-door"></i> Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="questions.php">Questions</a></li>
                            <li class="breadcrumb-item active"><?php echo $isEdit ? 'Edit' : 'Add'; ?></li>
                        </ol>
                    </nav>
                </div>
                <div class="col-md-6 text-md-end">
                    <a href="questions.php" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left me-1"></i> Back to Questions
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Error Message -->
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger mb-4">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>
        
        <!-- Success Message -->
        <?php if (!empty($success)): ?>
            <div class="alert alert-success mb-4">
                <i class="bi bi-check-circle-fill me-2"></i>
                <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>

        <!-- Question Form -->
        <form method="POST" enctype="multipart/form-data" id="questions-form">
            <!-- REMOVED the hidden exam_id and subject_id fields since they were causing issues -->
            
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="exam_id_select" class="form-label">Exam</label>
                            <select class="form-select" id="exam_id_select" name="exam_id_select" <?php echo $isEdit ? 'disabled' : ''; ?> required>
                                <option value="">Select Exam</option>
                                <?php foreach ($exams as $exam): ?>
                                    <option value="<?php echo $exam['id']; ?>" <?php echo $examId == $exam['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($exam['exam_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="subject_id_select" class="form-label">Subject</label>
                            <select class="form-select" id="subject_id_select" name="subject_id_select" <?php echo $isEdit ? 'disabled' : ''; ?> required>
                                <option value="">Select Subject</option>
                                <?php foreach ($subjects as $subject): ?>
                                    <option value="<?php echo $subject['id']; ?>" <?php echo $subjectId == $subject['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($subject['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <!-- Marks Configuration -->
                    <div class="marks-container">
                        <div class="row">
                            <div class="col-md-6">
                                <label for="marks_per_question" class="form-label">Marks Per Question</label>
                                <input type="number" class="form-control" id="marks_per_question" 
                                       name="marks_per_question" min="1" value="<?php echo $marksPerQuestion; ?>" required>
                                <small class="text-muted">Default marks for all questions</small>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mt-4 pt-3">
                                    <input class="form-check-input" type="checkbox" id="use_individual_marks">
                                    <label class="form-check-label" for="use_individual_marks">
                                        Use individual marks per question
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div> 
            
            <div id="questions-container">
                <?php if (!empty($questions)): ?>
                    <?php foreach ($questions as $index => $question): ?>
                        <div class="question-row" data-index="<?php echo $index; ?>">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <div class="d-flex align-items-center">
                                    <span class="question-number"><?php echo $question['question_number']; ?>.</span>
                                    <input type="text" class="form-control" name="questions[<?php echo $index; ?>][text]" 
                                           value="<?php echo htmlspecialchars($question['question_text']); ?>" required>
                                </div>
                                <button type="button" class="btn btn-link text-danger" onclick="removeQuestion(this)">
                                    <i class="bi bi-trash"></i> Remove
                                </button>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Question Image (Optional)</label>
                                <input type="file" class="form-control" name="questions[<?php echo $index; ?>][image]" accept="image/*">
                                <input type="hidden" name="questions[<?php echo $index; ?>][existing_image]" value="<?php echo htmlspecialchars($question['picture_url']); ?>">
                                <?php if (!empty($question['picture_url'])): ?>
                                    <div class="mt-2">
                                        <img src="../uploads/questions/<?php echo htmlspecialchars($question['picture_url']); ?>" class="question-image-preview">
                                        <div class="form-check mt-2">
                                            <input class="form-check-input" type="checkbox" 
                                                   id="remove_image_<?php echo $index; ?>" 
                                                   name="questions[<?php echo $index; ?>][remove_image]">
                                            <label class="form-check-label text-danger" for="remove_image_<?php echo $index; ?>">
                                                Remove current image
                                            </label>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="options-container">
                                <?php foreach (['A', 'B', 'C', 'D'] as $option): ?>
                                    <div class="option-container <?php echo $question['correct_option'] == $option ? 'correct-option' : ''; ?>">
                                        <span class="option-label"><?php echo $option; ?>:</span>
                                        <input type="text" class="form-control" 
                                               name="questions[<?php echo $index; ?>][options][<?php echo $option; ?>]" 
                                               value="<?php echo htmlspecialchars($question['option_' . strtolower($option)]); ?>"
                                               <?php echo in_array($option, ['A', 'B']) ? 'required' : ''; ?>>
                                        <div class="form-check ms-3">
                                            <input class="form-check-input" type="radio" 
                                                   name="questions[<?php echo $index; ?>][correct_option]" 
                                                   value="<?php echo $option; ?>"
                                                   <?php echo $question['correct_option'] == $option ? 'checked' : ''; ?>
                                                   required>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <div class="mt-3 individual-marks" style="display: none;">
                                <label class="form-label">Marks for this question</label>
                                <input type="number" class="form-control" name="questions[<?php echo $index; ?>][marks]" 
                                       value="<?php echo htmlspecialchars($question['marks']); ?>" min="1">
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <div class="d-flex justify-content-between mb-4">
                <button type="button" class="btn btn-primary" id="add-question-btn">
                    <i class="bi bi-plus-circle me-1"></i> Add Question
                </button>
                
                <button type="submit" class="btn btn-success" id="save-all-btn">
                    <i class="bi bi-save me-1"></i> <?php echo $isEdit ? 'Update All Questions' : 'Save All Questions'; ?>
                </button>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const questionsContainer = document.getElementById('questions-container');
            const addQuestionBtn = document.getElementById('add-question-btn');
            const saveAllBtn = document.getElementById('save-all-btn');
            const useIndividualMarks = document.getElementById('use_individual_marks');
            const marksPerQuestion = document.getElementById('marks_per_question');
            
            // Initialize question count
            let questionCount = <?php echo count($questions); ?>;
            
            // Show save button if we have questions
            if (questionCount > 0) {
                saveAllBtn.style.display = 'block';
            }
            
            // Toggle individual marks visibility
            useIndividualMarks.addEventListener('change', function() {
                document.querySelectorAll('.individual-marks').forEach(el => {
                    el.style.display = this.checked ? 'block' : 'none';
                });
            });
            
            // Add question button click handler
            addQuestionBtn.addEventListener('click', function() {
                questionCount++;
                const questionIndex = questionCount - 1;
                
                const questionRow = document.createElement('div');
                questionRow.className = 'question-row';
                questionRow.dataset.index = questionIndex;
                
                questionRow.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="d-flex align-items-center">
                            <span class="question-number">${questionCount}.</span>
                            <input type="text" class="form-control" name="questions[${questionIndex}][text]" 
                                   placeholder="Enter question text" required>
                        </div>
                        <button type="button" class="btn btn-link text-danger" onclick="removeQuestion(this)">
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Question Image (Optional)</label>
                        <input type="file" class="form-control" name="questions[${questionIndex}][image]" accept="image/*">
                        <input type="hidden" name="questions[${questionIndex}][existing_image]" value="">
                        <div class="image-preview-container mt-2" id="image-preview-${questionIndex}"></div>
                    </div>
                    
                    <div class="options-container">
                        ${['A', 'B', 'C', 'D'].map(option => `
                            <div class="option-container">
                                <span class="option-label">${option}:</span>
                                <input type="text" class="form-control" name="questions[${questionIndex}][options][${option}]" 
                                       placeholder="Option ${option}" ${option === 'A' || option === 'B' ? 'required' : ''}>
                                <div class="form-check ms-3">
                                    <input class="form-check-input" type="radio" 
                                           name="questions[${questionIndex}][correct_option]" 
                                           value="${option}" ${option === 'A' ? 'required' : ''}>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                    
                    <div class="mt-3 individual-marks" style="display: none;">
                        <label class="form-label">Marks for this question</label>
                        <input type="number" class="form-control" name="questions[${questionIndex}][marks]" 
                               value="${marksPerQuestion.value}" min="1">
                    </div>
                `;
                
                questionsContainer.appendChild(questionRow);
                saveAllBtn.style.display = 'block';
                
                // Show/hide individual marks based on checkbox
                if (useIndividualMarks.checked) {
                    questionRow.querySelector('.individual-marks').style.display = 'block';
                }
                
                // Add image preview functionality
                const fileInput = questionRow.querySelector('input[type="file"]');
                fileInput.addEventListener('change', function(e) {
                    const previewContainer = document.getElementById(`image-preview-${questionIndex}`);
                    previewContainer.innerHTML = '';
                    
                    if (e.target.files.length > 0) {
                        const file = e.target.files[0];
                        const reader = new FileReader();
                        
                        reader.onload = function(event) {
                            const img = document.createElement('img');
                            img.src = event.target.result;
                            img.className = 'question-image-preview';
                            previewContainer.appendChild(img);
                        };
                        
                        reader.readAsDataURL(file);
                    }
                });
                
                // Highlight correct option when selected
                questionRow.querySelectorAll('input[type="radio"]').forEach(radio => {
                    radio.addEventListener('change', function() {
                        this.closest('.option-container').classList.add('correct-option');
                        
                        // Remove highlight from other options
                        questionRow.querySelectorAll('.option-container').forEach(opt => {
                            if (opt !== this.closest('.option-container')) {
                                opt.classList.remove('correct-option');
                            }
                        });
                    });
                });
            });
            
            // Highlight existing correct options
            document.querySelectorAll('.option-container').forEach(container => {
                if (container.querySelector('input[type="radio"]:checked')) {
                    container.classList.add('correct-option');
                }
            });
            
            // Initialize individual marks display based on checkbox
            if (useIndividualMarks.checked) {
                document.querySelectorAll('.individual-marks').forEach(el => {
                    el.style.display = 'block';
                });
            }
        });
        
        // Global function for removing questions
        function removeQuestion(button) {
            const questionRow = button.closest('.question-row');
            const questionIndex = parseInt(questionRow.dataset.index);
            
            if (!confirm('Are you sure you want to remove this question?')) {
                return;
            }
            
            questionRow.remove();
            
            // Reindex remaining questions
            const remainingQuestions = document.querySelectorAll('.question-row');
            if (remainingQuestions.length === 0) {
                document.getElementById('save-all-btn').style.display = 'none';
                return;
            }
            
            remainingQuestions.forEach((row, index) => {
                row.dataset.index = index;
                const questionNumber = row.querySelector('.question-number');
                questionNumber.textContent = `${index + 1}.`;
                
                // Update all names in inputs
                const inputs = row.querySelectorAll('input, select, textarea');
                inputs.forEach(input => {
                    const name = input.name.replace(/questions\[\d+\]/, `questions[${index}]`);
                    input.name = name;
                });
                
                // Update IDs if they exist
                if (input.id) {
                    const id = input.id.replace(/\d+/, index);
                    input.id = id;
                }
            });
        }
    </script>
</body>
</html>