<?php
ob_start();
require('../fpdf186/fpdf.php');
require_once '../models/db_connection.php';

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];

    // ✅ Query to get student and exam info
    $query = "
        SELECT 
            students.fullname,
            students.filename,
            student_exams.id AS exam_id,
            student_exams.course,
            student_exams.created_date
        FROM students
        JOIN student_exams ON students.student_id = student_exams.student
        WHERE students.student_id = $id
    ";

    $getstudent = mysqli_query($conn, $query);

    if (!$getstudent) {
        die('Query failed: ' . mysqli_error($conn));
    }

    $fetch = mysqli_fetch_array($getstudent);
    if (!$fetch) {
        die('No student found for ID ' . $id);
    }

    $pdf = new FPDF();
    $pdf->AddPage();

    // ✅ Background image (full-page certificate template)
    $pdf->Image('certificate_template.jpg', 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight());

    // ✅ Student Image
    $imagePath = "../uploads/" . $fetch['filename'];
    if (!empty($fetch['filename']) && file_exists($imagePath)) {
        $pdf->Image($imagePath, 155, 60, 28, 35);
    } else {
        $pdf->Image('no_image.jpg', 150, 60, 28, 35);
    }

    // ✅ Student Name (centered)
    $pdf->SetFont('Times', 'B', 22);
    $pdf->SetTextColor(255, 0, 0);
    $pdf->SetXY(10, 119);
    $pdf->Cell(0, 10, strtoupper($fetch['fullname']), 0, 1, 'C');

    // // ✅ Course Name (from student_exams.course)
    // $pdf->SetFont('Times', 'I', 22);
    // $pdf->SetTextColor(255, 0, 0);
    // $pdf->SetXY(10, 152);
    // $pdf->Cell(0, 10, strtoupper($fetch['course']), 0, 1, 'C');

    // ✅ Date of completion
    $pdf->SetFont('Arial', 'I', 12);
    $pdf->SetTextColor(0, 0, 255);
    $pdf->SetXY(0, 146);
    $fromdate = $_GET['from'] ?? '';
    $todate = $_GET['to'] ?? '';
    if ($fromdate && $todate) {
        $pdf->Cell(0, 10, '     ' . (new DateTime($fromdate))->format('d/m/Y') . '               ' . (new DateTime($todate))->format('d/m/Y'), 0, 1, 'C');
    }

    // ✅ Certificate Number — bottom center
    $pdf->SetFont('Arial', '', 10);
    $pdf->SetTextColor(0, 0, 0);
    $pageHeight = $pdf->GetPageHeight();
    $pdf->SetXY(138, $pageHeight - 43); // ~20mm from bottom
    $pdf->Cell(0, 10, '' . str_pad($fetch['exam_id'], 4, '0', STR_PAD_LEFT), 0, 1, 'C');

    ob_end_clean();
    $pdf->Output();
}
?>
