<?php
require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'employee') {
    header("Location: ../login.php");
    exit();
}

$quizId = $_GET['id'] ?? 0;
$quizzes = readJson('quizzes');
$questions = readJson('questions');
$currentQuiz = null;

foreach ($quizzes as $quiz) {
    if ($quiz['id'] == $quizId) {
        $currentQuiz = $quiz;
        break;
    }
}

if (!$currentQuiz) {
    header("Location: dashboard.php");
    exit();
}

// Check if user already took this quiz
$results = readJson('results');
foreach ($results as $result) {
    if ($result['quiz_id'] == $quizId && $result['user_id'] == $_SESSION['user_id']) {
        header("Location: dashboard.php?msg=already_taken");
        exit();
    }
}

$quizQuestions = array_values(array_filter($questions, function($q) use ($quizId) {
    return $q['quiz_id'] == $quizId;
}));

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $score = 0;
    foreach ($quizQuestions as $question) {
        $userAnswer = $_POST['q' . $question['id']] ?? '';
        if ($userAnswer == $question['correct_answer']) {
            $score++;
        }
    }
    
    $percentage = ($score / count($quizQuestions)) * 100;
    $passed = $percentage >= ($currentQuiz['passing_score'] ?? 70);
    
    $results = readJson('results');
    $results[] = [
        'id' => getNextId('results'),
        'quiz_id' => $quizId,
        'user_id' => $_SESSION['user_id'],
        'score' => $score,
        'total' => count($quizQuestions),
        'percentage' => $percentage,
        'passed' => $passed,
        'completed_at' => date('Y-m-d H:i:s')
    ];
    writeJson('results', $results);
    
    $message = "You scored $score out of " . count($quizQuestions) . " (" . round($percentage) . "%)";
    $message .= $passed ? " - ✅ PASSED!" : " - ❌ FAILED. Passing score: " . ($currentQuiz['passing_score'] ?? 70) . "%";
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Quiz Results</title>
        <style>
            body { font-family: Arial; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f5f5f5; }
            .result-box { background: white; padding: 40px; border-radius: 10px; text-align: center; max-width: 90%; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            .btn { display: inline-block; padding: 12px 24px; background: #667eea; color: white; text-decoration: none; border-radius: 5px; margin-top: 20px; }
            @media (max-width: 600px) { .result-box { padding: 25px; } .btn { padding: 10px 20px; } }
        </style>
    </head>
    <body>
        <div class="result-box">
            <h2>Quiz Complete!</h2>
            <p style="font-size: 20px; margin: 20px 0;"><?php echo $message; ?></p>
            <a href="dashboard.php" class="btn">Back to Dashboard</a>
        </div>
    </body>
    </html>
    <?php
    exit();
}

// Check if there are questions
if (empty($quizQuestions)) {
    ?>
    <!DOCTYPE html>
    <html>
    <head><title>Quiz Error</title></head>
    <body style="font-family: Arial; text-align: center; padding: 50px;">
        <h2>⚠️ Quiz Error</h2>
        <p>This quiz has no questions yet. Please contact the administrator.</p>
        <a href="dashboard.php">Back to Dashboard</a>
    </body>
    </html>
    <?php
    exit();
}
?>
<?php include('../includes/header.php'); ?>
<div class="sidebar">
    <h3>👤 Employee Menu</h3>
    <a href="dashboard.php" class="btn" style="display: block;">🏠 Dashboard</a>
    <a href="view_memos.php" class="btn" style="display: block;">📝 Memos</a>
    <a href="take_quiz.php" class="btn" style="display: block;">📚 Take Quiz</a>
    <a href="safety_report.php" class="btn" style="display: block;">⚠️ Safety Report</a>
    <a href="profile.php" class="btn" style="display: block;">👤 Profile</a>
</div>
<div class="content">
    <h2><?php echo htmlspecialchars($currentQuiz['title']); ?></h2>
    <p><?php echo htmlspecialchars($currentQuiz['description'] ?? ''); ?></p>
    <p><strong>Passing Score:</strong> <?php echo $currentQuiz['passing_score'] ?? 70; ?>%</p>
    <p><strong>Questions:</strong> <?php echo count($quizQuestions); ?></p>
    
    <form method="POST">
        <?php foreach($quizQuestions as $index => $question): ?>
            <div class="card" style="margin-bottom: 20px;">
                <h4>Question <?php echo $index + 1; ?>: <?php echo htmlspecialchars($question['question']); ?></h4>
                <label style="display: block; margin: 10px 0;">
                    <input type="radio" name="q<?php echo $question['id']; ?>" value="A" required> 
                    A) <?php echo htmlspecialchars($question['option_a']); ?>
                </label>
                <label style="display: block; margin: 10px 0;">
                    <input type="radio" name="q<?php echo $question['id']; ?>" value="B"> 
                    B) <?php echo htmlspecialchars($question['option_b']); ?>
                </label>
                <label style="display: block; margin: 10px 0;">
                    <input type="radio" name="q<?php echo $question['id']; ?>" value="C"> 
                    C) <?php echo htmlspecialchars($question['option_c']); ?>
                </label>
                <label style="display: block; margin: 10px 0;">
                    <input type="radio" name="q<?php echo $question['id']; ?>" value="D"> 
                    D) <?php echo htmlspecialchars($question['option_d']); ?>
                </label>
            </div>
        <?php endforeach; ?>
        <button type="submit" class="btn btn-success" style="width: 100%; padding: 15px;">Submit Quiz</button>
    </form>
</div>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>