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

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

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

if (!$testId) {
    header('Location: post-test-management.php');
    exit;
}

// Get test details
$stmt = $db->prepare("
    SELECT pt.*, a.title as activity_title, a.activity_date
    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) {
    header('Location: post-test-management.php');
    exit;
}

// 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();

// Get all responses with user info
$stmt = $db->prepare("
    SELECT
        ptr.*,
        ep.first_name,
        ep.last_name,
        u.email,
        ep.department
    FROM post_test_responses ptr
    JOIN users u ON ptr.user_id = u.user_id
    LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
    WHERE ptr.test_id = ?
    ORDER BY ptr.submitted_at DESC
");
$stmt->execute([$testId]);
$responses = $stmt->fetchAll();

// Calculate statistics
$totalResponses = count($responses);
$passedCount = count(array_filter($responses, fn($r) => $r['passed']));
$failedCount = $totalResponses - $passedCount;
$passRate = $totalResponses > 0 ? round(($passedCount / $totalResponses) * 100) : 0;

// Calculate average score
$totalScore = array_sum(array_column($responses, 'score'));
$avgScore = $totalResponses > 0 ? round($totalScore / $totalResponses, 1) : 0;
$avgPercentage = $totalResponses > 0 ? round(array_sum(array_column($responses, 'percentage')) / $totalResponses, 1) : 0;

// Question statistics
$questionStats = [];
foreach ($questions as $question) {
    $questionId = $question['question_id'];
    
    // Get all answers for this question
    $stmt = $db->prepare("
        SELECT
            ta.answer_text as answer,
            ta.is_correct,
            COUNT(*) as count
        FROM test_answers ta
        JOIN post_test_responses ptr ON ta.response_id = ptr.response_id
        WHERE ta.question_id = ? AND ptr.test_id = ? AND ta.test_type = 'post_test'
        GROUP BY ta.answer_text, ta.is_correct
    ");
    $stmt->execute([$questionId, $testId]);
    $answerStats = $stmt->fetchAll();
    
    $correctCount = 0;
    $totalAnswers = 0;
    foreach ($answerStats as $stat) {
        $totalAnswers += $stat['count'];
        if ($stat['is_correct']) {
            $correctCount += $stat['count'];
        }
    }
    
    $questionStats[$questionId] = [
        'correct_count' => $correctCount,
        'total_answers' => $totalAnswers,
        'correct_percentage' => $totalAnswers > 0 ? round(($correctCount / $totalAnswers) * 100) : 0,
        'answer_distribution' => $answerStats
    ];
}

// Export to Excel
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="post_test_results_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header row
    fputcsv($output, ['Name', 'Email', 'Department', 'Score', 'Percentage', 'Passed', 'Time Taken (min)', 'Submitted At']);
    
    // Data rows
    foreach ($responses as $response) {
        $timeTaken = $response['time_taken'] ? round($response['time_taken'] / 60, 1) : 'N/A';
        fputcsv($output, [
            $response['first_name'] . ' ' . $response['last_name'],
            $response['email'],
            $response['department'],
            $response['score'],
            $response['percentage'] . '%',
            $response['passed'] ? 'Yes' : 'No',
            $timeTaken,
            date('Y-m-d H:i', strtotime($response['submitted_at']))
        ]);
    }
    
    fclose($output);
    exit;
}

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 mb-4">
                <div class="flex items-center">
                    <a href="post-test-management.php" class="text-admin hover:text-admin-dark mr-4">
                        <i class="fas fa-arrow-left text-xl"></i>
                    </a>
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900 mb-2">
                            <i class="fas fa-chart-line text-admin mr-2"></i>Post-Test Results
                        </h1>
                        <p class="text-gray-600">
                            <?php echo htmlspecialchars($test['title']); ?> - 
                            <?php echo htmlspecialchars($test['activity_title']); ?>
                        </p>
                    </div>
                </div>
                <a href="?test_id=<?php echo $testId; ?>&export=excel" 
                   class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 transition font-semibold">
                    <i class="fas fa-file-excel mr-2"></i>Export to Excel
                </a>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-5 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-admin">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Total Responses</p>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $totalResponses; ?></h3>
                    </div>
                    <div class="bg-blue-100 p-4 rounded-full">
                        <i class="fas fa-users text-admin text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Passed</p>
                        <h3 class="text-3xl font-bold text-green-600 mt-2"><?php echo $passedCount; ?></h3>
                    </div>
                    <div class="bg-green-100 p-4 rounded-full">
                        <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Failed</p>
                        <h3 class="text-3xl font-bold text-red-600 mt-2"><?php echo $failedCount; ?></h3>
                    </div>
                    <div class="bg-red-100 p-4 rounded-full">
                        <i class="fas fa-times-circle text-red-600 text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Pass Rate</p>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $passRate; ?>%</h3>
                    </div>
                    <div class="bg-yellow-100 p-4 rounded-full">
                        <i class="fas fa-percentage text-yellow-600 text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-purple-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Avg Score</p>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $avgPercentage; ?>%</h3>
                    </div>
                    <div class="bg-purple-100 p-4 rounded-full">
                        <i class="fas fa-star text-purple-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pass/Fail Chart -->
        <?php if ($totalResponses > 0): ?>
            <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
                <h2 class="text-xl font-bold text-gray-900 mb-6">
                    <i class="fas fa-chart-pie text-admin mr-2"></i>Pass/Fail Distribution
                </h2>
                <div class="grid grid-cols-2 gap-6">
                    <div class="bg-green-50 border-2 border-green-500 rounded-lg p-6 text-center">
                        <div class="text-6xl font-bold text-green-600 mb-3"><?php echo $passedCount; ?></div>
                        <div class="text-lg text-gray-700 mb-3">Passed (<?php echo $passRate; ?>%)</div>
                        <div class="w-full bg-gray-200 rounded-full h-4">
                            <div class="bg-green-500 h-4 rounded-full transition-all duration-500" style="width: <?php echo $passRate; ?>%"></div>
                        </div>
                    </div>
                    <div class="bg-red-50 border-2 border-red-500 rounded-lg p-6 text-center">
                        <div class="text-6xl font-bold text-red-600 mb-3"><?php echo $failedCount; ?></div>
                        <div class="text-lg text-gray-700 mb-3">Failed (<?php echo 100 - $passRate; ?>%)</div>
                        <div class="w-full bg-gray-200 rounded-full h-4">
                            <div class="bg-red-500 h-4 rounded-full transition-all duration-500" style="width: <?php echo 100 - $passRate; ?>%"></div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Question Analysis -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 class="text-xl font-bold text-gray-900 mb-6">
                <i class="fas fa-question-circle text-admin mr-2"></i>Question Analysis
            </h2>
            <div class="space-y-4">
                <?php foreach ($questions as $index => $question): ?>
                    <?php $stats = $questionStats[$question['question_id']]; ?>
                    <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition">
                        <div class="flex items-start justify-between mb-3">
                            <div class="flex-1">
                                <h3 class="font-semibold text-gray-900 mb-2">
                                    <?php echo $index + 1; ?>. <?php echo htmlspecialchars($question['question_text']); ?>
                                </h3>
                                <span class="text-sm text-gray-500">
                                    <?php 
                                    $typeLabels = [
                                        'multiple_choice' => '📝 Multiple Choice',
                                        'true_false' => '✓ True/False',
                                        'essay' => '📄 Essay'
                                    ];
                                    echo $typeLabels[$question['question_type']];
                                    ?>
                                </span>
                            </div>
                            <div class="text-right ml-4">
                                <div class="text-2xl font-bold <?php echo $stats['correct_percentage'] >= 70 ? 'text-green-600' : ($stats['correct_percentage'] >= 50 ? 'text-yellow-600' : 'text-red-600'); ?>">
                                    <?php echo $stats['correct_percentage']; ?>%
                                </div>
                                <div class="text-xs text-gray-500">Correct</div>
                            </div>
                        </div>
                        
                        <!-- Progress Bar -->
                        <div class="w-full bg-gray-200 rounded-full h-3 mb-2">
                            <div class="h-3 rounded-full transition-all duration-500 <?php echo $stats['correct_percentage'] >= 70 ? 'bg-green-500' : ($stats['correct_percentage'] >= 50 ? 'bg-yellow-500' : 'bg-red-500'); ?>" 
                                 style="width: <?php echo $stats['correct_percentage']; ?>%"></div>
                        </div>
                        
                        <div class="text-sm text-gray-600">
                            <?php echo $stats['correct_count']; ?> out of <?php echo $stats['total_answers']; ?> answered correctly
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Individual Responses -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="px-6 py-4 bg-admin text-white">
                <h2 class="text-xl font-bold">
                    <i class="fas fa-list mr-2"></i>Individual Responses
                </h2>
            </div>
            <?php if (empty($responses)): ?>
                <div class="p-12 text-center">
                    <i class="fas fa-inbox text-gray-300 text-6xl mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">No Responses Yet</h3>
                    <p class="text-gray-600">No one has taken this post-test yet.</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Name</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Department</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Score</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Percentage</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Result</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Time Taken</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Submitted</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($responses as $response): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4">
                                        <div class="font-semibold text-gray-900">
                                            <?php echo htmlspecialchars($response['first_name'] . ' ' . $response['last_name']); ?>
                                        </div>
                                        <div class="text-xs text-gray-500"><?php echo htmlspecialchars($response['email']); ?></div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-700">
                                        <?php echo htmlspecialchars($response['department']); ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-lg font-bold text-gray-900">
                                            <?php echo $response['score']; ?>/<?php echo count($questions); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-lg font-bold <?php echo $response['percentage'] >= 70 ? 'text-green-600' : 'text-red-600'; ?>">
                                            <?php echo $response['percentage']; ?>%
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <?php if ($response['passed']): ?>
                                            <span class="px-3 py-1 rounded-full bg-green-100 text-green-800 font-semibold text-sm">
                                                <i class="fas fa-check-circle mr-1"></i>Passed
                                            </span>
                                        <?php else: ?>
                                            <span class="px-3 py-1 rounded-full bg-red-100 text-red-800 font-semibold text-sm">
                                                <i class="fas fa-times-circle mr-1"></i>Failed
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-700">
                                        <?php 
                                        if ($response['time_taken']) {
                                            $minutes = floor($response['time_taken'] / 60);
                                            $seconds = $response['time_taken'] % 60;
                                            echo sprintf('%d:%02d', $minutes, $seconds);
                                        } else {
                                            echo 'N/A';
                                        }
                                        ?>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-700">
                                        <?php echo date('M j, Y g:i A', strtotime($response['submitted_at'])); ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

