<?php
require_once __DIR__ . '/inc/bootstrap.php';
require_login('student');
include("config.php");
$conn->query("SET time_zone = '+05:30'");
date_default_timezone_set('Asia/Kolkata');

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/dompdf/vendor/autoload.php'; 
use Dompdf\Dompdf;
use Dompdf\Options;

// Check responses
if (!isset($_SESSION['responses']) || !isset($_SESSION['exam_id'])) {
    echo "Invalid access";
    exit;
}

$exam_id    = intval($_SESSION['exam_id']);
$responses  = $_SESSION['responses'];
$user       = current_user();
$attempt_id = $_SESSION['attempt_id'] ?? null;

// Get exam metadata
$stmt = $conn->prepare("SELECT a.started_at, e.duration_minutes 
                        FROM attempts a 
                        JOIN exams e ON a.exam_id = e.id 
                        WHERE a.id = ? AND a.user_id = ?");
$stmt->bind_param("ii", $attempt_id, $user['id']);
$stmt->execute();
$examMeta = $stmt->get_result()->fetch_assoc();
$stmt->close();

$startedAt   = $examMeta['started_at'];
$duration    = (int)$examMeta['duration_minutes'];
$endAt       = date("Y-m-d H:i:s", strtotime("$startedAt +$duration minutes"));
$completedAt = date("Y-m-d H:i:s");

// ✅ Use shuffled questions from session
$questions = $_SESSION['shuffled_questions'][$exam_id] ?? [];

// Safety fallback if session lost
if (empty($questions)) {
    $stmt = $conn->prepare("SELECT * FROM questions WHERE exam_id = ? ORDER BY id ASC");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $questions = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

$totalQuestions = count($questions);
$totalmarks = 0;
$score = 0;
$attempted = 0;
$summary = [];

foreach ($questions as $q) {
    $qid    = $q['id'];
    $qtext  = $q['question_text'];
    $qmarks = (int)$q['mark'];
    $totalmarks += $qmarks;

    // Correct answer
    $stmt = $conn->prepare("SELECT id, option_text FROM options WHERE question_id = ? AND is_correct = 1 LIMIT 1");
    $stmt->bind_param("i", $qid);
    $stmt->execute();
    $correctRow = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $correctId   = $correctRow['id'] ?? null;
    $correctText = $correctRow['option_text'] ?? '---';

    // Match response by question_id
    $userChoiceId = $responses[$qid] ?? null;
    $userAnswer   = '';

    if ($userChoiceId) {
        $attempted++;
        $stmt = $conn->prepare("SELECT option_text FROM options WHERE id = ? LIMIT 1");
        $stmt->bind_param("i", $userChoiceId);
        $stmt->execute();
        $optRow = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $userAnswer = $optRow['option_text'] ?? '';
    }

    $isCorrect = ($userChoiceId == $correctId);
    if ($isCorrect) {
        $score += $qmarks;
    }

    $summary[] = [
        'qtext'      => $qtext,
        'yourAnswer' => $userAnswer ?: 'Not Answered',
        'correct'    => $correctText,
        'status'     => $isCorrect ? 'Correct' : 'Wrong',
        'marks'      => $qmarks,
        'earned'     => $isCorrect ? $qmarks : 0
    ];
}

// Time taken
$timeTakenSeconds = strtotime($completedAt) - strtotime($startedAt);
$timeTaken = gmdate("H:i:s", $timeTakenSeconds);

// Generate PDF
$options = new Options();
$options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options);

$html = '<h2>Exam Summary</h2>';
$html .= '<p><strong>Student:</strong> ' . htmlspecialchars($user['name']) . '</p>';
$html .= '<p><strong>Total Questions:</strong> ' . $totalQuestions . '</p>';
$html .= '<p><strong>Attempted:</strong> ' . $attempted . '/' . $totalQuestions . '</p>';
$html .= '<p><strong>Score:</strong> ' . $score . '/' . $totalmarks . '</p>';
$html .= '<p><strong>Started:</strong> ' . $startedAt . '</p>';
$html .= '<p><strong>Completed:</strong> ' . $completedAt . '</p>';
$html .= '<p><strong>Deadline:</strong> ' . $endAt . '</p>';
$html .= '<p><strong>Time Taken:</strong> ' . $timeTaken . '</p>';

$html .= '<h3>Details</h3><table border="1" cellspacing="0" cellpadding="5">';
$html .= '<tr><th>Question</th><th>Your Answer</th><th>Correct</th><th>Status</th><th>Marks</th><th>Earned</th></tr>';
foreach ($summary as $row) {
    $html .= '<tr>
        <td>' . htmlspecialchars($row['qtext']) . '</td>
        <td>' . htmlspecialchars($row['yourAnswer']) . '</td>
        <td>' . htmlspecialchars($row['correct']) . '</td>
        <td>' . $row['status'] . '</td>
        <td>' . $row['marks'] . '</td>
        <td>' . $row['earned'] . '</td>
    </tr>';
}
$html .= '</table>';

$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Save PDF
$uploadDir = __DIR__ . "/uploads/pdfs/";
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
$pdfFileName = "exam_summary_user_" . $user['id'] . "_exam" . $exam_id . "_" . time() . ".pdf";
$pdfFilePath = $uploadDir . $pdfFileName;
file_put_contents($pdfFilePath, $dompdf->output());
$pdfDbPath = "uploads/pdfs/" . $pdfFileName;

// Update attempt in DB
if ($attempt_id) {
    $stmt = $conn->prepare("UPDATE attempts 
        SET end_at = ?, completed_at = ?, score = ?, total = ?, summary_pdf = ?
        WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ssiisii", $endAt, $completedAt, $score, $totalmarks, $pdfDbPath, $attempt_id, $user['id']);
    $stmt->execute();
    $stmt->close();
}

// Clear session
$_SESSION = [];
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
session_destroy();
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Exam Submitted</title><link rel="stylesheet" href="assets/style.css"></head>
<body>
  <nav class="nav">
    <div class="container">
      <div class="brand">📝 Exam Portal</div>
      <div>
        <a class="button" href="<?= $pdfDbPath ?>" target="_blank">📄 View PDF</a>
        <a class="button" href="login.php">Home</a>
      </div>
    </div>
  </nav>
  <main class="container">
    <section class="card">
      <h2>✅ Exam Submitted</h2>
      <p>Your exam summary has been saved.</p>
      <p><a href="<?= $pdfDbPath ?>" target="_blank">View your PDF summary</a></p>
    </section>
  </main>
</body>
</html>
