<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

// Check login
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$success = "";
$error = "";

// Handle form submission
if (isset($_POST['submit_question'])) {
    $course  = $conn->real_escape_string($_POST['course']);
    $question = $conn->real_escape_string($_POST['question']);
    $type    = $conn->real_escape_string($_POST['type']);
    $options = null;
    $answer = '';

    // Validate required fields based on question type
    if ($type == 'multiple_choice') {
        if (empty($_POST['options']) || empty($_POST['answer_option'])) {
            $_SESSION['error'] = "Please provide both options and correct answer for multiple choice questions.";
            header("location:add_exam_question.php");
            exit();
        }
        
        $opts = array_map('trim', explode("\n", $_POST['options']));
        $opts = array_filter($opts); // Remove empty options
        
        if (count($opts) < 2) {
            $_SESSION['error'] = "Please provide at least 2 options for multiple choice questions.";
            header("location:add_exam_question.php");
            exit();
        }
        
        $options = json_encode($opts);
        
        // For multiple choice, get the selected option value
        $answer = $conn->real_escape_string($_POST['answer_option']);
    } else {
        // For essay questions, use the text answer
        if (empty($_POST['answer_text'])) {
            $_SESSION['error'] = "Please provide an answer for the essay question.";
            header("location:add_exam_question.php");
            exit();
        }
        $answer = $conn->real_escape_string($_POST['answer_text']);
    }

    // Validate that course and question are not empty
    if (empty($course) || empty($question)) {
        $_SESSION['error'] = "Please fill in all required fields.";
        header("location:add_exam_question.php");
        exit();
    }

    $sql = "INSERT INTO exam_questions (course, question, type, options, answer)
            VALUES ('$course', '$question', '$type', " . ($options ? "'$options'" : "NULL") . ", '$answer')";

    if ($conn->query($sql)) {
        $_SESSION['success'] = "Question added successfully!";
    } else {
        $_SESSION['error'] = "Error adding question: " . $conn->error;
    }

    header("location:add_exam_question.php");
    exit();
}

// Fetch all questions
$result = $conn->query("SELECT * FROM exam_questions ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exam Question Manager | Learning Management System</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
<style>
:root {
    --primary: #4e73df;
    --secondary: #6f42c1;
    --success: #1cc88a;
    --info: #36b9cc;
    --warning: #f6c23e;
    --danger: #e74a3b;
    --light: #f8f9fc;
    --dark: #5a5c69;
}

body {
    background-color: #f8f9fc;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.navbar {
    background: linear-gradient(90deg, var(--primary) 0%, var(--secondary) 100%);
}

.content {
    padding: 20px;
}

.card {
    border-radius: 10px;
    box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
    margin-bottom: 20px;
    border: none;
}

.card-header {
    background: linear-gradient(90deg, var(--primary) 0%, var(--secondary) 100%);
    color: white;
    border-radius: 10px 10px 0 0 !important;
}

.btn-primary {
    background-color: var(--primary);
    border-color: var(--primary);
}

.btn-primary:hover {
    background-color: #3a5fc8;
    border-color: #3a5fc8;
}

.table th {
    border-top: none;
    background-color: var(--primary);
    color: white;
}

.table-hover tbody tr:hover {
    background-color: rgba(78, 115, 223, 0.1);
}

.alert {
    border-radius: 10px;
    border: none;
}

.alert-success {
    background-color: rgba(28, 200, 138, 0.2);
    color: #0f6848;
}

.alert-danger {
    background-color: rgba(231, 74, 59, 0.2);
    color: #922724;
}

.form-control, .form-select {
    border-radius: 8px;
    padding: 10px 15px;
}

.form-control:focus, .form-select:focus {
    box-shadow: 0 0 0 0.25rem rgba(78, 115, 223, 0.25);
    border-color: var(--primary);
}

.btn {
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 600;
}

.badge-type {
    background-color: var(--info);
    color: white;
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.8rem;
}

.options-list {
    list-style-type: none;
    padding-left: 0;
    margin-bottom: 0;
}

.options-list li {
    padding: 3px 0;
    position: relative;
    padding-left: 20px;
}

.options-list li:before {
    content: "•";
    color: var(--primary);
    font-weight: bold;
    position: absolute;
    left: 0;
}

.page-title {
    color: var(--dark);
    font-weight: 700;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--primary);
}

.stats-card {
    text-align: center;
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 20px;
    color: white;
}

.stats-card i {
    font-size: 2rem;
    margin-bottom: 10px;
}

.stats-card h3 {
    font-size: 1.8rem;
    margin-bottom: 0;
}

.stats-card p {
    margin-bottom: 0;
    font-size: 0.9rem;
}

.stats-card.primary {
    background: linear-gradient(90deg, var(--primary) 0%, #3a5fc8 100%);
}

.stats-card.success {
    background: linear-gradient(90deg, var(--success) 0%, #17a673 100%);
}

.stats-card.warning {
    background: linear-gradient(90deg, var(--warning) 0%, #dda20a 100%);
}

/* Animation for new elements */
.animate-fade-in {
    animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .card {
        margin-bottom: 15px;
    }
    
    .stats-card {
        margin-bottom: 15px;
    }
}

/* Custom styles for form elements */
#multipleChoiceAnswerDiv .form-text {
    font-size: 0.85rem;
    color: #6c757d;
}

.form-label {
    font-weight: 600;
    margin-bottom: 8px;
    color: var(--dark);
}
</style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <div class="container-fluid">
        <h3 class="page-title animate-fade-in"><i class="fas fa-tasks me-2"></i>Exam Question Manager</h3>
        
        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="stats-card primary animate-fade-in">
                    <i class="fas fa-book"></i>
                    <h3>
                        <?php 
                        $course_count = $conn->query("SELECT COUNT(DISTINCT course) as count FROM exam_questions");
                        echo $course_count->fetch_assoc()['count'];
                        ?>
                    </h3>
                    <p>Total Courses</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card success animate-fade-in">
                    <i class="fas fa-question-circle"></i>
                    <h3>
                        <?php 
                        $question_count = $conn->query("SELECT COUNT(*) as count FROM exam_questions");
                        echo $question_count->fetch_assoc()['count'];
                        ?>
                    </h3>
                    <p>Total Questions</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card warning animate-fade-in">
                    <i class="fas fa-list-alt"></i>
                    <h3>
                        <?php 
                        $mc_count = $conn->query("SELECT COUNT(*) as count FROM exam_questions WHERE type='multiple_choice'");
                        echo $mc_count->fetch_assoc()['count'];
                        ?>
                    </h3>
                    <p>Multiple Choice Questions</p>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-lg-6">
                <!-- Add Question Card -->
                <div class="card animate-fade-in">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="fas fa-plus-circle me-2"></i>Add New Exam Question</h5>
                    </div>
                    <div class="card-body">
                        <!-- Success / Error Messages -->
                        <?php if(isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fa fa-check-circle me-2"></i> <?= $_SESSION['success']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success']); endif; ?>

                        <?php if(isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fa fa-exclamation-triangle me-2"></i> <?= $_SESSION['error']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error']); endif; ?>

                        <form method="post" id="questionForm">
                            <div class="row g-3">
                                <div class="col-md-12">
                                    <label class="form-label">Course Name</label>
                                    <select name="course" class="form-control" required>
                                        <option value="">-- Select Course --</option>
                                        <?php
                                        // Fetch courses from the database
                                        $courseQuery = mysqli_query($conn, "SELECT * FROM course ORDER BY course ASC");
                                        while($courseRow = mysqli_fetch_array($courseQuery)) {
                                            echo '<option value="' . htmlspecialchars($courseRow['course']) . '">' . 
                                                 htmlspecialchars($courseRow['course']) . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                
                                <div class="col-12">
                                    <label class="form-label">Question</label>
                                    <textarea name="question" class="form-control" rows="4" placeholder="Enter your question here..." required></textarea>
                                </div>

                                <div class="col-md-12">
                                    <label class="form-label">Question Type</label>
                                    <select name="type" class="form-select" id="questionType" onchange="toggleAnswerInput()" required>
                                        <option value="essay">Essay / One-word Answer</option>
                                        <option value="multiple_choice">Multiple Choice</option>
                                    </select>
                                </div>

                                <div class="col-12" id="answerSection">
                                    <!-- This will be dynamically populated based on question type -->
                                    <div id="essayAnswerDiv">
                                        <label class="form-label">Correct Answer</label>
                                        <input type="text" name="answer_text" class="form-control" placeholder="Enter the correct answer">
                                    </div>
                                    
                                    <div id="multipleChoiceAnswerDiv" style="display:none;">
                                        <div class="col-12">
                                            <label class="form-label">Options (enter one option per line)</label>
                                            <textarea name="options" id="optionsTextarea" class="form-control" rows="4" placeholder="Option A&#10;Option B&#10;Option C" oninput="updateAnswerOptions()"></textarea>
                                            <div class="form-text">The first option will be considered as Option A, the second as Option B, and so on.</div>
                                        </div>
                                        
                                        <div class="col-12 mt-3">
                                            <label class="form-label">Correct Answer</label>
                                            <select name="answer_option" id="answerSelect" class="form-select">
                                                <option value="">Please enter options first</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12 text-center mt-4">
                                    <button type="submit" name="submit_question" class="btn btn-primary btn-lg">
                                        <i class="fas fa-plus me-2"></i> Add Question
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-6">
                <!-- Questions Table Card -->
                <div class="card animate-fade-in">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="fas fa-list me-2"></i>All Questions</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Course</th>
                                        <th>Question</th>
                                        <th>Type</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php if($result->num_rows > 0): $i=1; ?>
                                    <?php while($row = $result->fetch_assoc()): ?>
                                    <tr>
                                        <td><?= $i++; ?></td>
                                        <td><span class="badge bg-primary"><?= htmlspecialchars($row['course']); ?></span></td>
                                        <td><?= htmlspecialchars(substr($row['question'], 0, 50)) . (strlen($row['question']) > 50 ? '...' : ''); ?></td>
                                        <td><span class="badge-type"><?= ucfirst($row['type']); ?></span></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#questionModal<?= $row['id']; ?>">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    
                                    <!-- Question Detail Modal -->
                                    <div class="modal fade" id="questionModal<?= $row['id']; ?>" tabindex="-1" aria-hidden="true">
                                        <div class="modal-dialog modal-lg">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">Question Details</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <strong>Course:</strong> <?= htmlspecialchars($row['course']); ?>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <strong>Type:</strong> <span class="badge-type"><?= ucfirst($row['type']); ?></span>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <strong>Question:</strong>
                                                        <p class="p-2 bg-light rounded"><?= htmlspecialchars($row['question']); ?></p>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <strong>Correct Answer:</strong>
                                                        <p class="p-2 bg-light rounded"><?= htmlspecialchars($row['answer']); ?></p>
                                                    </div>
                                                    
                                                    <?php if($row['type']=='multiple_choice' && $row['options']): ?>
                                                    <div class="mb-3">
                                                        <strong>Options:</strong>
                                                        <ul class="options-list p-2 bg-light rounded">
                                                            <?php 
                                                            $opts = json_decode($row['options'], true);
                                                            foreach($opts as $index => $o): 
                                                                $letter = chr(65 + $index); // A, B, C, etc.
                                                                $is_correct = (trim($o) === trim($row['answer']));
                                                            ?>
                                                                <li>
                                                                    <strong><?= $letter; ?>.</strong> <?= htmlspecialchars($o); ?>
                                                                    <?php if($is_correct): ?>
                                                                        <span class="badge bg-success ms-2">Correct</span>
                                                                    <?php endif; ?>
                                                                </li>
                                                            <?php endforeach; ?>
                                                        </ul>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <strong>Created:</strong> <?= $row['created_at']; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-4">
                                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No questions added yet. Start by adding a question using the form.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleAnswerInput() {
    const type = document.getElementById('questionType').value;
    const essayDiv = document.getElementById('essayAnswerDiv');
    const mcDiv = document.getElementById('multipleChoiceAnswerDiv');
    const essayInput = document.querySelector('input[name="answer_text"]');
    const optionsTextarea = document.getElementById('optionsTextarea');
    const answerSelect = document.getElementById('answerSelect');
    
    if (type === 'multiple_choice') {
        essayDiv.style.display = 'none';
        mcDiv.style.display = 'block';
        
        // Remove required attribute from essay answer
        essayInput.removeAttribute('required');
        
    } else {
        essayDiv.style.display = 'block';
        mcDiv.style.display = 'none';
        
        // Add required attribute back to essay answer
        essayInput.setAttribute('required', 'required');
        
        // Clear any existing multiple choice selection
        answerSelect.innerHTML = '<option value="">Please enter options first</option>';
        answerSelect.disabled = true;
        optionsTextarea.value = '';
    }
}

function updateAnswerOptions() {
    const optionsTextarea = document.getElementById('optionsTextarea');
    const answerSelect = document.getElementById('answerSelect');
    const options = optionsTextarea.value.split('\n').filter(opt => opt.trim() !== '');
    
    // Clear existing options
    answerSelect.innerHTML = '';
    
    if (options.length > 0) {
        // Add new options
        options.forEach((opt, index) => {
            const letter = String.fromCharCode(65 + index); // A, B, C, etc.
            const option = document.createElement('option');
            option.value = opt.trim();
            option.textContent = `${letter}. ${opt.trim()}`;
            answerSelect.appendChild(option);
        });
        
        answerSelect.disabled = false;
    } else {
        const option = document.createElement('option');
        option.value = '';
        option.textContent = 'Please enter options first';
        answerSelect.appendChild(option);
        answerSelect.disabled = true;
    }
}

// Form validation - FIXED VERSION
document.getElementById('questionForm').addEventListener('submit', function(e) {
    const type = document.getElementById('questionType').value;
    
    if (type === 'multiple_choice') {
        const optionsTextarea = document.getElementById('optionsTextarea');
        const answerSelect = document.getElementById('answerSelect');
        
        // Check if options are empty
        if (optionsTextarea.value.trim() === '') {
            e.preventDefault();
            alert('Please enter options for multiple choice questions.');
            optionsTextarea.focus();
            return false;
        }
        
        // Check if we have at least 2 options
        const options = optionsTextarea.value.split('\n').filter(opt => opt.trim() !== '');
        if (options.length < 2) {
            e.preventDefault();
            alert('Please provide at least 2 options for multiple choice questions.');
            optionsTextarea.focus();
            return false;
        }
        
        // Check if an answer is selected
        if (answerSelect.disabled || answerSelect.value === '') {
            e.preventDefault();
            alert('Please select a correct answer for multiple choice questions.');
            return false;
        }
    } else {
        // For essay questions, check if answer is provided
        const essayInput = document.querySelector('input[name="answer_text"]');
        if (essayInput.value.trim() === '') {
            e.preventDefault();
            alert('Please provide an answer for the essay question.');
            essayInput.focus();
            return false;
        }
    }
    
    // If we get here, the form is valid and will submit
});

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    toggleAnswerInput();
});

// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl)
});
</script>
</body>
</html>