<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Certificate System - Gateway Polytechnic Saapade</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
    @page { size: A4; margin: 0; }
    body { 
        font-family: "Times New Roman", serif; 
        background: #f5f9ff; 
        margin: 0; 
        padding: 0;
    }
    .navbar {
        background: linear-gradient(135deg, #5461ebff, #6d7cf0ff);
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .navbar-brand {
        font-weight: bold;
    }
    .logo {
        height: 40px;
        margin-right: 10px;
    }
    .mlogo {
        height: 100px;
        margin-right: 10px;
    }
    .certificate { 
        border: 2px solid #ffffffff; 
        background: white; 
        width: 210mm; 
        height: 297mm; 
        padding: 20mm;
        box-sizing: border-box; 
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); 
        text-align: center; 
        margin: 20px auto;
        position: relative;
        overflow: hidden;
    }
    .certificate h1 { 
        font-size: 28px; 
        margin: 0 0 10px 0; 
        font-weight: bold;
    }
    .pos { 
        position: relative; 
        width: 100%; 
        height: 150px;
        margin-bottom: 15px; 
    }
    .qr { 
        position: absolute; 
        top: 10px;
        left: 0; 
        width: 120px; 
        height: 120px; 
    }
    .qr img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .sap { 
        position: absolute; 
        top: 15px;
        left: 48%; 
        transform: translateX(-50%); 
        width: 120px;
        height: 120px; 
    }
    .certificate-number {
        position: absolute;
        top: 50%;
        right: 140px;
        transform: translateY(-50%);
        font-weight: 900;
        font-size: 18px;
        color: #000000ff;
    }
    .passport { 
        position: absolute; 
        top: 10px;
        right: 0; 
        width: 120px; 
        height: 120px; 
    }
    .passport img {
        width: 110%;
        height: 150%;
        object-fit: cover;
    }
    .certificate h2 { 
        font-style: italic; 
        margin: 15px 0;
        font-size: 20px;
    }
    .content { 
        margin: 20px 0;
        font-size: 16px; 
        line-height: 1.6; 
        text-align: justify; 
        min-height: 200px;
    }
    .student-name-bold {
        font-weight: bold;
        font-size: 22px;
        text-align: center;
        display: block;
        margin: 8px 0;
        padding: 8px;
        border-bottom: 1px solid #000;
        width: 80%;
        margin-left: auto;
        margin-right: auto;
    }
    .program-bold {
        font-weight: bold;
        font-size: 18px;
        text-align: center;
        display: block;
        margin: 8px 0;
        padding: 8px;
        border-bottom: 1px solid #000;
        width: 70%;
        margin-left: auto;
        margin-right: auto;
    }
    .certificate-type-display {
        font-weight: bold;
        font-size: 18px;
        text-align: center;
        display: block;
        margin: 8mm 0 5px 0;
    }
    .in-text {
        font-style: italic;
        text-align: center;
        display: block;
        margin: 5px 0 15mm 0;
        font-size: 16px;
    }
    .fields { 
        position: relative; 
        width: 100%; 
        height: 40px;
        font-size: 16px; 
        font-style: italic; 
        margin: 15px 0;
    }
    .matric { 
        position: absolute; 
        top: 0; 
        left: 0; 
        width: 300px;
        height: 20px; 
    }
    .inner { 
        margin-left: 0;
    }
    .grade { 
        position: absolute; 
        top: 0; 
        right: 0; 
        width: 200px;
        height: 20px; 
    }
    .space { 
        padding-left: 150px;
    }
    .seal { 
        margin: 30px auto;
        width: 100px;
        height: 100px; 
        border-radius: 50%;
        display: flex; 
        align-items: center; 
        justify-content: center; 
        font-size: 10px;
        text-align: center; 
        line-height: 1.2; 
        overflow: hidden;
    }
    .seal img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    /* --- UPDATED CERTIFICATE FOOTER AND SIGNATURE CSS --- */
    .certificate-footer {
        position: relative;
        margin-top: 40px;
        width: 100%;
        page-break-inside: avoid !important;
    }

    .signatures { 
        display: flex; 
        justify-content: space-between; 
        align-items: flex-start;
        margin-bottom: 60px;
        position: relative;
        width: 100%;
    }

    /* Generic signature box styling */
    .signature-box {
        text-align: center;
        position: relative;
        min-height: 80px; 
    }

    /* Date/Signature/Text content on or above the line */
    .signature-box .line-content {
        display: block;
        font-weight: bold; 
        margin-bottom: 5px; /* Space between content and line */
    }

    /* The actual line placeholder */
    .signature-box .signature-line-placeholder {
        display: block;
        width: 180px; 
        height: 1px;
        background-color: #000;
        margin: 5px auto; /* Reduced margin to pull line up closer to content */
    }
    
    /* Label (Date, Registrar, Rector) positioning */
    .signature-box > span:last-child {
        display: block;
        margin-top: 5px; /* Space between the line and the label */
    }

    /* Signature Box Dimensions */
    .sign-box-date { 
        width: 45%; 
    }

    .sign-box-registrar { 
        width: 45%; 
    }

    .sign-box-rector { 
        position: absolute;
        bottom: -90px; /* Moved further down as requested */
        left: 50%;
        transform: translateX(-50%);
        width: 30%; 
    }
    /* END UPDATED SIGNATURE CSS */
    
    .student-list {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-top: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .student-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.3s;
    }
    .student-card:hover {
        background-color: #f8f9fa;
        border-color: #007bff;
    }
    .student-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid #1a237e;
    }
    .settings-panel {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .loading-spinner {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 1000;
    }
    .stats-panel {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin: 20px 0;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .stat-card {
        text-align: center;
        padding: 20px;
        border-radius: 8px;
        margin: 10px 0;
    }
    .stat-printed {
        background: #e8f5e8;
        border-left: 4px solid #28a745;
    }
    .stat-pending {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
    }
    .stat-error {
        background: #f8d7da;
        border-left: 4px solid #dc3545;
    }
    .print-progress {
        margin: 20px 0;
    }

    @media print {
        body { 
            background: none; 
            box-shadow: none; 
            padding: 0;
            margin: 0;
            -webkit-print-color-adjust: exact;
            color-adjust: exact;
        }
        .certificate { 
            box-shadow: none; 
            margin: 0;
            border: 2px solid #000;
            padding: 20mm;
            page-break-inside: avoid !important;
            width: 210mm;
            height: 297mm;
        }
        .no-print {
            display: none !important;
        }
        .certificate-footer {
            position: relative;
            bottom: auto;
            left: auto;
            right: auto;
            margin-top: 40px;
            page-break-inside: avoid !important;
            width: 100%;
        }
        .signatures {
            page-break-inside: avoid !important;
            width: 100%;
        }
        .sign-box-rector {
            page-break-inside: avoid !important;
        }
        
        .certificate-footer {
            margin-top: 30px;
        }
        
        .signatures {
            margin-bottom: 50px;
        }
    }

    @media (max-width: 768px) {
        .certificate {
            padding: 10mm;
            height: auto;
            min-height: 297mm;
        }
        .signatures {
            flex-direction: column;
            gap: 20px;
        }
        .sign-box-date, .sign-box-registrar, .sign-box-rector {
            width: 100%;
            margin: 10px 0;
            text-align: center;
        }
        .certificate-number {
            position: relative;
            top: auto;
            right: auto;
            margin: 10px 0;
        }
    }
</style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark no-print">
        <div class="container">
            <a class="navbar-brand" href="#">
                <img src="assets/NewLogo.svg" alt="Logo" class="logo" onerror="this.src='https://via.placeholder.com/40x40/ffffff/1a237e?text=GIPS'">
                Gateway ICT Polytechnic Saapade
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php" onclick="showSection('certificateSection')">
                            <i class="fas fa-certificate me-1"></i>Certificate
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="bulk_upload.php"><i class="fas fa-users me-1"></i>Add students</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('printManagementSection')">
                            <i class="fas fa-print me-1"></i>Print Management
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('reportsSection')">
                            <i class="fas fa-chart-bar me-1"></i>Reports
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;"></div>
        <div class="mt-2">Loading...</div>
    </div>

    <div class="container-fluid">
        <div id="certificateSection">
            <div class="row">
                <div class="col-md-8">
                    <div class="settings-panel no-print">
                        <h4><i class="fas fa-cog me-2"></i>Certificate Settings</h4>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Issue Date</label>
                                    <input type="date" class="form-control" id="issueDate" value="<?php echo date('Y-m-d'); ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Certificate Type</label>
                                    <select class="form-control" id="certificateType">
                                        <option value="National Diploma">National Diploma</option>
                                        <option value="Higher National Diploma">Higher National Diploma</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <button class="btn btn-warning" onclick="updateCertificateSettings()">
                            <i class="fas fa-save me-2"></i>Update Settings
                        </button>
                        <button class="btn btn-info ms-2" onclick="testConnection()">
                            <i class="fas fa-plug me-2"></i>Test Connection
                        </button>
                    </div>

                    <div class="certificate">
                        <h1>The Gateway (ICT) Polytechnic Saapade<br />Ogun State, Nigeria</h1>
                        <div class="pos">
                            <div class="qr" id="qrCodeContainer">
                                <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:#f0f0f0;font-size:12px;">QR Code</div>
                            </div>
                            <div class="sap">
                                <img src="assets/NewLogo.svg" alt="Logo" class="mlogo" width="100px" onerror="this.style.display='none'" />
                            </div>
                            <div class="certificate-number" id="certificateNumber">GPS034253</div>
                            <div class="passport" id="studentPhotoContainer">
                                <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:#f0f0f0;font-size:12px;">Photo</div>
                            </div>
                        </div>
                        <h2>This is to Certify that</h2>
                        <div class="content">
                            <span class="student-name-bold" id="studentName">[Student Name]</span>
                            having completed an approved course of study, passed the examinations
                            and fulfilled all the requirements prescribed by the Polytechnic, as at
                            this day, under the authority of the Academic Board, been awarded the<br /><br />
                            <span class="certificate-type-display" id="certificateTypeDisplay">National Diploma</span>
                            <span class="in-text">in</span>
                            <span class="program-bold" id="programName">[Program Name]</span>
                        </div>
                        <div class="fields">
                            <div class="matric"><span class="inner">Matric No: <strong id="studentMatric">[student_id]</strong></span></div>
                            <div class="grade">{With <strong id="studentFinalGrade">[Grade]</strong> }<span class="space"></span></div>
                        </div>
                        <div class="seal" id="officialSealContainer">
                            <img src="assets/seal.jpg" alt="Official Seal" onerror="this.style.display='none'">
                        </div>
                        
                        <div class="certificate-footer">
                            <div class="signatures">
                                <div class="sign-box-date signature-box">
                                    <span class="line-content" id="issueDateDisplay"><?php echo date('F j, Y'); ?></span>
                                    <div class="signature-line-placeholder"></div>
                                    <span>Date</span>
                                </div>
                                <div class="sign-box-registrar signature-box">
                                    <span class="line-content"></span>
                                    <div class="signature-line-placeholder"></div>
                                    <span>Registrar</span>
                                </div>
                            </div>
                            <div class="sign-box-rector signature-box">
                                <span class="line-content"></span>
                                <div class="signature-line-placeholder"></div>
                                <span class="rec">Rector</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="action-buttons no-print text-center mb-4">
                        <button class="btn btn-primary btn-lg" onclick="printCurrentCertificate()">
                            <i class="fas fa-print me-2"></i>Print Current Certificate
                        </button>
                        <button class="btn btn-success btn-lg" onclick="showSection('printManagementSection')">
                            <i class="fas fa-download me-2"></i>Batch Print Management
                        </button>
                    </div>
                </div>
                
                <div class="col-md-4 no-print">
                    <div class="student-list">
                        <h3 class="mb-4"><i class="fas fa-users me-2"></i>Student Records</h3>
                        
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" placeholder="Search students..." id="searchInput">
                            <button class="btn btn-outline-primary" type="button" onclick="searchStudents()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                        
                        <div id="studentsContainer">
                            <div class="text-center">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p>Loading students...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="printManagementSection" style="display: none;">
            <div class="row">
                <div class="col-12">
                    <div class="settings-panel">
                        <h4><i class="fas fa-print me-2"></i>Batch Print Management</h4>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Print Range</label>
                                    <select class="form-control" id="printRange">
                                        <option value="all">All Students</option>
                                        <option value="unprinted">Unprinted Only</option>
                                        <option value="selected">Selected Students</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Resume From</label>
                                    <select class="form-control" id="resumeFrom">
                                        <option value="start">Start from Beginning</option>
                                        <option value="last">Resume from Last Printed</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="print-progress">
                            <div class="d-flex justify-content-between mb-2">
                                <span>Print Progress</span>
                                <span id="progressText">0/0</span>
                            </div>
                            <div class="progress">
                                <div id="printProgressBar" class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                        </div>

                        <div class="alert alert-info" id="printStatus">
                            Ready to start printing
                        </div>

                        <button class="btn btn-success btn-lg" onclick="startBatchPrint()">
                            <i class="fas fa-play me-2"></i>Start Batch Print
                        </button>
                        <button class="btn btn-warning btn-lg" onclick="pauseBatchPrint()">
                            <i class="fas fa-pause me-2"></i>Pause Print
                        </button>
                        <button class="btn btn-danger btn-lg" onclick="stopBatchPrint()">
                            <i class="fas fa-stop me-2"></i>Stop Print
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div id="reportsSection" style="display: none;">
            <div class="row">
                <div class="col-12">
                    <div class="settings-panel">
                        <h4><i class="fas fa-chart-bar me-2"></i>Printing Reports & Statistics</h4>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="stat-card stat-printed">
                                    <h3 id="printedCount">0</h3>
                                    <p>Certificates Printed</p>
                                    <i class="fas fa-check-circle fa-2x text-success"></i>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stat-card stat-pending">
                                    <h3 id="pendingCount">0</h3>
                                    <p>Pending Printing</p>
                                    <i class="fas fa-clock fa-2x text-warning"></i>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stat-card stat-error">
                                    <h3 id="errorCount">0</h3>
                                    <p>Printing Errors</p>
                                    <i class="fas fa-exclamation-triangle fa-2x text-danger"></i>
                                </div>
                            </div>
                        </div>

                        <div class="mt-4">
                            <h5>Last Print Session</h5>
                            <div class="alert alert-warning" id="lastPrintSession">
                                No print session recorded
                            </div>
                        </div>

                        <div class="mt-4">
                            <h5>Print Error Log</h5>
                            <div class="alert alert-light" id="errorLog" style="max-height: 200px; overflow-y: auto;">
                                No errors recorded
                            </div>
                        </div>

                        <button class="btn btn-info" onclick="refreshReports()">
                            <i class="fas fa-sync me-2"></i>Refresh Reports
                        </button>
                        <button class="btn btn-secondary" onclick="exportReports()">
                            <i class="fas fa-download me-2"></i>Export Report
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentStudent = null;
        let allStudents = [];
        let printQueue = [];
        let currentPrintIndex = 0;
        let isPrinting = false;
        let printSession = {
            startTime: null,
            endTime: null,
            total: 0,
            printed: 0,
            errors: 0,
            lastPrinted: null
        };

        let certificateSettings = {
            issueDate: '<?php echo date('Y-m-d'); ?>',
            certificateType: 'National Diploma',
            officialSeal: 'assets/red-seal-certificate.avif',
            registrarSignature: 'assets/registrar-signature.png',
            rectorSignature: 'assets/rector-signature.png'
        };

        // Navigation functions
        function showSection(sectionId) {
            document.getElementById('certificateSection').style.display = 'none';
            document.getElementById('printManagementSection').style.display = 'none';
            document.getElementById('reportsSection').style.display = 'none';
            
            document.getElementById(sectionId).style.display = 'block';
            
            if (sectionId === 'reportsSection') {
                refreshReports();
            }
        }

        // Generate unique certificate number
        function generateCertificateNumber(studentId = null) {
            const prefix = "GPS";
            const timestamp = Date.now().toString().slice(-6);
            const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
            
            if (studentId) {
                return `${prefix}${studentId.toString().padStart(6, '0')}`;
            }
            
            return `${prefix}${timestamp}${random}`;
        }

        // Show loading spinner
        function showLoading(message = 'Loading...') {
            const spinner = document.getElementById('loadingSpinner');
            spinner.style.display = 'block';
            spinner.querySelector('div:last-child').textContent = message;
        }

        // Hide loading spinner
        function hideLoading() {
            document.getElementById('loadingSpinner').style.display = 'none';
        }

        // Test database connection
        async function testConnection() {
            try {
                showLoading('Testing connection...');
                const response = await fetch('api/test_connection.php');
                const result = await response.json();
                
                if (result.success) {
                    alert('✅ Connection successful! ' + result.message);
                } else {
                    alert('❌ Connection failed: ' + result.message);
                }
            } catch (error) {
                alert('❌ Connection error: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        // Fetch all students
        async function fetchStudents() {
            try {
                showLoading('Loading students...');
                
                const response = await fetch('api/get_students.php');
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('API Response:', data);
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                let students = [];
                if (data.records && Array.isArray(data.records)) {
                    students = data.records;
                } else if (Array.isArray(data)) {
                    students = data;
                } else if (data.data && Array.isArray(data.data)) {
                    students = data.data;
                } else if (data.students && Array.isArray(data.students)) {
                    students = data.students;
                }
                
                if (students.length > 0) {
                    allStudents = students;
                    displayStudents(allStudents);
                    // viewStudent will now handle the certificateNumber for QR code
                    await viewStudent(allStudents[0].id);
                    updatePrintStats();
                } else {
                    showNoStudentsMessage();
                }
            } catch (error) {
                console.error('Error fetching students:', error);
                showError('studentsContainer', 'Error loading students: ' + error.message);
                createSampleStudents();
            } finally {
                hideLoading();
            }
        }

        // Create sample students that match your database structure
        function createSampleStudents() {
            allStudents = [
                {
                    id: 1,
                    student_id: "GPS/ND/24/001",
                    full_name: "John Chika Okafor",
                    program: "Computer Science",
                    department: "Computer Science",
                    grade: "Distinction",
                    graduation_date: "2024-07-15",
                    photo_path: "https://via.placeholder.com/120x120/1a237e/ffffff?text=JCO",
                    certificate_id: null,
                    created_at: "2024-01-01 10:00:00"
                },
                {
                    id: 2,
                    student_id: "GPS/ND/24/002",
                    full_name: "Maryam Adekunle",
                    program: "Electrical Engineering", 
                    department: "Electrical Engineering",
                    grade: "Upper Credit",
                    graduation_date: "2024-07-15",
                    photo_path: "https://via.placeholder.com/120x120/1a237e/ffffff?text=MA",
                    certificate_id: null,
                    created_at: "2024-01-01 10:00:00"
                },
                {
                    id: 3,
                    student_id: "GPS/ND/24/003",
                    full_name: "David Okon",
                    program: "Business Administration",
                    department: "Business Administration", 
                    grade: "Lower Credit",
                    graduation_date: "2024-07-15",
                    photo_path: "https://via.placeholder.com/120x120/1a237e/ffffff?text=DO",
                    certificate_id: null,
                    created_at: "2024-01-01 10:00:00"
                }
            ];
            
            displayStudents(allStudents);
            viewStudent(allStudents[0].id);
            updatePrintStats();
        }

        // Display students in the list
        function displayStudents(students) {
            const container = document.getElementById('studentsContainer');
            
            container.innerHTML = students.map(student => `
                <div class="student-card" onclick="viewStudent(${student.id})" data-student-id="${student.id}">
                    <div class="d-flex align-items-center">
                        <img src="${student.photo_path || 'https://via.placeholder.com/50x50/1a237e/ffffff?text=Photo'}" 
                             alt="${student.full_name}" 
                             class="student-avatar me-3"
                             onerror="this.src='https://via.placeholder.com/50x50/1a237e/ffffff?text=Photo'">
                        <div class="flex-grow-1">
                            <h6 class="mb-1">${student.full_name}</h6>
                            <small class="text-muted">${student.program}</small><br>
                            <small class="text-primary">Matric: ${student.student_id}</small>
                        </div>
                        <span class="badge bg-success">${student.grade}</span>
                    </div>
                </div>
            `).join('');
        }

        function showNoStudentsMessage() {
            document.getElementById('studentsContainer').innerHTML = `
                <div class="alert alert-info">
                    <h5>No Students Found</h5>
                    <p>No student records were found in the database.</p>
                    <button class="btn btn-sm btn-primary" onclick="createSampleStudents()">
                        Load Sample Data
                    </button>
                </div>`;
        }

        function showError(containerId, message) {
            document.getElementById(containerId).innerHTML = `
                <div class="alert alert-danger">
                    <h5>Error</h5>
                    <p>${message}</p>
                    <small>Check browser console for details</small>
                </div>`;
        }

        // View student certificate
        async function viewStudent(studentId) {
            try {
                showLoading('Loading student data...');
                
                let student;
                
                try {
                    const response = await fetch(`api/get_student.php?id=${studentId}`);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    
                    student = await response.json();
                    
                    if (student.error) {
                        throw new Error(student.error);
                    }
                    
                    if (student.message) {
                        throw new Error(student.message);
                    }
                } catch (apiError) {
                    console.warn('API fetch failed, using local data:', apiError);
                    student = allStudents.find(s => s.id == studentId);
                    if (!student) {
                        throw new Error('Student not found');
                    }
                }
                
                currentStudent = student;
                console.log('Student data for certificate:', student);
                updateCertificateDisplay(student);
                
                document.querySelectorAll('.student-card').forEach(card => {
                    card.style.borderLeft = '1px solid #ddd';
                });
                
                const selectedCard = document.querySelector(`[data-student-id="${studentId}"]`);
                if (selectedCard) {
                    selectedCard.style.borderLeft = '4px solid #007bff';
                }
            } catch (error) {
                console.error('Error fetching student:', error);
                alert('Error loading student data: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        // Update certificate display with student data
        function updateCertificateDisplay(student) {
            try {
                document.getElementById('studentName').textContent = student.full_name || '[Student Name]';
                document.getElementById('studentMatric').textContent = student.student_id || '[Matric Number]';
                document.getElementById('studentFinalGrade').textContent = student.grade || '[Grade]';
                document.getElementById('programName').textContent = student.program || '[Program Name]';
                
                const certificateType = document.getElementById('certificateType').value;
                document.getElementById('certificateTypeDisplay').textContent = certificateType;
                
                const certificateNumber = generateCertificateNumber(student.id);
                document.getElementById('certificateNumber').textContent = certificateNumber;
                
                const issueDate = document.getElementById('issueDate').value;
                const formattedDate = new Date(issueDate).toLocaleDateString('en-US', { 
                    year: 'numeric', 
                    month: 'long', 
                    day: 'numeric' 
                });
                document.getElementById('issueDateDisplay').textContent = formattedDate;
                
                const photoContainer = document.getElementById('studentPhotoContainer');
                const photoUrl = student.photo_path && !student.photo_path.includes('placeholder') 
                    ? student.photo_path 
                    : 'https://via.placeholder.com/120x120/1a237e/ffffff?text=Photo';
                photoContainer.innerHTML = `<img src="${photoUrl}" alt="${student.full_name}" 
                    onerror="this.src='https://via.placeholder.com/120x120/1a237e/ffffff?text=Photo'">`;
                
                // --- MODIFICATION HERE ---
                updateQRCode(student, certificateNumber);
                // --- END MODIFICATION ---

            } catch (error) {
                console.error('Error updating certificate display:', error);
            }
        }

        // Update QR code
        // --- MODIFICATION HERE ---
        async function updateQRCode(student, certificateNumber) {
        // --- END MODIFICATION ---
            const qrContainer = document.getElementById('qrCodeContainer');
            
            try {
                // Assuming qr/generate_qr.php can handle more parameters and returns a QR code path/URL
                const response = await fetch(`qr/generate_qr.php?student_id=${student.id}&cert_id=${certificateNumber}`);
                const result = await response.json();
                
                if (result.success) {
                    if (result.qr_code_path) {
                        qrContainer.innerHTML = `<img src="${result.qr_code_path}" alt="QR Code">`;
                    } else if (result.qr_code_url) {
                        qrContainer.innerHTML = `<img src="${result.qr_code_url}" alt="QR Code">`;
                    }
                } else {
                    // --- MODIFICATION HERE ---
                    generateFallbackQRCode(student, qrContainer, certificateNumber);
                    // --- END MODIFICATION ---
                }
            } catch (error) {
                console.error('Error generating QR code:', error);
                // --- MODIFICATION HERE ---
                generateFallbackQRCode(student, qrContainer, certificateNumber);
                // --- END MODIFICATION ---
            }
        }

        // Generate fallback QR code
        // --- MODIFICATION HERE ---
        function generateFallbackQRCode(student, qrContainer, certificateNumber) {
            // The QR code now links to an external verification portal.
            // This external page (e.g., https://certverify.polytechnic.edu.ng/verify.php)
            // is where the user will see the "Request Transcript" and "View CGPA" links.
            // The CGPA link on that page would trigger the payment process and redirection.
            const qrContent = `https://certverify.polytechnic.edu.ng/verify.php?matric=${student.student_id}&cert_id=${certificateNumber}`;
            // --- END MODIFICATION ---
            
            const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(qrContent)}`;
            qrContainer.innerHTML = `<img src="${qrUrl}" alt="Verification Link QR Code">`;
        }

        // Update certificate settings
        function updateCertificateSettings() {
            certificateSettings.issueDate = document.getElementById('issueDate').value;
            certificateSettings.certificateType = document.getElementById('certificateType').value;
            
            if (currentStudent) {
                updateCertificateDisplay(currentStudent);
            }
            
            alert('Certificate settings updated successfully!');
        }

        // Search students
        async function searchStudents() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            
            if (searchTerm === '') {
                displayStudents(allStudents);
                return;
            }
            
            try {
                showLoading('Searching...');
                const response = await fetch(`api/get_students.php?s=${encodeURIComponent(searchTerm)}`);
                const data = await response.json();
                
                if (data.records) {
                    displayStudents(data.records);
                }
            } catch (error) {
                console.error('Error searching students:', error);
                const filteredStudents = allStudents.filter(student => 
                    student.full_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    (student.student_id && student.student_id.toLowerCase().includes(searchTerm.toLowerCase())) ||
                    student.program.toLowerCase().includes(searchTerm.toLowerCase())
                );
                displayStudents(filteredStudents);
            } finally {
                hideLoading();
            }
        }

        // Print current certificate
        function printCurrentCertificate() {
            if (!currentStudent) {
                alert('Please select a student first');
                return;
            }
            window.print();
        }

        // Batch printing functions
        async function startBatchPrint() {
            const printRange = document.getElementById('printRange').value;
            const resumeFrom = document.getElementById('resumeFrom').value;
            
            printQueue = [];
            
            if (printRange === 'all') {
                printQueue = [...allStudents];
            } else if (printRange === 'unprinted') {
                printQueue = allStudents.filter(student => !student.printed);
            } else if (printRange === 'selected') {
                printQueue = [currentStudent];
            }
            
            if (printQueue.length === 0) {
                alert('No students to print');
                return;
            }
            
            if (resumeFrom === 'last') {
                const lastPrintedId = localStorage.getItem('lastPrintedStudentId');
                if (lastPrintedId) {
                    const lastIndex = printQueue.findIndex(student => student.id == lastPrintedId);
                    currentPrintIndex = lastIndex > -1 ? lastIndex : 0;
                }
            } else {
                currentPrintIndex = 0;
            }
            
            printSession = {
                startTime: new Date(),
                endTime: null,
                total: printQueue.length,
                printed: 0,
                errors: 0,
                lastPrinted: null
            };
            
            isPrinting = true;
            updatePrintProgress();
            document.getElementById('printStatus').className = 'alert alert-info';
            document.getElementById('printStatus').textContent = 'Printing in progress...';
            
            await printNextCertificate();
        }

        function pauseBatchPrint() {
            isPrinting = false;
            document.getElementById('printStatus').className = 'alert alert-warning';
            document.getElementById('printStatus').textContent = 'Printing paused';
        }

        function stopBatchPrint() {
            isPrinting = false;
            document.getElementById('printStatus').className = 'alert alert-danger';
            document.getElementById('printStatus').textContent = 'Printing stopped';
            updatePrintStats();
        }

        async function printNextCertificate() {
            if (!isPrinting || currentPrintIndex >= printQueue.length) {
                printSession.endTime = new Date();
                isPrinting = false;
                document.getElementById('printStatus').className = 'alert alert-success';
                document.getElementById('printStatus').textContent = 'Printing completed successfully!';
                updatePrintStats();
                return;
            }
            
            const student = printQueue[currentPrintIndex];
            
            try {
                await viewStudent(student.id);
                await new Promise(resolve => setTimeout(resolve, 1000));
                window.print();
                
                printSession.printed++;
                printSession.lastPrinted = student.id;
                localStorage.setItem('lastPrintedStudentId', student.id);
                await markStudentAsPrinted(student.id);
                
                currentPrintIndex++;
                updatePrintProgress();
                setTimeout(printNextCertificate, 2000);
                
            } catch (error) {
                console.error('Error printing certificate for:', student.full_name, error);
                printSession.errors++;
                currentPrintIndex++;
                updatePrintProgress();
                logError(`Error printing ${student.full_name}: ${error.message}`);
                setTimeout(printNextCertificate, 1000);
            }
        }

        function updatePrintProgress() {
            const progress = (currentPrintIndex / printQueue.length) * 100;
            document.getElementById('printProgressBar').style.width = `${progress}%`;
            document.getElementById('progressText').textContent = `${currentPrintIndex}/${printQueue.length}`;
        }

        async function markStudentAsPrinted(studentId) {
            try {
                const response = await fetch(`api/mark_printed.php?id=${studentId}`, {
                    method: 'POST'
                });
                return await response.json();
            } catch (error) {
                console.error('Error marking student as printed:', error);
            }
        }

        function logError(message) {
            const errorLog = document.getElementById('errorLog');
            const timestamp = new Date().toLocaleTimeString();
            errorLog.innerHTML += `<div class="text-danger">[${timestamp}] ${message}</div>`;
            errorLog.scrollTop = errorLog.scrollHeight;
        }

        // Reports functions
        function updatePrintStats() {
            const printedCount = allStudents.filter(s => s.printed).length;
            const pendingCount = allStudents.length - printedCount;
            
            document.getElementById('printedCount').textContent = printedCount;
            document.getElementById('pendingCount').textContent = pendingCount;
            document.getElementById('errorCount').textContent = printSession.errors;
        }

        function refreshReports() {
            updatePrintStats();
            
            const lastSession = document.getElementById('lastPrintSession');
            if (printSession.startTime) {
                const duration = printSession.endTime 
                    ? Math.round((printSession.endTime - printSession.startTime) / 1000)
                    : Math.round((new Date() - printSession.startTime) / 1000);
                
                lastSession.innerHTML = `
                    Started: ${printSession.startTime.toLocaleString()}<br>
                    ${printSession.endTime ? `Completed: ${printSession.endTime.toLocaleString()}<br>` : ''}
                    Duration: ${duration} seconds<br>
                    Printed: ${printSession.printed}/${printSession.total}<br>
                    Errors: ${printSession.errors}
                `;
            }
        }

        function exportReports() {
            alert('Export functionality would be implemented here');
        }

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            fetchStudents();
            
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchStudents();
                }
            });
            
            document.getElementById('issueDate').addEventListener('change', function() {
                if (currentStudent) {
                    updateCertificateDisplay(currentStudent);
                }
            });
            
            document.getElementById('certificateType').addEventListener('change', function() {
                if (currentStudent) {
                    updateCertificateDisplay(currentStudent);
                }
            });
        });
    </script>
</body>
</html>