<?php
require_once 'db/config.php';
require_once 'includes/TCPDF-main/tcpdf.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die('Invalid certificate ID.');
}

$certificate_id = $_GET['id'];
$user_id = $_SESSION['user_id'];

$pdo = db();
$stmt = $pdo->prepare('
    SELECT
        c.id,
        c.certificate_type,
        c.issued_at,
        u.name as username,
        com.title as competition_title
    FROM certificates c
    JOIN users u ON c.user_id = u.id
    JOIN competitions com ON c.competition_id = com.id
    WHERE c.id = ? AND c.user_id = ?');
$stmt->execute([$certificate_id, $user_id]);
$certificate = $stmt->fetch();

if (!$certificate) {
    die('Certificate not found or you do not have permission to view it.');
}

// Create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('RS Learning Lab');
$pdf->SetTitle('Certificate of Achievement');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

$pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);

// Add a page
$pdf->AddPage();

// Add logo and title
$pdf->SetFont('helvetica', 'B', 20);
$pdf->Cell(0, 15, 'RS Learning Lab', 0, false, 'C', 0, '', 0, false, 'M', 'M');
$pdf->Image('assets/pasted-20251129-095357-cfd84971.png', 10, 10, 30, 0, 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false);
$pdf->Ln(20);


// Set background image
// NOTE: You might need to adjust the path to the image.
// $pdf->Image('assets/images/certificate_background.png', 0, 0, 210, 297, '', '', '', false, 300, '', false, false, 0);

// Set font
$pdf->SetFont('helvetica', 'B', 20);

// Title
$pdf->Cell(0, 15, 'Certificate of Achievement', 0, 1, 'C');
$pdf->Ln(10);

$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'This is to certify that', 0, 1, 'C');
$pdf->Ln(5);

$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 10, strtoupper($certificate['username']), 0, 1, 'C');
$pdf->Ln(5);

$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'has successfully completed the', 0, 1, 'C');
$pdf->Ln(5);

$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, $certificate['competition_title'], 0, 1, 'C');
$pdf->Ln(5);

if ($certificate['certificate_type'] === 'winner') {
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Cell(0, 10, 'and is a winner of the competition.', 0, 1, 'C');
    $pdf->Ln(5);
}

$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 10, 'Issued on: ' . date('M d, Y', strtotime($certificate['issued_at'])), 0, 1, 'C');

// Close and output PDF document
$pdf->Output('certificate.pdf', 'I');
