Path : /home/vishqocm/pcib.in/student/ajax/
File Upload :
Current File : //home/vishqocm/pcib.in/student/ajax/download_certificate_pdf.php

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

// Include necessary files
require_once '../../config.php';

// Check if student is logged in
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    header("HTTP/1.1 403 Forbidden");
    echo "Access denied";
    exit();
}

// Get certificate number from request
$certificate_number = $_POST['certificate_number'] ?? '';

if (empty($certificate_number)) {
    header("HTTP/1.1 400 Bad Request");
    echo "Certificate number is required";
    exit();
}

// Get the certificate from database
$query = "SELECT e.certificate_data, e.certificate_meta, 
                 CONCAT(u.first_name, ' ', u.last_name) AS student_name,
                 c.title AS course_title
          FROM enrollments e
          INNER JOIN users u ON e.user_id = u.id
          INNER JOIN courses c ON e.course_id = c.id
          WHERE e.certificate_number = ? AND e.user_id = ?";

$userId = $_SESSION['user_id'];
$stmt = $conn->prepare($query);
$stmt->bind_param("si", $certificate_number, $userId);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    $certificate = $result->fetch_assoc();
    
    // Get certificate HTML
    $html = $certificate['certificate_data'];
    
    if (empty($html)) {
        header("HTTP/1.1 404 Not Found");
        echo "Certificate content not found";
        exit();
    }
    
    // Clean up the HTML for PDF generation
    $html = preg_replace('/<div class="print-(button|actions)">.*?<\/div>/s', '', $html);
    
    try {
        // First check if DOMPDF is available via composer autoload
        if (file_exists('../../vendor/autoload.php')) {
            require_once '../../vendor/autoload.php';
            
            // Check if the DOMPDF classes exist
            if (class_exists('\\Dompdf\\Dompdf') && class_exists('\\Dompdf\\Options')) {
                // Use DOMPDF
                $options = new \Dompdf\Options();
                $options->set('isHtml5ParserEnabled', true);
                $options->set('isPhpEnabled', true);
                $options->set('isRemoteEnabled', true);
                $options->set('defaultFont', 'DejaVu Sans');
                
                // Initialize DOMPDF
                $dompdf = new \Dompdf\Dompdf($options);
                
                // Load HTML content
                $dompdf->loadHtml($html);
                
                // Set paper size and orientation
                $dompdf->setPaper('A4', 'portrait');
                
                // Render PDF
                $dompdf->render();
                
                // Generate unique filename
                $filename = 'certificate_' . $certificate_number . '.pdf';
                
                // Set headers
                header('Content-Type: application/pdf');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Cache-Control: max-age=0');
                
                // Output PDF
                echo $dompdf->output();
                exit();
            } else {
                throw new Exception("DOMPDF classes not found. Please install dompdf/dompdf via Composer.");
            }
        } else {
            throw new Exception("Vendor autoload.php not found. Please run 'composer install' in the root directory.");
        }
    } catch (Exception $e) {
        // Log the error
        error_log("PDF Generation Error: " . $e->getMessage());
        
        // FALLBACK: If PDF generation fails, return the HTML with instructions to print as PDF
        header('Content-Type: text/html');
        
        // Add print instructions
        $fallbackHTML = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Certificate - Print to PDF</title>
    <style>
        .alert {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border: 1px solid #f5c6cb;
            z-index: 9999;
            text-align: center;
        }
        .instructions {
            position: fixed;
            bottom: 20px;
            left: 0;
            right: 0;
            background-color: #cce5ff;
            color: #004085;
            padding: 15px;
            border: 1px solid #b8daff;
            z-index: 9999;
            text-align: center;
        }
        @media print {
            .alert, .instructions {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="alert">
        <p>PDF generation failed: ' . htmlspecialchars($e->getMessage()) . '</p>
    </div>
    <div class="instructions">
        <p><strong>Instructions:</strong> Please use your browser\'s print function (Ctrl+P or Cmd+P) and select "Save as PDF" to download your certificate.</p>
    </div>
    ' . $html . '
    <script>
        window.onload = function() {
            setTimeout(function() {
                document.querySelector(".alert").style.display = "none";
            }, 5000);
        };
    </script>
</body>
</html>';
        
        echo $fallbackHTML;
        exit();
    }
} else {
    header("HTTP/1.1 404 Not Found");
    echo "Certificate not found";
    exit();
}
?>