﻿﻿??????????????
﻿﻿??????????????
<?php
session_start();
require_once "session.php";
require_once "connection.php";

require_once __DIR__ . "/vendor/autoload.php";  // mPDF + PHPMailer

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if (!isset($_GET['attempt_id']) || intval($_GET['attempt_id']) <= 0) {
    die("Invalid attempt ID.");
}

$attempt_id = intval($_GET['attempt_id']);

/* -------------------------------
   Fetch Student & Attempt Details
----------------------------------*/
$q = $pdo->prepare("
    SELECT 
        sa.id AS attempt_id,
        sa.started_at,
        sa.submitted_at,
        sa.total_obtained,
        sa.total_possible,
        sa.status,
        
        s.id AS student_id,
        s.student_name,
        s.admission_no,
        s.course,
        s.email,

        a.title AS assignment_title,
        a.total_marks
    FROM student_attempts sa
    LEFT JOIN students s ON sa.student_id = s.id
    LEFT JOIN assignments a ON sa.assignment_id = a.id
    WHERE sa.id = ?
");
$q->execute([$attempt_id]);
$attempt = $q->fetch(PDO::FETCH_ASSOC);

if (!$attempt) {
    die("Attempt not found.");
}

$student_email = $attempt['email'];

if (empty($student_email)) {
    die("No email found for this student.");
}

/* -------------------------------
   Fetch breakdown
----------------------------------*/
$q2 = $pdo->prepare("
SELECT 
    q.question_text,
    q.weight,
    aa.selected_option_id,
    aa.is_correct,
    aa.obtained_marks,
    o.option_text AS chosen_option
FROM attempt_answers aa
LEFT JOIN questions q ON aa.question_id = q.id
LEFT JOIN options o ON aa.selected_option_id = o.id
WHERE aa.attempt_id = ?
ORDER BY q.question_order ASC
");
$q2->execute([$attempt_id]);
$answers = $q2->fetchAll(PDO::FETCH_ASSOC);

/* -------------------------------
   Build PDF (same style as before)
----------------------------------*/

$percentage = ($attempt['total_possible'] > 0)
              ? round(($attempt['total_obtained'] / $attempt['total_possible']) * 100, 2)
              : 0;

$status_badge = ($attempt['status'] == 'submitted') ? "Completed" : "Pending";

$logo_url = "../images/logo-wide.png";

$html = "
<h2 style='text-align:center;'>Assignment Result Report</h2>
<h3 style='text-align:center;'>{$attempt['assignment_title']}</h3>

<p><b>Student:</b> {$attempt['student_name']}<br>
<b>Admission No:</b> {$attempt['admission_no']}<br>
<b>Course:</b> {$attempt['course']}</p>

<p><b>Total Marks:</b> {$attempt['total_possible']}<br>
<b>Obtained:</b> {$attempt['total_obtained']}<br>
<b>Percentage:</b> {$percentage}%<br>
<b>Status:</b> {$status_badge}</p>

<h3>Question Breakdown:</h3>
<table border='1' cellspacing='0' cellpadding='6' width='100%'>
<tr>
<th>#</th>
<th>Question</th>
<th>Selected Option</th>
<th>Marks</th>
<th>Correct?</th>
</tr>
";

$i = 1;
foreach ($answers as $a) {
    $correct_text = $a['is_correct'] ? "✔ Correct" : "✘ Wrong";
    $color = $a['is_correct'] ? "green" : "red";
    $chosen = $a['chosen_option'] ?? "<i>Not Answered</i>";

    $html .= "
    <tr>
        <td>$i</td>
        <td>{$a['question_text']}</td>
        <td>{$chosen}</td>
        <td>{$a['obtained_marks']} / {$a['weight']}</td>
        <td style='color:$color; font-weight:bold;'>$correct_text</td>
    </tr>";
    $i++;
}

$html .= "</table>";

/* -------------------------------
   Generate PDF in Memory
----------------------------------*/
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);

// Save PDF temporarily
$pdf_file = __DIR__ . "/temp_report_$attempt_id.pdf";
$mpdf->Output($pdf_file, "F");

/* -------------------------------
   Send Email
----------------------------------*/

$mail = new PHPMailer(true);

try {
    // SMTP SETTINGS ---- Edit this section as per your SMTP ----
    $mail->isSMTP();
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPAuth = true;
    $mail->Username = "yourgmail@gmail.com";
    $mail->Password = "YOUR_APP_PASSWORD";  // Use Google App Password
    $mail->SMTPSecure = "tls";
    $mail->Port = 587;

    $mail->setFrom("yourgmail@gmail.com", "Institute Admin");
    $mail->addAddress($student_email, $attempt['student_name']);

    $mail->Subject = "Your Assignment Result – {$attempt['assignment_title']}";
    $mail->Body = "Dear {$attempt['student_name']},\n\nYour assignment result is attached.\n\nRegards,\nInstitute Admin";
    $mail->addAttachment($pdf_file);

    $mail->send();

    unlink($pdf_file);

    echo "<h3>Email sent successfully to <b>$student_email</b></h3>";

} catch (Exception $e) {
    echo "Email error: " . $mail->ErrorInfo;
}
?>
