<?php
require_once '../config/config.php';
requireRole('secretariat');

$pageTitle = 'Post-Test Questions - Secretariat - PSAU GAD';
$db = getDB();

// Get test ID
$testId = isset($_GET['test_id']) ? (int)$_GET['test_id'] : 0;

if (!$testId) {
    $_SESSION['error'] = 'Invalid test ID.';
    header('Location: post-test-management.php');
    exit;
}

// Get test details
$stmt = $db->prepare("
    SELECT pt.*, a.title as activity_title 
    FROM post_tests pt
    JOIN activities a ON pt.activity_id = a.activity_id
    WHERE pt.test_id = ?
");
$stmt->execute([$testId]);
$test = $stmt->fetch();

if (!$test) {
    $_SESSION['error'] = 'Test not found.';
    header('Location: post-test-management.php');
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'add_question') {
        $questionText = trim($_POST['question_text']);
        $questionType = $_POST['question_type'];
        $points = (int)$_POST['points'];
        
        $optionA = isset($_POST['option_a']) ? trim($_POST['option_a']) : null;
        $optionB = isset($_POST['option_b']) ? trim($_POST['option_b']) : null;
        $optionC = isset($_POST['option_c']) ? trim($_POST['option_c']) : null;
        $optionD = isset($_POST['option_d']) ? trim($_POST['option_d']) : null;
        $correctAnswer = isset($_POST['correct_answer']) ? trim($_POST['correct_answer']) : null;
        
        // Get next order number
        $stmt = $db->prepare("SELECT COALESCE(MAX(order_num), 0) + 1 as next_order FROM test_questions WHERE test_id = ? AND test_type = 'post_test'");
        $stmt->execute([$testId]);
        $orderNum = $stmt->fetchColumn();
        
        try {
            $stmt = $db->prepare("
                INSERT INTO test_questions (test_id, test_type, question_text, question_type, option_a, option_b, option_c, option_d, correct_answer, points, order_num)
                VALUES (?, 'post_test', ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$testId, $questionText, $questionType, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $points, $orderNum]);
            $_SESSION['success'] = 'Question added successfully!';
            header('Location: post-test-questions.php?test_id=' . $testId);
            exit;
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error adding question: ' . $e->getMessage();
        }
    } elseif ($action === 'delete_question') {
        $questionId = (int)$_POST['question_id'];
        
        try {
            $stmt = $db->prepare("DELETE FROM test_questions WHERE question_id = ?");
            $stmt->execute([$questionId]);
            $_SESSION['success'] = 'Question deleted successfully!';
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error deleting question: ' . $e->getMessage();
        }
    }
}

// Get all questions
$stmt = $db->prepare("
    SELECT * FROM test_questions 
    WHERE test_id = ? AND test_type = 'post_test'
    ORDER BY order_num ASC
");
$stmt->execute([$testId]);
$questions = $stmt->fetchAll();

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-question-circle text-secretariat mr-2"></i>Manage Questions
                    </h1>
                    <p class="text-gray-600"><?php echo htmlspecialchars($test['title']); ?></p>
                    <p class="text-sm text-gray-500">Activity: <?php echo htmlspecialchars($test['activity_title']); ?></p>
                </div>
                <div class="flex gap-3">
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                            class="bg-secretariat text-white px-6 py-3 rounded-lg hover:bg-secretariat-dark transition font-semibold">
                        <i class="fas fa-plus mr-2"></i>Add Question
                    </button>
                    <a href="post-test-management.php" class="bg-gray-500 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition font-semibold">
                        <i class="fas fa-arrow-left mr-2"></i>Back
                    </a>
                </div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded">
                <i class="fas fa-check-circle mr-2"></i><?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded">
                <i class="fas fa-exclamation-circle mr-2"></i><?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>

        <!-- Test Info -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div class="text-center">
                    <p class="text-3xl font-bold text-secretariat"><?php echo count($questions); ?></p>
                    <p class="text-sm text-gray-600">Total Questions</p>
                </div>
                <div class="text-center">
                    <p class="text-3xl font-bold text-green-600"><?php echo array_sum(array_column($questions, 'points')); ?></p>
                    <p class="text-sm text-gray-600">Total Points</p>
                </div>
                <div class="text-center">
                    <p class="text-3xl font-bold text-yellow-600"><?php echo $test['passing_score']; ?>%</p>
                    <p class="text-sm text-gray-600">Passing Score</p>
                </div>
                <div class="text-center">
                    <p class="text-3xl font-bold text-purple-600"><?php echo $test['time_limit']; ?> min</p>
                    <p class="text-sm text-gray-600">Time Limit</p>
                </div>
            </div>
        </div>

        <!-- Questions List -->
        <div class="space-y-4">
            <?php if (empty($questions)): ?>
                <div class="bg-white rounded-xl shadow-lg p-12 text-center">
                    <i class="fas fa-question-circle text-gray-300 text-6xl mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">No Questions Yet</h3>
                    <p class="text-gray-600 mb-6">Add your first question to get started.</p>
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                            class="bg-secretariat text-white px-6 py-3 rounded-lg hover:bg-secretariat-dark transition font-semibold">
                        <i class="fas fa-plus mr-2"></i>Add Question
                    </button>
                </div>
            <?php else: ?>
                <?php foreach ($questions as $index => $question): ?>
                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex-1">
                                <div class="flex items-center mb-2">
                                    <span class="bg-secretariat text-white px-3 py-1 rounded-full text-sm font-bold mr-3">
                                        Q<?php echo $index + 1; ?>
                                    </span>
                                    <span class="px-3 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-700">
                                        <?php echo ucwords(str_replace('_', ' ', $question['question_type'])); ?>
                                    </span>
                                    <span class="ml-2 px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                                        <?php echo $question['points']; ?> <?php echo $question['points'] == 1 ? 'point' : 'points'; ?>
                                    </span>
                                </div>
                                <p class="text-lg text-gray-900 font-medium"><?php echo htmlspecialchars($question['question_text']); ?></p>
                            </div>
                            <form method="POST" class="ml-4" onsubmit="return confirm('Delete this question?')">
                                <input type="hidden" name="action" value="delete_question">
                                <input type="hidden" name="question_id" value="<?php echo $question['question_id']; ?>">
                                <button type="submit" class="text-red-600 hover:text-red-700">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                        
                        <?php if ($question['question_type'] === 'multiple_choice'): ?>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4">
                                <div class="flex items-center p-3 rounded-lg <?php echo $question['correct_answer'] === 'A' ? 'bg-green-50 border-2 border-green-500' : 'bg-gray-50'; ?>">
                                    <span class="font-bold mr-3">A.</span>
                                    <span><?php echo htmlspecialchars($question['option_a']); ?></span>
                                    <?php if ($question['correct_answer'] === 'A'): ?>
                                        <i class="fas fa-check-circle text-green-600 ml-auto"></i>
                                    <?php endif; ?>
                                </div>
                                <div class="flex items-center p-3 rounded-lg <?php echo $question['correct_answer'] === 'B' ? 'bg-green-50 border-2 border-green-500' : 'bg-gray-50'; ?>">
                                    <span class="font-bold mr-3">B.</span>
                                    <span><?php echo htmlspecialchars($question['option_b']); ?></span>
                                    <?php if ($question['correct_answer'] === 'B'): ?>
                                        <i class="fas fa-check-circle text-green-600 ml-auto"></i>
                                    <?php endif; ?>
                                </div>
                                <div class="flex items-center p-3 rounded-lg <?php echo $question['correct_answer'] === 'C' ? 'bg-green-50 border-2 border-green-500' : 'bg-gray-50'; ?>">
                                    <span class="font-bold mr-3">C.</span>
                                    <span><?php echo htmlspecialchars($question['option_c']); ?></span>
                                    <?php if ($question['correct_answer'] === 'C'): ?>
                                        <i class="fas fa-check-circle text-green-600 ml-auto"></i>
                                    <?php endif; ?>
                                </div>
                                <div class="flex items-center p-3 rounded-lg <?php echo $question['correct_answer'] === 'D' ? 'bg-green-50 border-2 border-green-500' : 'bg-gray-50'; ?>">
                                    <span class="font-bold mr-3">D.</span>
                                    <span><?php echo htmlspecialchars($question['option_d']); ?></span>
                                    <?php if ($question['correct_answer'] === 'D'): ?>
                                        <i class="fas fa-check-circle text-green-600 ml-auto"></i>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php elseif ($question['question_type'] === 'true_false'): ?>
                            <div class="flex gap-3 mt-4">
                                <div class="flex items-center p-3 rounded-lg <?php echo $question['correct_answer'] === 'TRUE' ? 'bg-green-50 border-2 border-green-500' : 'bg-gray-50'; ?>">
                                    <span class="font-bold mr-3">TRUE</span>
                                    <?php if ($question['correct_answer'] === 'TRUE'): ?>
                                        <i class="fas fa-check-circle text-green-600 ml-2"></i>
                                    <?php endif; ?>
                                </div>
                                <div class="flex items-center p-3 rounded-lg <?php echo $question['correct_answer'] === 'FALSE' ? 'bg-green-50 border-2 border-green-500' : 'bg-gray-50'; ?>">
                                    <span class="font-bold mr-3">FALSE</span>
                                    <?php if ($question['correct_answer'] === 'FALSE'): ?>
                                        <i class="fas fa-check-circle text-green-600 ml-2"></i>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php elseif ($question['question_type'] === 'essay'): ?>
                            <div class="mt-4 p-3 bg-blue-50 rounded-lg">
                                <p class="text-sm text-blue-700"><i class="fas fa-info-circle mr-2"></i>Essay question - requires manual grading</p>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Question Modal -->
<div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
        <div class="bg-secretariat text-white px-6 py-4 flex items-center justify-between rounded-t-xl sticky top-0">
            <h3 class="text-xl font-bold"><i class="fas fa-plus mr-2"></i>Add Question</h3>
            <button onclick="document.getElementById('addModal').classList.add('hidden')" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <form method="POST" class="p-6" id="questionForm">
            <input type="hidden" name="action" value="add_question">
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Question Type *</label>
                    <select name="question_type" id="questionType" required onchange="toggleOptions()"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                        <option value="multiple_choice">Multiple Choice</option>
                        <option value="true_false">True/False</option>
                        <option value="essay">Essay</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Question Text *</label>
                    <textarea name="question_text" required rows="3"
                              placeholder="Enter your question..."
                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"></textarea>
                </div>
                
                <div id="multipleChoiceOptions">
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Options *</label>
                    <div class="space-y-2">
                        <input type="text" name="option_a" placeholder="Option A" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <input type="text" name="option_b" placeholder="Option B" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <input type="text" name="option_c" placeholder="Option C" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <input type="text" name="option_d" placeholder="Option D" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                    </div>
                    
                    <label class="block text-sm font-semibold text-gray-700 mb-2 mt-4">Correct Answer *</label>
                    <select name="correct_answer" id="mcCorrectAnswer" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <option value="A">A</option>
                        <option value="B">B</option>
                        <option value="C">C</option>
                        <option value="D">D</option>
                    </select>
                </div>
                
                <div id="trueFalseOptions" class="hidden">
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Correct Answer *</label>
                    <select name="correct_answer_tf" id="tfCorrectAnswer" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <option value="TRUE">TRUE</option>
                        <option value="FALSE">FALSE</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Points *</label>
                    <input type="number" name="points" value="1" min="1" max="10" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                </div>
            </div>
            
            <div class="flex justify-end space-x-3 mt-6 pt-6 border-t border-gray-200">
                <button type="button" onclick="document.getElementById('addModal').classList.add('hidden')"
                        class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition font-semibold">
                    Cancel
                </button>
                <button type="submit" class="bg-secretariat text-white px-6 py-2 rounded-lg hover:bg-secretariat-dark transition font-semibold">
                    <i class="fas fa-save mr-2"></i>Add Question
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function toggleOptions() {
    const type = document.getElementById('questionType').value;
    const mcOptions = document.getElementById('multipleChoiceOptions');
    const tfOptions = document.getElementById('trueFalseOptions');
    const mcAnswer = document.getElementById('mcCorrectAnswer');
    const tfAnswer = document.getElementById('tfCorrectAnswer');
    
    if (type === 'multiple_choice') {
        mcOptions.classList.remove('hidden');
        tfOptions.classList.add('hidden');
        mcAnswer.name = 'correct_answer';
        tfAnswer.name = 'correct_answer_disabled';
    } else if (type === 'true_false') {
        mcOptions.classList.add('hidden');
        tfOptions.classList.remove('hidden');
        mcAnswer.name = 'correct_answer_disabled';
        tfAnswer.name = 'correct_answer';
    } else {
        mcOptions.classList.add('hidden');
        tfOptions.classList.add('hidden');
    }
}
</script>

<?php include '../includes/footer.php'; ?>

