<?php
session_start();
require_once 'config/db.php';
require_once 'includes/header.php';

$track_id = (int)($_GET['track_id'] ?? 0);

$student_name = $_SESSION['student_name'] ?? 'Student';
$roll_number  = $_SESSION['roll_number'] ?? '';

/* Fetch next unanswered question */
$stmt = $pdo->prepare("
    SELECT q.*
    FROM practice_questions q
    WHERE q.track_id = ?
    AND q.id NOT IN (
        SELECT question_id FROM practice_attempts
        WHERE student_name = ? AND is_correct = 1
    )
    ORDER BY q.id ASC
    LIMIT 1
");
$stmt->execute([$track_id, $student_name]);
$question = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$question) {
    header("Location: track_complete.php?track_id=".$track_id);
    exit();
}

$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $selected = $_POST['answer'];

    $stmt = $pdo->prepare("
        SELECT * FROM practice_attempts
        WHERE student_name = ? AND question_id = ?
    ");
    $stmt->execute([$student_name, $question['id']]);
    $attempt = $stmt->fetch(PDO::FETCH_ASSOC);

    $attempt_count = $attempt ? $attempt['attempt_count'] + 1 : 1;

    $is_correct = ($selected === $question['correct_option']) ? 1 : 0;

    if ($attempt) {

    // If already correct, don't downgrade it
    if ($attempt['is_correct'] == 1) {
        $is_correct = 1;
    }

    $stmt = $pdo->prepare("
        UPDATE practice_attempts
        SET attempt_count = ?, is_correct = ?
        WHERE id = ?
    ");
    $stmt->execute([$attempt_count, $is_correct, $attempt['id']]);

}
 else {
        $stmt = $pdo->prepare("
            INSERT INTO practice_attempts
            (student_name, roll_number, track_id, question_id, attempt_count, is_correct)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$student_name, $roll_number, $track_id, $question['id'], $attempt_count, $is_correct]);
    }

    if ($is_correct) {
        $message = "<div class='success'>Well done! Let’s move to the next challenge.</div>";
    } else {
        $message = ($attempt_count == 1)
            ? "<div class='hint'>{$question['hint_1']}</div>"
            : "<div class='hint'>{$question['hint_2']}</div>";
    }
}
?>

<div class="challenge-wrapper">
    <h2>Python Basics – Practice Challenge</h2>

    <?php echo $message; ?>

    <div class="question-box">
        <p><strong><?php echo htmlspecialchars($question['question']); ?></strong></p>

        <form method="POST">
            <?php foreach (['a','b','c','d'] as $opt): ?>
                <label>
                    <input type="radio" name="answer" value="<?php echo $opt; ?>" required>
                    <?php echo htmlspecialchars($question['option_'.$opt]); ?>
                </label><br>
            <?php endforeach; ?>

            <button type="submit">Submit Answer</button>
        </form>
    </div>
</div>

</body>
</html>
