<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

require "../user/db.php";

// Get quiz ID from GET
$quiz_id = isset($_GET['quiz_id']) ? (int)$_GET['quiz_id'] : 0;

// Fetch quiz info
$quiz_res = $conn->prepare("SELECT * FROM quizzes WHERE id=?");
$quiz_res->bind_param("i", $quiz_id);
$quiz_res->execute();
$quiz_result = $quiz_res->get_result();
$quiz = $quiz_result->fetch_assoc();
if(!$quiz){
    die("Quiz not found");
}

// Fetch questions for the quiz
$questions_res = $conn->prepare("SELECT * FROM quiz_questions WHERE quiz_id=?");
$questions_res->bind_param("i", $quiz_id);
$questions_res->execute();
$questions_result = $questions_res->get_result();
$questions = [];
while($q = $questions_result->fetch_assoc()){
    $questions[$q['id']] = $q;
}

// Handle grading submission
if(isset($_POST['grade_submission'])){
    $submission_id = (int)$_POST['submission_id'];
    $score = (int)$_POST['score'];

    $stmt = $conn->prepare("UPDATE quiz_submissions SET score=? WHERE id=?");
    $stmt->bind_param("ii", $score, $submission_id);
    if($stmt->execute()){
        $success = "Score updated successfully!";
    } else {
        $error = "Error: " . $stmt->error;
    }
}

// Fetch all submissions for this quiz
$subs_res = $conn->prepare("
    SELECT s.*, u.fullname as student_name 
    FROM quiz_submissions s
    JOIN users u ON u.user_id = s.id
    WHERE s.quiz_id=?
    ORDER BY s.submitted_at DESC
");

$subs_res->bind_param("i", $quiz_id);
$subs_res->execute();
$subs_result = $subs_res->get_result();
$submissions = [];
while($sub = $subs_result->fetch_assoc()){
    $submissions[] = $sub;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Quiz Submissions</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{font-family:Segoe UI,sans-serif;margin:0;padding:0;background:#f4f6f9;}
.container{padding:20px;}
h1,h2{color:#1e293b;}
table{width:100%;border-collapse:collapse;margin-bottom:30px;}
th,td{border:1px solid #cbd5e1;padding:10px;text-align:left;}
th{background:#e2e8f0;}
.success{color:green;}
.error{color:red;}
.btn{padding:8px 15px;border:none;background:#2563eb;color:white;border-radius:5px;cursor:pointer;}
.btn:hover{background:#1d4ed8;}
textarea,input[type=number]{width:100%;padding:8px;border:1px solid #cbd5e1;border-radius:5px;}
</style>
</head>
<body>
<div class="container">
    <h1>Quiz: <?= htmlspecialchars($quiz['title']) ?></h1>

    <?php if(isset($success)) echo "<p class='success'>$success</p>"; ?>
    <?php if(isset($error)) echo "<p class='error'>$error</p>"; ?>

    <?php if(count($submissions)===0): ?>
        <p>No submissions yet.</p>
    <?php else: ?>
        <?php foreach($submissions as $sub): ?>
            <div style="background:#fff;padding:15px;border-radius:8px;margin-bottom:20px;box-shadow:0 2px 5px rgba(0,0,0,0.1);">
                <h2>Student: <?= htmlspecialchars($sub['student_name']) ?></h2>
                <p><strong>Submitted At:</strong> <?= htmlspecialchars($sub['submitted_at']) ?></p>
                <form method="POST">
                    <input type="hidden" name="submission_id" value="<?= $sub['id'] ?>">
                    <table>
                        <tr>
                            <th>Question</th>
                            <th>Answer</th>
                        </tr>
                        <?php
                        $answers = json_decode($sub['answers'], true) ?? [];
                        foreach($answers as $qid => $ans):
                            if(isset($questions[$qid])):
                        ?>
                            <tr>
                                <td><?= htmlspecialchars($questions[$qid]['question_text']) ?></td>
                                <td><?= is_array($ans) ? htmlspecialchars(implode(", ", $ans)) : htmlspecialchars($ans) ?></td>
                            </tr>
                        <?php
                            endif;
                        endforeach;
                        ?>
                        <tr>
                            <td><strong>Score</strong></td>
                            <td>
                                <input type="number" name="score" value="<?= htmlspecialchars($sub['score']??0) ?>" min="0" max="<?= $quiz['total_marks'] ?>" required>
                            </td>
                        </tr>
                    </table>
                    <button class="btn" name="grade_submission">Update Score</button>
                </form>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
</body>
</html>
