<?php
// Start output buffering
ob_start();

// Change directory and start session
chdir('../');
session_start();

// Include required files
require_once('public/connection.php');
require_once('tcpdf/tcpdf.php');

// Ensure student is logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: ../index.php");
    exit;
}

$student_id = $_SESSION['student_id'];

// Fetch student details using prepared statement
$stmt = $conn->prepare("
    SELECT firstname, lastname, othername, reg_number, class 
    FROM students 
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    die("Error: Student not found.");
}

// Fetch exam results using prepared statement
$stmt = $conn->prepare("
    SELECT r.*, s.subjects AS subject_name
    FROM exam_group_results r
    JOIN school_subjects s ON r.subject = s.subjects
    WHERE r.student_id = ?
    ORDER BY r.session DESC
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$query = $stmt->get_result();

// Initialize PDF (portrait orientation)
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('My Exam Results');
$pdf->SetMargins(15, 15, 15);
$pdf->SetAutoPageBreak(true, 15);
$pdf->SetFont('helvetica', '', 10);
$pdf->AddPage();

// Title
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 10, 'Student Exam Results', 0, 1, 'C');
$pdf->Ln(8);

// Student Details Table
$fullname = htmlspecialchars($student['lastname'] . ' ' . $student['firstname'] . ' ' . $student['othername']);
$regno = htmlspecialchars($student['reg_number']);
$class = htmlspecialchars($student['class']);

// Calculate page width (A4 width = 210mm, left + right margins = 30mm, usable width = 180mm)
$page_width = 180;
$col_width = $page_width / 3; // 60mm per column for 3 columns

// Draw student details table header
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell($col_width, 8, '' . $fullname, 1, 0, 'L');
$pdf->Cell($col_width, 8, '' . $regno, 1, 0, 'L');
$pdf->Cell($col_width, 8, '' . $class, 1, 1, 'L'); // ln=1 to move to next line
$pdf->Ln(8);

// Results Table
// Define column widths (total 180mm, matching previous percentages: 7%, 25%, 10%, 15%, 11%, 11%, 11%, 10%)
$col_widths = [
    7  => 0.07 * $page_width, // 12.6mm
    25 => 0.25 * $page_width, // 45mm
    10 => 0.10 * $page_width, // 18mm
    15 => 0.15 * $page_width, // 27mm
    11 => 0.11 * $page_width, // 19.8mm
    10 => 0.10 * $page_width, // 18mm
];

// Header
$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetFillColor(242, 242, 242); // Light gray background (#f2f2f2)
$pdf->Cell($col_widths[7], 8, '#', 1, 0, 'C', true);
$pdf->Cell($col_widths[25], 8, 'Subject', 1, 0, 'L', true);
$pdf->Cell($col_widths[10], 8, 'Term', 1, 0, 'C', true);
$pdf->Cell($col_widths[15], 8, 'Session', 1, 0, 'C', true);
$pdf->Cell($col_widths[11], 8, 'Objectives', 1, 0, 'C', true);
$pdf->Cell($col_widths[11], 8, 'Theory', 1, 0, 'C', true);
$pdf->Cell($col_widths[11], 8, 'Total', 1, 0, 'C', true);
$pdf->Cell($col_widths[10], 8, 'Status', 1, 1, 'C', true);

// Data rows
$pdf->SetFont('helvetica', '', 10);
if ($query && $query->num_rows > 0) {
    $sn = 1;
    while ($row = $query->fetch_assoc()) {
        $subject_name = htmlspecialchars($row['subject_name']);
        $term = htmlspecialchars($row['term']);
        $session = htmlspecialchars($row['session']);
        $mcq_score = htmlspecialchars($row['mcq_score'] ?? 0);
        $theory_score = htmlspecialchars($row['theory_score'] ?? 0);
        $total = htmlspecialchars($row['total'] ?? 0);
        $status = htmlspecialchars($row['status'] ?? '-');

        $pdf->Cell($col_widths[7], 8, $sn, 1, 0, 'C');
        $pdf->Cell($col_widths[25], 8, $subject_name, 1, 0, 'L');
        $pdf->Cell($col_widths[10], 8, $term, 1, 0, 'C');
        $pdf->Cell($col_widths[15], 8, $session, 1, 0, 'C');
        $pdf->Cell($col_widths[11], 8, $mcq_score, 1, 0, 'C');
        $pdf->Cell($col_widths[11], 8, $theory_score, 1, 0, 'C');
        $pdf->SetFont('helvetica', 'B', 10); // Bold for Total
        $pdf->Cell($col_widths[11], 8, $total, 1, 0, 'C');
        $pdf->SetFont('helvetica', '', 10);
        $pdf->Cell($col_widths[10], 8, $status, 1, 1, 'C');
        $sn++;
    }
} else {
    // No results
    $pdf->Cell($page_width, 8, 'No results found.', 1, 1, 'C');
}

$stmt->close();

// Clean output buffer and output PDF
ob_end_clean();
$pdf->Output('my_results.pdf', 'I');
exit;
?>