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

<?php
// Check if session already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../includes/db_connect.php';

// Set content type to JSON
header('Content-Type: application/json');

// Check if student is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    echo json_encode([
        'success' => false,
        'message' => 'Authentication required'
    ]);
    exit();
}

$userId = $_SESSION['user_id'];
$response = [
    'success' => false,
    'message' => 'Invalid request'
];

// Validate input
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enrollment_id'])) {
    $enrollment_id = intval($_POST['enrollment_id']);
    
    // Check if enrollment belongs to this student and is completed
    $check_query = "
        SELECT e.id, e.course_id, c.title as course_title, 
              CONCAT(u.first_name, ' ', u.last_name) as student_name,
              u.email as student_email,
              CONCAT(i.first_name, ' ', i.last_name) as instructor_name
        FROM enrollments e
        INNER JOIN courses c ON e.course_id = c.id
        INNER JOIN users u ON e.user_id = u.id
        LEFT JOIN users i ON c.instructor_id = i.id
        WHERE e.id = ? AND e.user_id = ? AND (e.status = 'completed' OR c.status = 'completed')
    ";
    
    $stmt = $conn->prepare($check_query);
    $stmt->bind_param("ii", $enrollment_id, $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $enrollment_data = $result->fetch_assoc();
        
        // Get institute information
        $school = [
            'site_name' => 'Popular Computer Institute',
            'site_address' => 'Bhimpura No. 1, Ballia, Uttar Pradesh 221716, India',
            'site_phone' => '+91 9984878446',
            'site_email' => '[email protected]',
            'site_logo' => 'assets/img/logo.png',
            'site_url' => 'https://pcib.in'
        ];
        
        try {
            $site_settings_query = "SELECT * FROM site_settings WHERE setting_key IN ('site_name', 'site_address', 'contact_phone', 'contact_email', 'site_logo', 'site_url')";
            $site_settings_result = $conn->query($site_settings_query);
            
            if ($site_settings_result && $site_settings_result->num_rows > 0) {
                while($row = $site_settings_result->fetch_assoc()) {
                    // Map site_settings keys to our school array keys
                    $key_mapping = [
                        'site_name' => 'site_name',
                        'site_address' => 'site_address',
                        'site_phone' => 'site_phone',
                        'site_email' => 'site_email',
                        'site_logo' => 'site_logo',
                        'site_url' => 'site_url'
                    ];
                    
                    if (isset($key_mapping[$row['setting_key']])) {
                        $school[$key_mapping[$row['setting_key']]] = $row['setting_value'];
                    }
                }
            }
        } catch (Exception $e) {
            // Silently handle the error - default values already set
            error_log("Settings table error: " . $e->getMessage());
        }
        // Generate certificate number
        $certificate_number = 'PCIB-' . date('Y') . '-' . $enrollment_id . '-' . mt_rand(1000, 9999);
        
        // Ensure the certificates directory exists
        $cert_dir = '../../uploads/certificates/';
        if (!file_exists($cert_dir)) {
            mkdir($cert_dir, 0777, true);
        }
        
        // Create a unique certificate filename
        $file_name = 'certificate_' . $userId . '_' . $enrollment_id . '_' . time() . '.pdf';
        $certificate_path = '../../uploads/certificates/' . $file_name;
        $full_path = '../../' . $certificate_path;
        
        // Generate certificate HTML content
        $certificate_html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Course Completion Certificate</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            color: #333;
            margin: 0;
            padding: 0;
        }
        .certificate-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            border: 15px solid #0d6efd;
            position: relative;
            background-color: #fff;
        }
        .logo {
            text-align: center;
            margin-bottom: 10px;
        }
        .logo img {
            max-height: 80px;
        }
        .certificate-header {
            text-align: center;
            margin-bottom: 20px;
        }
        .certificate-title {
            font-size: 28px;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 10px;
            color: #0d6efd;
        }
        .certificate-subtitle {
            font-size: 18px;
            margin-bottom: 10px;
        }
        .student-name {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin: 20px 0;
            color: #333;
        }
        .certificate-content {
            margin: 20px 0;
            text-align: center;
            font-size: 16px;
            line-height: 1.5;
        }
        .certificate-footer {
            display: flex;
            justify-content: space-between;
            margin-top: 40px;
        }
        .signature {
            text-align: center;
            width: 30%;
        }
        .signature-line {
            width: 100%;
            border-bottom: 1px solid #333;
            margin-bottom: 5px;
        }
        .certificate-number {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #666;
        }
        .certificate-date {
            text-align: right;
            margin-top: 10px;
            font-size: 14px;
        }
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 60px;
            color: rgba(13, 110, 253, 0.05);
            z-index: 0;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="certificate-container">
        <div class="watermark">' . htmlspecialchars($school['site_name']) . '</div>
        
        <div class="logo">
            <img src="' . $school['site_logo'] . '" alt="' . htmlspecialchars($school['site_name']) . ' Logo">
        </div>
        
        <div class="certificate-header">
            <div class="certificate-title">Certificate of Completion</div>
            <div class="certificate-subtitle">This is to certify that</div>
        </div>
        
        <div class="student-name">' . htmlspecialchars($enrollment_data['student_name']) . '</div>
        
        <div class="certificate-content">
            has successfully completed the course<br>
            <strong>"' . htmlspecialchars($enrollment_data['course_title']) . '"</strong><br>
            at ' . htmlspecialchars($school['site_name']) . '.
        </div>
        
        <div class="certificate-footer">
            <div class="signature">
                <div class="signature-line"></div>
                <div>Instructor</div>
                <div>' . htmlspecialchars($enrollment_data['instructor_name'] ?? 'Course Instructor') . '</div>
            </div>
            
            <div class="signature">
                <div class="signature-line"></div>
                <div>Date</div>
                <div>' . date('d F Y') . '</div>
            </div>
            
            <div class="signature">
                <div class="signature-line"></div>
                <div>Director</div>
                <div>' . htmlspecialchars($school['site_name']) . '</div>
            </div>
        </div>
        
        <div class="certificate-number">
            Certificate Number: ' . $certificate_number . '<br>
            Verify this certificate at: ' . htmlspecialchars($school['site_url'] ?? 'www.pcib.in') . '/verify
        </div>
        
        <div class="certificate-date">
            Issued on: ' . date('d F Y') . '
        </div>
    </div>
</body>
</html>';
        
        // Save the certificate file
        if (file_put_contents($full_path, $certificate_html)) {
            // Update the enrollment record
            $update_query = "
                UPDATE enrollments
                SET certificate_number = ?, certificate_path = ?, certificate_issue_date = NOW()
                WHERE id = ?
            ";
            
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("ssi", $certificate_number, $certificate_path, $enrollment_id);
            
            if ($stmt->execute()) {
                $response = [
                    'success' => true,
                    'message' => 'Certificate generated successfully!',
                    'certificate_path' => $certificate_path,
                    'certificate_number' => $certificate_number
                ];
            } else {
                $response = [
                    'success' => false,
                    'message' => 'Error updating enrollment record: ' . $stmt->error
                ];
            }
        } else {
            $response = [
                'success' => false,
                'message' => 'Error saving certificate file'
            ];
        }
    } else {
        $response = [
            'success' => false,
            'message' => 'Invalid enrollment or course not completed'
        ];
    }
} else {
    $response = [
        'success' => false,
        'message' => 'Missing enrollment ID'
    ];
}

// Return JSON response
echo json_encode($response);
?>