<?php
// view_result.php
session_start();
require_once 'config.php';
if (empty($_SESSION['student_id'])) { header('Location: student_login.php'); exit; }
$student_id = (int)$_SESSION['student_id'];
$attempt_id = (int)($_GET['attempt_id'] ?? 0);
if (!$attempt_id) { echo "Attempt not specified."; exit; }

// fetch attempt details
$stmt = $dbh->prepare("
    SELECT ea.*, ex.title, ex.total_marks, ex.subject_id, s.name as subject_name
    FROM exam_attempts ea 
    JOIN exams ex ON ex.id = ea.exam_id 
    LEFT JOIN Subjects s ON s.id = ex.subject_id 
    WHERE ea.id = :id AND ea.student_id = :sid 
    LIMIT 1
");
$stmt->execute([':id'=>$attempt_id, ':sid'=>$student_id]);
$attempt = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$attempt){ echo "Result not found."; exit; }

// fetch questions + answers (corrected)
$ansStmt = $dbh->prepare("
    SELECT q.id as question_id, q.question_text, q.type, q.options, q.correct_answer,
           sa.answer_text, sa.marked_score
    FROM exam_questions eq
    JOIN questions q ON q.id = eq.question_id
    LEFT JOIN student_answers sa 
        ON sa.question_id = q.id AND sa.student_id = :sid
    WHERE eq.exam_id = :exam_id
    ORDER BY eq.q_order
");
$ansStmt->execute([
    ':exam_id' => $attempt['exam_id'],
    ':sid' => $student_id
]);
$answers = $ansStmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Result - <?=htmlspecialchars($attempt['title'])?></title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
body{font-family:Inter,system-ui,Segoe UI,Roboto,Arial;margin:0;background:#f3f7fb;color:#0f172a}
.container{max-width:980px;margin:18px auto;padding:18px}
.card{background:#fff;padding:16px;border-radius:10px;box-shadow:0 6px 18px rgba(16,24,40,0.04);margin-bottom:12px}
.green{color:#16a34a;font-weight:700}
.red{color:#ef4444;font-weight:700}
.small{font-size:13px;color:#6b7280}
.qbox{padding:12px;border-radius:8px;border:1px solid #eef2f6;margin-bottom:12px}
.correct{background:#ecfdf5;border:1px solid #6ee7b7}
.incorrect{background:#fef2f2;border:1px solid #fca5a5}
</style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div style="display:flex;justify-content:space-between;align-items:center">
        <div>
          <h2 style="margin:0"><?=htmlspecialchars($attempt['title'])?></h2>
          <div class="small"><?=htmlspecialchars($attempt['subject_name'] ?? '')?> • Submitted: <?=htmlspecialchars($attempt['submitted_at'])?></div>
        </div>
        <div style="text-align:right">
          <div class="small">Time taken</div>
          <div style="font-size:18px;font-weight:700"><?=intval($attempt['time_taken_seconds'] / 60)?>m <?= $attempt['time_taken_seconds'] % 60 ?>s</div>
          <div style="margin-top:6px" class="<?=($attempt['score'] >= ($attempt['total_marks']/2) ? 'green' : 'red')?>">Score: <?=number_format($attempt['score'],2)?> </div>
        </div>
      </div>
    </div>

    <div class="card">
        <div class='text-center mt-10'>
      <a href='student_dashboard.php' 
         class='inline-block px-8 py-3 bg-blue-600 text-white rounded-xl text-lg font-semibold shadow-md hover:bg-blue-700 transition'>
        <h2>Back to Dashboard </h2>
      </a>
    </div>
      <h3 style="margin-top:0">Questions & Answers</h3>
      <?php foreach($answers as $i=>$a): 
        $studentAns = trim((string)$a['answer_text']);
        $correctAns = trim((string)$a['correct_answer']);
        $isCorrect = (strcasecmp($studentAns, $correctAns) === 0);
      ?>
        <div class="qbox <?= $studentAns==='' ? '' : ($isCorrect ? 'correct' : 'incorrect') ?>">
          <div style="font-weight:600"><?=($i+1)?>. <?=htmlspecialchars($a['question_text'])?></div>
          <div class="small" style="margin-top:6px">Type: <?=htmlspecialchars($a['type'])?></div>
          <div style="margin-top:8px">
            <strong>Your answer:</strong>
            <div style="margin-top:6px"><?= $studentAns !== '' ? nl2br(htmlspecialchars($studentAns)) : "<span class='small'>Not answered</span>" ?></div>
          </div>
          <?php if($a['type'] === 'objective'): 
            $opts = json_decode($a['options'] ?? '[]', true);
          ?>
            <div style="margin-top:6px" class="small">Options:</div>
            <ul>
              <?php if(is_array($opts)) foreach($opts as $k=>$opt): ?>
                <li><?=htmlspecialchars($opt)?></li>
              <?php endforeach; ?>
            </ul>
          <?php endif; ?>
          <div style="margin-top:8px">
            <strong>Correct answer:</strong> <?=htmlspecialchars($correctAns)?>
          </div>
          <div style="margin-top:8px">
            <strong>Marked score:</strong> <?= $a['marked_score'] === null ? '<span class="small">Pending</span>' : htmlspecialchars(number_format($a['marked_score'],2)) ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</body>
</html>
