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

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

// Get activity ID
$activityId = isset($_GET['activity_id']) ? (int)$_GET['activity_id'] : 0;

if (!$activityId) {
    $_SESSION['error'] = 'Invalid activity ID.';
    header('Location: my-activities.php');
    exit;
}

// Get activity details
$stmt = $db->prepare("SELECT * FROM activities WHERE activity_id = ?");
$stmt->execute([$activityId]);
$activity = $stmt->fetch();

if (!$activity) {
    $_SESSION['error'] = 'Activity not found.';
    header('Location: my-activities.php');
    exit;
}

// Check if user is registered for this activity
$stmt = $db->prepare("
    SELECT * FROM activity_registrations 
    WHERE activity_id = ? AND user_id = ? AND status = 'approved'
");
$stmt->execute([$activityId, getCurrentUserId()]);
$registration = $stmt->fetch();

if (!$registration) {
    $_SESSION['error'] = 'You are not registered for this activity.';
    header('Location: my-activities.php');
    exit;
}

// Get post-test for this activity
$stmt = $db->prepare("
    SELECT * FROM post_tests 
    WHERE activity_id = ? AND is_active = 1
    LIMIT 1
");
$stmt->execute([$activityId]);
$test = $stmt->fetch();

if (!$test) {
    $_SESSION['error'] = 'No post-test available for this activity.';
    header('Location: my-activities.php');
    exit;
}

// Check if already taken
$stmt = $db->prepare("
    SELECT * FROM post_test_responses 
    WHERE test_id = ? AND user_id = ?
");
$stmt->execute([$test['test_id'], getCurrentUserId()]);
$existingResponse = $stmt->fetch();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_test'])) {
    if ($existingResponse) {
        $_SESSION['error'] = 'You have already taken this post-test.';
        header('Location: post-test.php?activity_id=' . $activityId);
        exit;
    }
    
    $startTime = strtotime($_POST['start_time']);
    $timeTaken = time() - $startTime;
    
    try {
        $db->beginTransaction();
        
        // Create response record
        $stmt = $db->prepare("
            INSERT INTO post_test_responses (test_id, user_id, activity_id, registration_id, started_at, submitted_at, time_taken)
            VALUES (?, ?, ?, ?, FROM_UNIXTIME(?), NOW(), ?)
        ");
        $stmt->execute([$test['test_id'], getCurrentUserId(), $activityId, $registration['registration_id'], $startTime, $timeTaken]);
        $responseId = $db->lastInsertId();
        
        // Get all questions
        $stmt = $db->prepare("
            SELECT * FROM test_questions 
            WHERE test_id = ? AND test_type = 'post_test'
            ORDER BY order_num
        ");
        $stmt->execute([$test['test_id']]);
        $questions = $stmt->fetchAll();
        
        $totalScore = 0;
        $totalPoints = 0;
        
        // Process each answer
        foreach ($questions as $question) {
            $questionId = $question['question_id'];
            $answer = isset($_POST['answer_' . $questionId]) ? trim($_POST['answer_' . $questionId]) : '';
            
            $isCorrect = 0;
            $pointsEarned = 0;
            
            if ($question['question_type'] !== 'essay') {
                // Auto-grade multiple choice and true/false
                if (strtoupper($answer) === strtoupper($question['correct_answer'])) {
                    $isCorrect = 1;
                    $pointsEarned = $question['points'];
                    $totalScore += $pointsEarned;
                }
            }
            
            $totalPoints += $question['points'];
            
            // Save answer
            $stmt = $db->prepare("
                INSERT INTO test_answers (response_id, test_type, question_id, answer_text, is_correct, points_earned)
                VALUES (?, 'post_test', ?, ?, ?, ?)
            ");
            $stmt->execute([$responseId, $questionId, $answer, $isCorrect, $pointsEarned]);
        }
        
        // Calculate percentage and pass/fail
        $percentage = $totalPoints > 0 ? ($totalScore / $totalPoints) * 100 : 0;
        $passed = $percentage >= $test['passing_score'] ? 1 : 0;
        
        // Update response with scores
        $stmt = $db->prepare("
            UPDATE post_test_responses 
            SET score = ?, total_points = ?, percentage = ?, passed = ?
            WHERE response_id = ?
        ");
        $stmt->execute([$totalScore, $totalPoints, $percentage, $passed, $responseId]);
        
        $db->commit();
        
        $_SESSION['success'] = 'Pre-test submitted successfully!';
        header('Location: post-test-result.php?response_id=' . $responseId);
        exit;
        
    } catch (PDOException $e) {
        $db->rollBack();
        $_SESSION['error'] = 'Error submitting test: ' . $e->getMessage();
    }
}

// Get questions if not yet taken
$questions = [];
if (!$existingResponse) {
    $stmt = $db->prepare("
        SELECT * FROM test_questions 
        WHERE test_id = ? AND test_type = 'post_test'
        ORDER BY order_num
    ");
    $stmt->execute([$test['test_id']]);
    $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 max-w-4xl">
        <?php if ($existingResponse): ?>
            <!-- Already Taken -->
            <div class="bg-white rounded-xl shadow-lg p-8 text-center">
                <i class="fas fa-check-circle text-green-500 text-6xl mb-4"></i>
                <h2 class="text-2xl font-bold text-gray-900 mb-2">Post-Test Already Completed</h2>
                <p class="text-gray-600 mb-6">You have already taken this post-test.</p>
                
                <div class="bg-gray-50 rounded-lg p-6 mb-6">
                    <div class="grid grid-cols-3 gap-4">
                        <div>
                            <p class="text-3xl font-bold text-employee"><?php echo number_format($existingResponse['score'], 1); ?></p>
                            <p class="text-sm text-gray-600">Score</p>
                        </div>
                        <div>
                            <p class="text-3xl font-bold text-employee"><?php echo number_format($existingResponse['percentage'], 1); ?>%</p>
                            <p class="text-sm text-gray-600">Percentage</p>
                        </div>
                        <div>
                            <p class="text-3xl font-bold <?php echo $existingResponse['passed'] ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo $existingResponse['passed'] ? 'PASSED' : 'FAILED'; ?>
                            </p>
                            <p class="text-sm text-gray-600">Result</p>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-center gap-3">
                    <a href="post-test-result.php?response_id=<?php echo $existingResponse['response_id']; ?>" 
                       class="bg-employee text-white px-6 py-3 rounded-lg hover:bg-employee-dark transition font-semibold">
                        <i class="fas fa-eye mr-2"></i>View Results
                    </a>
                    <a href="my-activities.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 to Activities
                    </a>
                </div>
            </div>
        <?php else: ?>
            <!-- Take Test -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <!-- Header -->
                <div class="bg-employee text-white px-8 py-6">
                    <h1 class="text-2xl font-bold mb-2">
                        <i class="fas fa-file-alt mr-2"></i><?php echo htmlspecialchars($test['title']); ?>
                    </h1>
                    <p class="text-employee-light"><?php echo htmlspecialchars($activity['title']); ?></p>
                </div>
                
                <!-- Instructions -->
                <div class="bg-yellow-50 border-l-4 border-yellow-500 p-6">
                    <h3 class="font-bold text-gray-900 mb-2"><i class="fas fa-info-circle mr-2"></i>Instructions</h3>
                    <?php if ($test['instructions']): ?>
                        <p class="text-gray-700 mb-4"><?php echo nl2br(htmlspecialchars($test['instructions'])); ?></p>
                    <?php endif; ?>
                    <ul class="list-disc list-inside text-gray-700 space-y-1">
                        <li>Total Questions: <strong><?php echo count($questions); ?></strong></li>
                        <li>Passing Score: <strong><?php echo $test['passing_score']; ?>%</strong></li>
                        <li>Time Limit: <strong><?php echo $test['time_limit']; ?> minutes</strong></li>
                        <li>You can only take this test <strong>once</strong></li>
                        <li>Make sure to answer all questions before submitting</li>
                    </ul>
                </div>
                
                <!-- Test Form -->
                <form method="POST" id="testForm" class="p-8">
                    <input type="hidden" name="submit_test" value="1">
                    <input type="hidden" name="start_time" value="<?php echo time(); ?>">
                    
                    <!-- Timer -->
                    <div class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-center">
                        <p class="text-sm text-gray-600 mb-1">Time Remaining</p>
                        <p id="timer" class="text-3xl font-bold text-red-600">--:--</p>
                    </div>
                    
                    <!-- Questions -->
                    <div class="space-y-8">
                        <?php foreach ($questions as $index => $question): ?>
                            <div class="border border-gray-200 rounded-lg p-6 bg-gray-50">
                                <div class="flex items-start mb-4">
                                    <span class="bg-employee text-white px-4 py-2 rounded-lg font-bold mr-4">
                                        <?php echo $index + 1; ?>
                                    </span>
                                    <div class="flex-1">
                                        <p class="text-lg font-medium text-gray-900 mb-2">
                                            <?php echo htmlspecialchars($question['question_text']); ?>
                                        </p>
                                        <span class="text-sm text-gray-500">
                                            (<?php echo $question['points']; ?> <?php echo $question['points'] == 1 ? 'point' : 'points'; ?>)
                                        </span>
                                    </div>
                                </div>
                                
                                <?php if ($question['question_type'] === 'multiple_choice'): ?>
                                    <div class="space-y-2 ml-16">
                                        <label class="flex items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                            <input type="radio" name="answer_<?php echo $question['question_id']; ?>" value="A" required class="mr-3">
                                            <span><strong>A.</strong> <?php echo htmlspecialchars($question['option_a']); ?></span>
                                        </label>
                                        <label class="flex items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                            <input type="radio" name="answer_<?php echo $question['question_id']; ?>" value="B" required class="mr-3">
                                            <span><strong>B.</strong> <?php echo htmlspecialchars($question['option_b']); ?></span>
                                        </label>
                                        <label class="flex items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                            <input type="radio" name="answer_<?php echo $question['question_id']; ?>" value="C" required class="mr-3">
                                            <span><strong>C.</strong> <?php echo htmlspecialchars($question['option_c']); ?></span>
                                        </label>
                                        <label class="flex items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                            <input type="radio" name="answer_<?php echo $question['question_id']; ?>" value="D" required class="mr-3">
                                            <span><strong>D.</strong> <?php echo htmlspecialchars($question['option_d']); ?></span>
                                        </label>
                                    </div>
                                <?php elseif ($question['question_type'] === 'true_false'): ?>
                                    <div class="space-y-2 ml-16">
                                        <label class="flex items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                            <input type="radio" name="answer_<?php echo $question['question_id']; ?>" value="TRUE" required class="mr-3">
                                            <span class="font-bold">TRUE</span>
                                        </label>
                                        <label class="flex items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                            <input type="radio" name="answer_<?php echo $question['question_id']; ?>" value="FALSE" required class="mr-3">
                                            <span class="font-bold">FALSE</span>
                                        </label>
                                    </div>
                                <?php elseif ($question['question_type'] === 'essay'): ?>
                                    <div class="ml-16">
                                        <textarea name="answer_<?php echo $question['question_id']; ?>" rows="5" required
                                                  placeholder="Type your answer here..."
                                                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-employee focus:border-transparent"></textarea>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Submit Button -->
                    <div class="mt-8 pt-6 border-t border-gray-200 flex justify-between items-center">
                        <a href="my-activities.php" class="text-gray-600 hover:text-gray-800">
                            <i class="fas fa-arrow-left mr-2"></i>Cancel
                        </a>
                        <button type="submit" onclick="return confirm('Are you sure you want to submit? You cannot retake this test.')"
                                class="bg-employee text-white px-8 py-3 rounded-lg hover:bg-employee-dark transition font-semibold text-lg">
                            <i class="fas fa-paper-plane mr-2"></i>Submit Test
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Timer
const timeLimit = <?php echo $test['time_limit']; ?> * 60; // Convert to seconds
let timeRemaining = timeLimit;

function updateTimer() {
    const minutes = Math.floor(timeRemaining / 60);
    const seconds = timeRemaining % 60;
    document.getElementById('timer').textContent = 
        String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
    
    if (timeRemaining <= 0) {
        alert('Time is up! The test will be submitted automatically.');
        document.getElementById('testForm').submit();
    } else if (timeRemaining <= 60) {
        document.getElementById('timer').classList.add('animate-pulse');
    }
    
    timeRemaining--;
}

<?php if (!$existingResponse && !empty($questions)): ?>
    setInterval(updateTimer, 1000);
    updateTimer();
<?php endif; ?>
</script>

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

