<?php
// Suppress warnings to prevent PDF corruption
error_reporting(0);
ini_set('display_errors', 0);

require_once 'includes/functions.php';

// Check if TCPDF exists (silent check now)
if (!file_exists('libs/tcpdf/tcpdf.php') || !file_exists('libs/phpqrcode/qrlib.php')) {
    die("Error: Libraries missing. Please run install_libs.php");
}

require_once 'libs/tcpdf/tcpdf.php';
require_once 'libs/phpqrcode/qrlib.php';

// Authorization logic
$cert = null;
if (isset($_GET['token'])) {
    $token = $_GET['token'];
    $stmt = $pdo->prepare("SELECT * FROM certificates WHERE token = ? AND status = 'active'");
    $stmt->execute([$token]);
    $cert = $stmt->fetch();
    if (!$cert) {
        die("Invalid or inactive certificate token.");
    }
} else {
    // Normal session-based access
    if (!isLoggedIn()) {
        die("Unauthorized access. Please login.");
    }

    if (!isset($_GET['id'])) {
        die("Invalid request. ID missing.");
    }

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

    // Fetch certificate
    $stmt = $pdo->prepare("SELECT * FROM certificates WHERE id = ?");
    $stmt->execute([$id]);
    $cert = $stmt->fetch();

    if (!$cert) {
        die("Certificate not found.");
    }

    // Check permissions (Admin can see all, users only their own)
    if ($role !== 'admin' && $cert['user_id'] != $user_id) {
        die("Unauthorized access to this certificate.");
    }
}

// Fetch Settings for Template
$settings = getSettings($pdo);
$template_path = $settings['template_path'];

if (!file_exists($template_path)) {
    die("Error: Certificate template not found. Please upload it in Admin Settings.");
}

// Load Coordinates
$coords = include 'config/coordinates.php';

// Initialize TCPDF
// A4 Portrait: 210 x 297 mm
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('CRS Delhi');
$pdf->SetTitle('Certificate - ' . $cert['registration_no']);
$pdf->SetMargins(0, 0, 0);
$pdf->SetAutoPageBreak(false, 0);
$pdf->AddPage();

// 1. Add Background Image
// 210mm width, 297mm height
$pdf->Image($template_path, 0, 0, 210, 297, '', '', '', false, 300, '', false, false, 0);

// 2. Set Font
// Use 'freeserif' because standard 'times' does not support Hindi (Unicode)
// freeserif is a Times-like font that supports UTF-8
$font_family = 'helvetica'; // Use core font for maximum compatibility on live servers
$pdf->SetTextColor(0, 0, 0); // Pure Black

// 3. Place Text
foreach ($coords as $key => $pos) {
    if ($key === 'qr') continue; // Skip QR for now
    
    // Get value from cert data
    $value = '';
    switch ($key) {
        case 'top_reg_no': $value = $cert['registration_no']; break;
        case 'reg_no': $value = $cert['registration_no']; break;
        case 'date_reg': $value = date('d-m-Y', strtotime($cert['date_of_registration'])); break;
        case 'name': $value = $cert['name']; break;
        case 'gender': $value = $cert['gender']; break;
        case 'dob': $value = date('d-m-Y', strtotime($cert['dob'])); break;
        case 'place': $value = $cert['place_of_birth']; break;
        case 'mother': $value = $cert['mother_name']; break;
        case 'father': $value = $cert['father_name']; break;
        case 'present_addr': $value = $cert['present_address']; break;
        case 'perm_addr': $value = $cert['permanent_address']; break;
        case 'issue_date': $value = date('d-m-y H:i:s', strtotime($cert['date_of_issue'])); break;
    }
    
    // Force Regular Style (Not Bold) - strict request
    $pdf->SetFont($font_family, '', $pos['size']);
    
    // 3. Place Text
    // Use Cell for single-line fields to prevent unwanted wrapping and Ensure vertical alignment
    // Use MultiCell ONLY for addresses as requested

    $is_address = in_array($key, ['present_addr', 'perm_addr']);
    
    // Set X,Y
    $pdf->SetXY($pos['x'], $pos['y']);
    
    if ($is_address) {
        // MultiCell(w, h, txt, border, align, fill, ln)
        // ln=1 means cursor moves to next line (but we reset XY next loop anyway)
        $pdf->MultiCell($pos['w'], 0, $value, 0, $pos['align'], false, 1);
    } else {
        // Cell(w, h, txt, border, ln, align, fill, link)
        // ln=0 means cursor stays to right, but we reset XY next loop
        $pdf->Cell($pos['w'], 0, $value, 0, 0, $pos['align'], false);
    }
}

// 4. Generate and Place QR Code
// Updated: Point QR directly to this generation script for instant opening
$qr_content = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . $_SERVER['PHP_SELF'] . "?token=" . $cert['token'];
$qr_base = 'uploads/temp_qr_' . $cert['id'];

if (isset($coords['qr'])) {
    $q = $coords['qr'];
    
    // Check if GD is installed for PNG
    if (function_exists('imagecreate')) {
        $qr_file = $qr_base . '.png';
        QRcode::png($qr_content, $qr_file, QR_ECLEVEL_L, 4);
        $pdf->Image($qr_file, $q['x'], $q['y'], $q['w'], $q['h']);
    } else {
        // Fallback to SVG if GD is missing (e.g. initial XAMPP setup)
        $qr_file = $qr_base . '.svg';
        QRcode::svg($qr_content, $qr_file, QR_ECLEVEL_L, 4);
        $pdf->ImageSVG($qr_file, $q['x'], $q['y'], $q['w'], $q['h']);
    }
    
    if (file_exists($qr_file)) {
        @unlink($qr_file); // cleanup
    }
}

// 5. Output
$action = isset($_GET['action']) && $_GET['action'] === 'download' ? 'D' : 'I';
$pdf->Output('Certificate_' . $cert['registration_no'] . '.pdf', $action);
?>
