<?php
session_start();
require('dbconnect.php'); // Database connection
require('fpdf/fpdf.php'); // FPDF library include

// Ensure user is logged in
if (!isset($_SESSION['USER_ID'])) {
    die("Please login to download your certificate.");
}

$user_id = $_SESSION['USER_ID'];

// Fetch user details including registration_date
$query = "SELECT full_name, registration_date FROM user_register WHERE id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    die("User not found.");
}

// Check if 31 days have passed since registration
$today = date("Y-m-d");
$registered_date = $user['registration_date'];
$eligible_date = date("Y-m-d", strtotime($registered_date . ' + 31 days'));

if ($today < $eligible_date) {
    die("You can download your certificate after 31 days from registration.");
}

// Generate Certificate
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 20);

// Set Background Image (If Needed)
$bg_image = "certificate_template.jpg"; // Make sure this file exists
if (file_exists($bg_image)) {
    $pdf->Image($bg_image, 0, 0, 210, 297); // A4 size background
}

// Title
$pdf->Cell(190, 20, 'Certificate of Completion', 0, 1, 'C');
$pdf->Ln(10);

// Awarded to
$pdf->SetFont('Arial', '', 16);
$pdf->Cell(190, 10, 'This is to certify that', 0, 1, 'C');
$pdf->Ln(5);

$pdf->SetFont('Arial', 'B', 22);
$pdf->Cell(190, 10, strtoupper($user['full_name']), 0, 1, 'C');
$pdf->Ln(5);

$pdf->SetFont('Arial', '', 14);
$pdf->Cell(190, 10, "Has successfully completed the course.", 0, 1, 'C');
$pdf->Ln(10);

// Date of Completion
$pdf->SetFont('Arial', '', 12);
$pdf->Cell(190, 10, 'Date of Completion: ' . $today, 0, 1, 'C');
$pdf->Ln(20);

// Signature
$pdf->Image('signature.png', 70, 200, 70); // Add signature image
$pdf->SetFont('Arial', 'I', 12);
$pdf->Cell(190, 10, 'Authorized Signatory', 0, 1, 'C');

// Output Certificate
$pdf->Output('D', 'Certificate.pdf'); // Force download

?>
