<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
$db = Database::getInstance();
$user = getCurrentUser();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$assessment = $db->get("SELECT * FROM assessments WHERE id = ? AND (is_published = 1 OR created_by = ?)", [$id, $user['id']]);
if (!$assessment) {
    header('Location: ' . APP_URL . '/lms/assessments.php');
    exit;
}

// Load questions
$questions = $db->getAll("SELECT * FROM assessment_questions WHERE assessment_id = ? ORDER BY sort_order ASC", [$id]);

// Handle submission
$submissionResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $answers = $_POST['answer'] ?? [];
    $totalPoints = 0;
    $earnedPoints = 0;
    $rawAnswers = [];

    foreach ($questions as $q) {
        $qid = (int)$q['id'];
        $totalPoints += (float)$q['points'];
        $given = $answers[$qid] ?? null;
        $rawAnswers[$qid] = $given;

        // auto-grade
        if ($q['question_type'] === 'multiple_choice' || $q['question_type'] === 'true_false') {
            // options stored as JSON, correct_answer stored (for MCQ may be index or value)
            $correct = $q['correct_answer'];
            if (is_array($given)) {
                // multiple answers (not common here)
                $isCorrect = in_array($correct, $given);
            } else {
                $isCorrect = trim((string)$given) === trim((string)$correct);
            }
            if ($isCorrect) $earnedPoints += (float)$q['points'];
        } elseif ($q['question_type'] === 'short_answer') {
            // simple exact match (case-insensitive)
            $correct = trim((string)$q['correct_answer']);
            if ($correct !== '' && strcasecmp(trim((string)$given), $correct) === 0) {
                $earnedPoints += (float)$q['points'];
            }
        } else {
            // essay/manual grading — leave score null
        }
    }

    $percentage = $totalPoints > 0 ? ($earnedPoints / $totalPoints) * 100 : 0;
    $passed = $percentage >= (float)$assessment['passing_score'];

    // Insert submission
    $db->query("INSERT INTO assessment_submissions (assessment_id, student_id, answers, score, max_score, percentage, passed, time_taken_minutes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", [$id, $user['id'], json_encode($rawAnswers), $earnedPoints, $totalPoints, $percentage, $passed ? 1 : 0, null]);

    $submissionResult = [
        'earned' => $earnedPoints,
        'total' => $totalPoints,
        'percentage' => round($percentage, 2),
        'passed' => $passed
    ];
}

$pageTitle = 'Take Assessment - ' . htmlspecialchars($assessment['title']);
include __DIR__ . '/includes/header.php';
?>

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header"><h5 class="m-0"><?php echo htmlspecialchars($assessment['title']); ?></h5></div>
            <div class="card-body">
                <?php if ($submissionResult): ?>
                    <div class="alert alert-info">
                        <strong>Result:</strong> <?php echo htmlspecialchars($submissionResult['earned']); ?> / <?php echo htmlspecialchars($submissionResult['total']); ?> points (<?php echo htmlspecialchars($submissionResult['percentage']); ?>%) - <?php echo $submissionResult['passed'] ? 'Passed' : 'Not Passed'; ?>
                    </div>
                    <a href="<?php echo APP_URL; ?>/lms/assessments.php" class="btn btn-outline-secondary">Back</a>
                <?php else: ?>
                    <?php if (empty($questions)): ?>
                        <p class="text-muted">No questions defined for this assessment.</p>
                        <a href="<?php echo APP_URL; ?>/lms/assessments.php" class="btn btn-outline-secondary">Back</a>
                    <?php else: ?>
                        <form method="post">
                            <?php foreach ($questions as $idx => $q): ?>
                                <div class="mb-4">
                                    <h6><?php echo ($idx+1) . '. ' . htmlspecialchars($q['question_text']); ?> <small class="text-muted">(<?php echo htmlspecialchars($q['question_type']); ?>, <?php echo htmlspecialchars($q['points']); ?> pts)</small></h6>

                                    <?php if ($q['question_type'] === 'multiple_choice'): $options = json_decode($q['options'], true) ?: []; ?>
                                        <?php foreach ($options as $optIndex => $opt): ?>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="answer[<?php echo (int)$q['id']; ?>]" id="q<?php echo (int)$q['id']; ?>_<?php echo $optIndex; ?>" value="<?php echo htmlspecialchars($opt); ?>" />
                                                <label class="form-check-label" for="q<?php echo (int)$q['id']; ?>_<?php echo $optIndex; ?>"><?php echo htmlspecialchars($opt); ?></label>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php elseif ($q['question_type'] === 'true_false'): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="answer[<?php echo (int)$q['id']; ?>]" id="q<?php echo (int)$q['id']; ?>_t" value="true" />
                                            <label class="form-check-label" for="q<?php echo (int)$q['id']; ?>_t">True</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="answer[<?php echo (int)$q['id']; ?>]" id="q<?php echo (int)$q['id']; ?>_f" value="false" />
                                            <label class="form-check-label" for="q<?php echo (int)$q['id']; ?>_f">False</label>
                                        </div>
                                    <?php elseif ($q['question_type'] === 'short_answer'): ?>
                                        <input class="form-control" type="text" name="answer[<?php echo (int)$q['id']; ?>]" />
                                    <?php else: /* essay */ ?>
                                        <textarea class="form-control" name="answer[<?php echo (int)$q['id']; ?>]"></textarea>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>

                            <button class="btn btn-primary">Submit</button>
                        </form>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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