<?php
// Admin Page to Add/Manage Quizzes and Questions

// Include the necessary files
require_once 'config.php';
require_once 'layouts.php';

// Check if the user is an admin
if (get_user_role() !== 'admin') {
    die("Access Denied: Admins only.");
}

$message = '';
$quizId = null;

// --- Handle Form Submissions ---

// 1. Handle Quiz Creation/Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_quiz') {
    $title = trim($_POST['title']);
    $topic = trim($_POST['topic']);
    $timeLimit = (int)($_POST['time_limit'] ?? 0);
    $timeUnit = $_POST['time_unit'] ?? 'seconds';

    // Calculate total time in seconds for storage
    $totalTimeInSeconds = 0;
    if ($timeLimit > 0) {
        $totalTimeInSeconds = ($timeUnit === 'minutes') ? $timeLimit * 60 : $timeLimit;
    }


    if (!empty($title) && !empty($topic)) {
        // Pass the total time in seconds to the save_quiz function
        $quizId = save_quiz($title, $topic, $totalTimeInSeconds); 
        $message = '<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-xl mb-4" role="alert">Quiz "' . htmlspecialchars($title) . '" created successfully! Add questions below. Time Limit Set: ' . ($totalTimeInSeconds > 0 ? format_time($totalTimeInSeconds) : 'No Limit') . '</div>';
    } else {
        $message = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl mb-4" role="alert">Please enter both a Title and a Topic for the quiz.</div>';
    }
}

// 2. Handle Question Addition
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_question') {
    $quizId = (int)$_POST['quiz_id'];
    $question = trim($_POST['question']);
    
    // Get the index of the correct option (1-based from the radio button)
    $correctIndex = (int)($_POST['correct_option_index'] ?? 0);
    
    // Collect all options texts (including empty ones for now)
    $rawOptions = array_map('trim', $_POST['options']);
    
    // Extract the text of the correct answer using the index (0-based array index is $correctIndex - 1)
    $correctAnswerText = '';
    if ($correctIndex > 0 && isset($rawOptions[$correctIndex - 1])) {
        $correctAnswerText = $rawOptions[$correctIndex - 1];
    }

    // Now filter the options to remove empty ones, keeping only those that have text
    $options = array_filter($rawOptions); 
    
    // Validation check
    if (empty($correctAnswerText) || !in_array($correctAnswerText, $options)) {
        // If the selected option is empty or no correct option was chosen
        $message = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl mb-4" role="alert">Please select the correct option and ensure it has text before saving.</div>';
    } elseif (!empty($quizId) && !empty($question) && count($options) >= 2) {
        
        shuffle($options); // Shuffle options for display in the quiz later

        // Use $correctAnswerText as the answer text for the database
        add_quiz_question($quizId, $question, $options, $correctAnswerText); 
        $quiz = get_quiz_by_id($quizId);
        $message = '<div class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded-xl mb-4" role="alert">Question added to quiz "' . htmlspecialchars($quiz['title']) . '". Total questions: ' . count($quiz['questions']) . '</div>';
    } else {
        $message = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl mb-4" role="alert">Please fill out the question, select the correct option, and provide text for at least two distinct options.</div>';
    }
}

// Check for quiz ID in POST (after creation/addition) or GET (after selection)
if (isset($_POST['quiz_id'])) {
    $quizId = (int)$_POST['quiz_id'];
} elseif (isset($_GET['quiz_id'])) {
    $quizId = (int)$_GET['quiz_id'];
}

// Helper function (Assuming this is available or added to config.php in a prior step)
// Converts seconds to a human-readable format (e.g., 5 min 30 sec)
function format_time($seconds) {
    if (!is_numeric($seconds) || $seconds <= 0) return 'No Limit';
    $minutes = floor($seconds / 60);
    $remainingSeconds = $seconds % 60;
    $output = '';
    if ($minutes > 0) {
        $output .= $minutes . ' min' . ($minutes > 1 ? 's' : '');
    }
    if ($remainingSeconds > 0) {
        if ($minutes > 0) $output .= ' ';
        $output .= $remainingSeconds . ' sec' . ($remainingSeconds > 1 ? 's' : '');
    }
    return trim($output);
}


// --- Render Page ---

// NOTE: Assuming render_header, render_topbar, render_sidebar, render_main_content_end, and render_footer are in layouts.php
// and get_all_quizzes, get_quiz_by_id, save_quiz, add_quiz_question are available via config.php

render_header('Add Quizzes');
render_topbar('Add Quizzes');
render_sidebar(get_user_role(), basename($_SERVER['PHP_SELF']));

$quizzes = get_all_quizzes();
$currentQuiz = $quizId ? get_quiz_by_id($quizId) : null;
?>

<div class="space-y-10">
    <h2 class="text-3xl font-extrabold text-gray-900 border-b pb-2" id="quiz-selection">Quiz Management</h2>

    <?= $message ?>

    <!-- 1. Select Existing Quiz or Create New (Always Visible) -->
    <div class="bg-white p-6 rounded-xl shadow-2xl border-2 border-indigo-400">
        <h3 class="text-2xl font-semibold text-indigo-700 mb-4 flex items-center">
            <i class="fa-solid fa-layer-group mr-2"></i> Select/Create Quiz Pack
        </h3>
        
        <!-- Existing Quizzes Dropdown -->
        <div class="mb-4">
            <label for="select_quiz" class="block text-sm font-medium text-gray-700 mb-2">
                Select Existing Quiz to Edit Questions:
            </label>
            <select id="select_quiz" class="w-full p-3 border border-gray-300 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 bg-gray-50">
                <option value="">-- Choose a Quiz --</option>
                <?php foreach ($quizzes as $quiz): ?>
                    <option value="<?= $quiz['id'] ?>" <?= $quizId == $quiz['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($quiz['title']) ?> (<?= count($quiz['questions']) ?> Qs, Time: <?= format_time($quiz['time_limit_seconds'] ?? 0) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
            
            <!-- New Quiz button to toggle the form -->
            <button id="toggle-create-form" type="button" class="mt-3 inline-block text-sm text-indigo-600 hover:text-indigo-800 font-medium transition duration-150 hover:underline focus:outline-none">
                <i class="fa-solid fa-plus-circle mr-1"></i> Create New Quiz
            </button>
        </div>

        <!-- OR Separator - Hidden by default -->
        <p id="or-separator" class="text-center my-4 text-gray-500 font-bold hidden">OR</p>

        <!-- New Quiz Creation Form - Hidden by default -->
        <div id="new-quiz-form-container" class="hidden">
            <h4 class="text-xl font-medium text-gray-700 mb-3">Create New Quiz</h4>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="action" value="create_quiz">
                <div>
                    <label for="title" class="block text-sm font-medium text-gray-700">Quiz Title:</label>
                    <input type="text" id="title" name="title" required
                           class="mt-1 block w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <div>
                    <label for="topic" class="block text-sm font-medium text-gray-700">Topic/Class:</label>
                    <input type="text" id="topic" name="topic" required
                           class="mt-1 block w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                </div>

                <!-- New Time Limit Fields -->
                <div class="p-4 border border-dashed border-gray-300 rounded-xl bg-gray-50">
                    <label class="block text-lg font-bold text-gray-700 mb-3">Time Limit per Quiz:</label>
                    <div class="flex space-x-4">
                        <div class="flex-1">
                            <label for="time_limit" class="block text-sm font-medium text-gray-700">Time Value:</label>
                            <input type="number" id="time_limit" name="time_limit" value="0" min="0" 
                                   class="mt-1 block w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <div class="flex-1">
                            <label for="time_unit" class="block text-sm font-medium text-gray-700">Unit:</label>
                            <select id="time_unit" name="time_unit"
                                    class="mt-1 block w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white">
                                <option value="seconds">Seconds</option>
                                <option value="minutes">Minutes</option>
                            </select>
                        </div>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">Set to 0 for no time limit. This applies to the entire quiz, not per question.</p>
                </div>
                <!-- End New Time Limit Fields -->
                
                <button type="submit"
                        class="w-full py-3 px-4 border border-transparent rounded-xl shadow-lg text-white font-semibold bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-200 transform hover:scale-[1.01]">
                    <i class="fa-solid fa-plus mr-2"></i> Create Quiz
                </button>
            </form>
        </div>
    </div>

    <!-- 2. Add Questions Form -->
    <div class="bg-white p-6 rounded-xl shadow-2xl border-2 border-green-400 min-h-[400px]">
        
        <?php if ($currentQuiz): ?>
            <h3 class="text-2xl font-semibold text-green-700 mb-4 flex items-center">
                <i class="fa-solid fa-circle-question mr-2"></i> Add Question to: <span class="ml-2 font-extrabold text-indigo-600"><?= htmlspecialchars($currentQuiz['title']) ?></span>
            </h3>
            <p class="text-sm text-gray-500 mb-4">
                Total Questions: <span class="font-bold text-lg"><?= count($currentQuiz['questions']) ?></span> | 
                Time Limit: <span class="font-bold text-lg text-red-500"><?= format_time($currentQuiz['time_limit_seconds'] ?? 0) ?></span>
            </p>

            <form method="POST" class="space-y-5">
                <input type="hidden" name="action" value="add_question">
                <input type="hidden" name="quiz_id" value="<?= $currentQuiz['id'] ?>">

                <div>
                    <label for="question" class="block text-sm font-medium text-gray-700">Question Text:</label>
                    <textarea id="question" name="question" rows="3" required
                           class="mt-1 block w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500"></textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <?php 
                    // Generate 4 option inputs with an accompanying radio button
                    $options = array_fill(0, 4, '');
                    for ($i = 1; $i <= 4; $i++): 
                    ?>
                    <div class="flex items-center space-x-3 p-2 border border-gray-200 rounded-xl">
                        <!-- Radio Button to select the correct answer -->
                        <input type="radio" id="is_correct_<?= $i ?>" name="correct_option_index" value="<?= $i ?>" required 
                               class="h-5 w-5 text-green-600 border-gray-300 focus:ring-green-500 cursor-pointer">
                        
                        <div class="flex-grow">
                            <label for="option<?= $i ?>" class="block text-sm font-medium text-gray-700">Option <?= $i ?>:</label>
                            <input type="text" id="option<?= $i ?>" name="options[]" placeholder="E.g., An option"
                                   class="mt-1 block w-full p-2 border border-gray-300 rounded-lg shadow-sm focus:ring-gray-400 focus:border-gray-400">
                        </div>
                    </div>
                    <?php endfor; ?>
                </div>



                <button type="submit"
                        class="w-full py-3 px-4 border border-transparent rounded-xl shadow-lg text-white font-semibold bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition duration-200 transform hover:scale-[1.01]">
                    <i class="fa-solid fa-plus-square mr-2"></i> Save Question
                </button>
            </form>
        <?php else: ?>
            <!-- Simple fallback message when NO Quiz is Selected (Modal handles primary prompt) -->
            <div class="flex flex-col items-center justify-center p-8 text-center h-full bg-gray-50 rounded-xl">
                <i class="fa-solid fa-lock text-6xl text-gray-400 mb-4"></i>
                <p class="text-xl font-medium text-gray-600">
                    To add questions, please select a Quiz above or create a new one.
                </p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- --- Full-Screen Modal Overlay to Force Quiz Selection --- -->
<?php if (!$currentQuiz): ?>
<div id="quiz-selection-modal" class="fixed inset-0 bg-gray-900 bg-opacity-90 z-50 flex items-center justify-center p-4" aria-modal="true" role="dialog">
    <div class="bg-white rounded-2xl shadow-2xl p-8 max-w-lg w-full transform transition-all duration-300 scale-100">
        <div class="text-center">
            <i class="fa-solid fa-exclamation-triangle text-6xl text-red-600 mb-4 animate-pulse"></i>
            <h3 class="text-3xl font-extrabold text-gray-900 mb-3">Select Quiz Pack Or Make>
            <p class="text-lg text-gray-600 mb-6">
              Before adding questions, please select your quiz or create a new quiz.
            </p>
        </div>

        <!-- Quiz Selection Dropdown (Mirrored for Modal interaction) -->
        <div class="mb-6 border-t pt-4">
            <label for="modal_select_quiz" class="block text-sm font-medium text-gray-700 mb-2">
                Select Existing Quiz:
            </label>
            <select id="modal_select_quiz" class="w-full p-3 border border-gray-300 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 bg-gray-50">
                <option value="">-- Choose a Quiz --</option>
                <?php foreach ($quizzes as $quiz): ?>
                    <option value="<?= $quiz['id'] ?>">
                        <?= htmlspecialchars($quiz['title']) ?> (<?= count($quiz['questions']) ?> Qs, Time: <?= format_time($quiz['time_limit_seconds'] ?? 0) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <p class="text-center my-4 text-gray-500 font-bold">OR</p>
        
        <button type="button" onclick="document.getElementById('quiz-selection-modal').style.display='none';"
           class="w-full inline-block text-center py-3 px-4 border border-transparent rounded-xl shadow-lg text-white font-semibold bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-200">
            <i class="fa-solid fa-pencil-ruler mr-2"></i> Make New Quiz Pack
        </button>
        <p class="text-xs text-gray-400 mt-2 text-center">ClassKey Digital Education</p>

    </div>
</div>

<script>
    // Modal specific script to handle selection
    document.getElementById('modal_select_quiz').addEventListener('change', function() {
        const selectedId = this.value;
        if (selectedId) {
            // Reload the page with the selected quiz ID. This action effectively 'closes' the modal
            // because the PHP condition !$currentQuiz will no longer be true on reload.
            window.location.href = 'addquiz.php?quiz_id=' + selectedId;
        }
    });
</script>
<?php endif; ?>

<!-- JavaScript to handle main quiz selection change and form toggle -->
<script>
    document.getElementById('select_quiz').addEventListener('change', function() {
        const selectedId = this.value;
        if (selectedId) {
            // Correctly constructs the URL with the selected quiz ID.
            window.location.href = 'addquiz.php?quiz_id=' + selectedId;
        } else {
            // If "Choose a Quiz" is selected, go back to the base page
            window.location.href = 'addquiz.php';
        }
    });
    
    // Logic to toggle the New Quiz Creation Form
    document.addEventListener('DOMContentLoaded', function() {
        const toggleButton = document.getElementById('toggle-create-form');
        const formContainer = document.getElementById('new-quiz-form-container');
        const separator = document.getElementById('or-separator');

        if (toggleButton && formContainer && separator) {
            toggleButton.addEventListener('click', function() {
                const isHidden = formContainer.classList.contains('hidden');
                
                if (isHidden) {
                    // Show form
                    formContainer.classList.remove('hidden');
                    separator.classList.remove('hidden');
                    toggleButton.innerHTML = '<i class="fa-solid fa-minus-circle mr-1"></i> Hide New Quiz';
                } else {
                    // Hide form
                    formContainer.classList.add('hidden');
                    separator.classList.add('hidden');
                    toggleButton.innerHTML = '<i class="fa-solid fa-plus-circle mr-1"></i> Make New Quiz';
                }
            });
        }
    });
</script>

<?php
render_main_content_end();
render_footer();
?>