<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";

if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['studentid'];
$intake = $_SESSION['intake'] ?? '';
$program = $_SESSION['program'] ?? '';

// Initialize scholarship variable
$scholarship = 0;
$query12 = mysqli_query($conn, "SELECT percentage as scholarship FROM scholarship WHERE studentid='$userlogin'");
if ($query12 && mysqli_num_rows($query12) > 0) {
    $row = mysqli_fetch_array($query12);
    $scholarship = $row['scholarship'];
}

// Function to calculate current year and semester based on intake
function calculateCurrentYearSemester($intake) {
    $intakeDate = DateTime::createFromFormat('F Y', $intake);
    if (!$intakeDate) {
        return ['year' => 1, 'semester' => 1];
    }
    
    $currentDate = new DateTime();
    $interval = $currentDate->diff($intakeDate);
    $monthsDifference = ($interval->y * 12) + $interval->m;
    $currentSemester = floor($monthsDifference / 6) + 1;
    $currentYear = ceil($currentSemester / 2);
    $semesterInYear = ($currentSemester % 2 == 0) ? 2 : 1;
    
    return [
        'year' => max(1, $currentYear),
        'semester' => $semesterInYear,
        'total_semesters' => $currentSemester
    ];
}

$currentInfo = calculateCurrentYearSemester($intake);
$currentYear = $currentInfo['year'];
$currentSemester = $currentInfo['semester'];

// Get admin settings
$sql = "SELECT * FROM admin LIMIT 1"; 
$resultadmin = mysqli_query($conn, $sql); 
if (!$resultadmin) {     
    die("Query failed: " . mysqli_error($conn)); 
} 
$row = mysqli_fetch_assoc($resultadmin); 
$sname = $row['sname'] ?? '';
$call = $row['contact'] ?? '';
$add = $row['address'] ?? '';
$web = $row['web'] ?? '';
$maxpay = $row['maxpay'] ?? 75; // fallback to 75%

// Check if student has paid at least the required percentage of fees
function checkFeeClearance($conn, $studentid, $maxpay, $program, $scholarship) {
    // Get student intake
    $studentQuery = "SELECT intake FROM students WHERE studentid = '" . mysqli_real_escape_string($conn, $studentid) . "' LIMIT 1";
    $studentResult = mysqli_query($conn, $studentQuery);
    $studentData = $studentResult ? mysqli_fetch_assoc($studentResult) : null;
    $studentIntake = $studentData['intake'] ?? '';
    
    // Get total fees required
    $feeQuery = "SELECT SUM(amount) as total_fees FROM balances WHERE program='" . mysqli_real_escape_string($conn, $program) . "' AND intake = '" . mysqli_real_escape_string($conn, $studentIntake) . "'";
    $feeResult = mysqli_query($conn, $feeQuery);
    $feeData = $feeResult ? mysqli_fetch_assoc($feeResult) : null;
    
    $totalfe = $feeData['total_fees'] ?? 0;
    
    // Apply scholarship discount if applicable
    if ($scholarship != 0) {
        $scholar = ($scholarship / 100) * $totalfe;
    } else {
        $scholar = 0;
    }
    
    $totalFees = $totalfe - $scholar;
    if ($totalFees < 0) $totalFees = 0;
    
    // Get total payments made
    $paymentQuery = "SELECT SUM(amount) as total_paid FROM payments WHERE studentid = '" . mysqli_real_escape_string($conn, $studentid) . "' AND status = 'paid'";
    $paymentResult = mysqli_query($conn, $paymentQuery);
    $paymentData = $paymentResult ? mysqli_fetch_assoc($paymentResult) : null;
    $totalPaid = $paymentData['total_paid'] ?? 0;
    
    // Calculate percentage paid
    if ($totalFees > 0) {
        $percentagePaid = ($totalPaid / $totalFees) * 100;
    } else {
        // If total fees is 0 (100% scholarship or no fees), consider as 100% paid
        $percentagePaid = 100;
    }
    
    // SPECIAL CASE: If scholarship is 100%, automatically clear fees regardless of payments
    $isFullySponsored = ($scholarship == 100);
    
    return [
        'clear' => ($percentagePaid >= $maxpay) || $isFullySponsored,
        'percentage' => round($percentagePaid, 1), 
        'total_fees' => $totalFees,
        'total_paid' => $totalPaid,
        'balance' => $totalFees - $totalPaid,
        'scholarship_amount' => $scholar,
        'scholarship_percentage' => $scholarship,
        'is_fully_sponsored' => $isFullySponsored,
        'original_fees' => $totalfe
    ];
}

// Check if student has special permission from permit table
function checkSpecialPermission($conn, $studentid) {
    $currentDate = date('Y-m-d');
    
    // Check for active permits that haven't expired
    $permitQuery = "SELECT `id`, `studentid`, `permittedby`, `days`, `semester`, `year`, `created_date`
                   FROM `permit` 
                   WHERE studentid = '" . mysqli_real_escape_string($conn, $studentid) . "' 
                   AND CURDATE() <= DATE_ADD(created_date, INTERVAL days DAY)
                   AND CURDATE() >= created_date
                   ORDER BY created_date DESC 
                   LIMIT 1";
    
    $permitResult = mysqli_query($conn, $permitQuery);
    
    if ($permitResult && mysqli_num_rows($permitResult) > 0) {
        $permitData = mysqli_fetch_assoc($permitResult);
        
        // Calculate days remaining
        $createdDate = new DateTime($permitData['created_date']);
        $currentDateObj = new DateTime($currentDate);
        $expiryDate = date('Y-m-d', strtotime($permitData['created_date'] . ' + ' . $permitData['days'] . ' days'));
        $expiryDateObj = new DateTime($expiryDate);
        $daysRemaining = $currentDateObj->diff($expiryDateObj)->days;
        
        return [
            'has_permission' => true,
            'permitted_by' => $permitData['permittedby'],
            'days_valid' => $daysRemaining,
            'total_days' => $permitData['days'],
            'created_date' => $permitData['created_date'],
            'expiry_date' => $expiryDate,
            'permit_data' => $permitData
        ];
    }
    
    // Alternative: Check for permits without days field but with status
    $permitQuery2 = "SELECT `id`, `studentid`, `permittedby`, `days`, `semester`, `year`, `created_date`
                    FROM `permit` 
                    WHERE studentid = '" . mysqli_real_escape_string($conn, $studentid) . "' 
                    ORDER BY created_date DESC 
                    LIMIT 1";
    
    $permitResult2 = mysqli_query($conn, $permitQuery2);
    
    if ($permitResult2 && mysqli_num_rows($permitResult2) > 0) {
        $permitData = mysqli_fetch_assoc($permitResult2);
        return [
            'has_permission' => true,
            'permitted_by' => $permitData['permittedby'],
            'days_valid' => 999, // No expiry
            'total_days' => $permitData['days'] ?? 0,
            'created_date' => $permitData['created_date'],
            'expiry_date' => 'No Expiry',
            'permit_data' => $permitData
        ];
    }
    
    return [
        'has_permission' => false,
        'permitted_by' => '',
        'days_valid' => 0,
        'total_days' => 0,
        'created_date' => '',
        'expiry_date' => '',
        'permit_data' => null
    ];
}

// Check if student has returned all issued books
function checkBookReturns($conn, $studentid) {
    $bookQuery = "SELECT COUNT(*) as outstanding_books FROM `book_issues` 
                  WHERE `studentid` = '" . mysqli_real_escape_string($conn, $studentid) . "' 
                  AND (`return_date` IS NULL OR `return_date` = '0000-00-00' OR `status` = 'issued')";
    
    $bookResult = mysqli_query($conn, $bookQuery);
    
    if ($bookResult && mysqli_num_rows($bookResult) > 0) {
        $bookData = mysqli_fetch_assoc($bookResult);
        $outstandingBooks = $bookData['outstanding_books'] ?? 0;
        
        return [
            'has_outstanding_books' => $outstandingBooks > 0,
            'outstanding_count' => $outstandingBooks
        ];
    }
    
    return [
        'has_outstanding_books' => false,
        'outstanding_count' => 0
    ];
}

// NEW FUNCTION: Check if student has any outstanding association fees
function checkAssociationFees($conn, $studentid) {
    // First, get student's program, intake, and calculate current year/semester
    $studentQuery = "SELECT program, intake FROM students WHERE studentid = '" . mysqli_real_escape_string($conn, $studentid) . "' LIMIT 1";
    $studentResult = mysqli_query($conn, $studentQuery);
    $studentData = $studentResult ? mysqli_fetch_assoc($studentResult) : null;
    
    if (!$studentData) {
        return [
            'has_association_balance' => false,
            'total_invoice' => 0,
            'total_paid' => 0,
            'balance' => 0,
            'invoices' => [],
            'payments' => []
        ];
    }
    
    $program = $studentData['program'];
    $intake = $studentData['intake'];
    
    // Calculate current academic year and semester
    $currentYear = date('Y');
    $currentMonth = date('n');
    $currentSemester = ($currentMonth >= 1 && $currentMonth <= 6) ? 1 : 2;
    
    // Get all association invoices that apply to this student
    // Based on student_type (all, specific program, etc.)
    $invoiceQuery = "SELECT ai.* 
                    FROM `association_invoice` ai
                    WHERE (ai.student_type = 'all' 
                           OR (ai.student_type = 'program' AND ai.description LIKE '%" . mysqli_real_escape_string($conn, $program) . "%')
                           OR (ai.student_type = 'year' AND ai.year <= $currentYear))
                    AND (ai.year <= $currentYear)
                    AND (ai.semester <= $currentSemester OR ai.semester = 0)
                    ORDER BY ai.year DESC, ai.semester DESC";
    
    $invoiceResult = mysqli_query($conn, $invoiceQuery);
    $invoices = [];
    $totalInvoice = 0;
    
    if ($invoiceResult) {
        while ($invoice = mysqli_fetch_assoc($invoiceResult)) {
            $invoices[] = $invoice;
            $totalInvoice += $invoice['amount'];
        }
    }
    
    // Get all association payments made by this student
    $paymentQuery = "SELECT * FROM `association_payment` 
                    WHERE studentid = '" . mysqli_real_escape_string($conn, $studentid) . "' 
                    AND status = 'paid'
                    ORDER BY payment_date DESC";
    
    $paymentResult = mysqli_query($conn, $paymentQuery);
    $payments = [];
    $totalPaid = 0;
    
    if ($paymentResult) {
        while ($payment = mysqli_fetch_assoc($paymentResult)) {
            $payments[] = $payment;
            $totalPaid += $payment['amount'];
        }
    }
    
    $balance = $totalInvoice - $totalPaid;
    
    return [
        'has_association_balance' => $balance > 0,
        'total_invoice' => $totalInvoice,
        'total_paid' => $totalPaid,
        'balance' => $balance,
        'invoices' => $invoices,
        'payments' => $payments,
        'current_year' => $currentYear,
        'current_semester' => $currentSemester
    ];
}

// Get student details
$studentQuery = "SELECT * FROM students WHERE studentid = '" . mysqli_real_escape_string($conn, $userlogin) . "' LIMIT 1";
$studentResult = mysqli_query($conn, $studentQuery);
$student = $studentResult ? mysqli_fetch_assoc($studentResult) : [];

// Check clearance status
$clearanceStatus = checkFeeClearance($conn, $userlogin, $maxpay, $program, $scholarship);

// Check special permission
$permissionStatus = checkSpecialPermission($conn, $userlogin);

// Check book returns
$bookReturnStatus = checkBookReturns($conn, $userlogin);

// NEW: Check association fees
$associationStatus = checkAssociationFees($conn, $userlogin);

// Debug: Check what's being returned
error_log("Clearance Status: " . ($clearanceStatus['clear'] ? 'CLEAR' : 'NOT CLEAR'));
error_log("Permission Status: " . ($permissionStatus['has_permission'] ? 'HAS PERMISSION' : 'NO PERMISSION'));
error_log("Book Return Status: " . ($bookReturnStatus['has_outstanding_books'] ? 'HAS OUTSTANDING BOOKS' : 'NO OUTSTANDING BOOKS'));
error_log("Association Status: " . ($associationStatus['has_association_balance'] ? 'HAS ASSOCIATION BALANCE' : 'NO ASSOCIATION BALANCE'));

// Determine if student can access certificate
// Student must have no association balance AND (fee clearance OR permission) AND no outstanding books
$canAccessCertificate = !$associationStatus['has_association_balance'] && 
                       ($clearanceStatus['clear'] || $permissionStatus['has_permission']) && 
                       !$bookReturnStatus['has_outstanding_books'];

error_log("Can Access Certificate: " . ($canAccessCertificate ? 'YES' : 'NO'));

// Calculate current year and semester
$currentInfo = calculateCurrentYearSemester($intake);
$currentYear1 = date("Y");
$currentSemester = $currentInfo['semester'];

// Get current semester courses (for display; we'll query again where needed)
$courseQuery = "SELECT * FROM results 
               WHERE year = '$currentYear1' 
               AND term = '" . mysqli_real_escape_string($conn, $currentSemester) . "' 
               AND studentid = '" . mysqli_real_escape_string($conn, $userlogin) . "'
               ORDER BY course ASC";
$courseResult = mysqli_query($conn, $courseQuery);
$courses = [];
if ($courseResult) {
    while ($courseRow = mysqli_fetch_assoc($courseResult)) {
        $courses[] = $courseRow;
    }
}

// Generate document IDs (consistent single generation)
try {
    // Document ID: 8 hex chars
    $documentSuffix = strtoupper(bin2hex(random_bytes(4))); // 8 hex chars
    $documentID = "CLR-" . $documentSuffix;

    // Security code: 4 hex chars (short)
    $securityCode = strtoupper(substr(bin2hex(random_bytes(2)), 0, 4)); // 4 hex chars

} catch (Exception $e) {
    // Fallback if random_bytes fails
    $documentID = "CLR-" . strtoupper(substr(md5(uniqid($userlogin, true)), 0, 8));
    $securityCode = strtoupper(substr(md5($userlogin . date('Ymd')), 0, 4));
}

$generatedOn = date('Y-m-d');
$expiryDate = date('Y-m-d', strtotime($generatedOn . ' +21 days'));

// If student has special permission, use shorter expiry based on permit days
if ($permissionStatus['has_permission'] && $permissionStatus['expiry_date'] != 'No Expiry') {
    $expiryDate = $permissionStatus['expiry_date'];
}

// Check if we're viewing the certificate page
$viewCertificate = isset($_GET['view']) && $_GET['view'] === 'certificate';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $viewCertificate ? 'Fee Clearance Certificate' : 'Fee Clearance - Student Portal'; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Arial', sans-serif; background: linear-gradient(135deg,#f5f7fa 0%,#e4efe9 100%); min-height:100vh; }
        .mobile-container { width:100%; max-width:100%; margin:0 auto; background:; min-height:100vh;  }
        .header { background: #13700bdc; color:white; padding:15px 20px; text-align:center; position:sticky; top:0; z-index:100; box-shadow:0 2px 10px rgba(0,0,0,0.1); }
        .header h1 { font-size:1.5rem; margin:0; }
        .header p { font-size:0.9rem; opacity:0.9; margin:5px 0 0; }
        .content-section { padding:20px 15px; }
        .status-card { text-align:center; padding:20px 15px; border-radius:12px; margin-bottom:20px; box-shadow:0 4px 10px rgba(0,0,0,0.08); }
        .status-cleared { background-color:#d4edda; color:#155724; border:1px solid #c3e6cb; }
        .status-not-cleared { background-color:#f8d7da; color:#721c24; border:1px solid #f5c6cb; }
        .status-permitted { background-color:#e7f3ff; color:#0c5460; border:1px solid #b8daff; }
        .status-scholarship { background-color:#d1ecf1; color:#0c5460; border:1px solid #bee5eb; }
        .percentage-circle { width:100px; height:100px; border-radius:50%; background:#f8f9fa; border:8px solid #e9ecef; margin:0 auto 15px; display:flex; align-items:center; justify-content:center; font-size:20px; font-weight:bold; }
        .btn-download { background:#13700bdc; color:white; padding:12px 25px; font-size:16px; border-radius:8px; transition:all 0.3s; width:100%; max-width:300px; border:none; margin:10px 0; }
        .btn-download:hover { background:#037c2c; transform:translateY(-2px); }
        .btn-download:disabled { background:#6c757d; cursor:not-allowed; }
        .btn-view-certificate { background:#0d6efd; color:white; padding:12px 25px; font-size:16px; border-radius:8px; transition:all 0.3s; width:100%; max-width:300px; border:none; margin:10px 0; }
        .btn-view-certificate:hover { background:#0b5ed7; transform:translateY(-2px); }
        .payment-summary { margin-top:15px; overflow-x:auto; }
        .payment-summary table { width:100%; border-collapse:collapse; min-width:300px; }
        .payment-summary th, .payment-summary td { padding:10px; text-align:left; border-bottom:1px solid #ddd; }
        .payment-summary th { background-color:#f8f9fa; font-weight:600; }
        .barcode-container { text-align:center; margin:15px 0; padding:10px; background:#f8f9fa; border-radius:8px; }
        .barcode { margin:0 auto; max-width:100%; }
        .info-section { background-color:#e7f3ff; border-radius:12px; padding:15px; margin-top:20px; }
        .info-section h5 { color:#0d6efd; margin-bottom:10px; }
        .info-section ul { padding-left:20px; margin-bottom:0; }
        .info-section li { margin-bottom:8px; font-size:0.9rem; }
        .certificate-page { display: <?php echo $viewCertificate ? 'block' : 'none'; ?>; }
        .main-page { display: <?php echo $viewCertificate ? 'none' : 'block'; ?>; }
        .certificate-container { padding:15px; background:white; border-radius:12px; box-shadow:0 4px 10px rgba(0,0,0,0.1); margin:15px; position:relative; }
        .certificate-header { text-align:center; margin-bottom:20px; border-bottom:2px solid #333; padding-bottom:15px; }
        .university-name { font-size:18px; font-weight:bold; color:#13700bdc; }
        .office-name { font-size:16px; margin-top:8px; }
        .certificate-title { text-align:center; font-size:18px; font-weight:bold; margin:20px 0; text-decoration:underline; }
        .student-info { margin:15px 0; }
        .info-row { margin:6px 0; }
        .info-label { font-weight:bold; display:inline-block; width:100px; }
        .status-cleared-pdf { color:#28a745; font-weight:bold; font-size:16px; text-align:center; margin:20px 0; padding:10px; border:2px solid #28a745; background-color:#f8fff8; }
        .status-permitted-pdf { color:#0d6efd; font-weight:bold; font-size:16px; text-align:center; margin:20px 0; padding:10px; border:2px solid #0d6efd; background-color:#f0f8ff; }
        .status-scholarship-pdf { color:#17a2b8; font-weight:bold; font-size:16px; text-align:center; margin:20px 0; padding:10px; border:2px solid #17a2b8; background-color:#f0f8ff; }
        .certificate-table { width:100%; border-collapse:collapse; margin:15px 0; }
        .certificate-table th, .certificate-table td { border:1px solid #ddd; padding:8px; text-align:left; }
        .certificate-table th { background-color:#f2f2f2; font-weight:bold; }
        .signature-container { margin-top:40px; text-align:right; margin-right:30px; }
        .signature-label { text-align:center; margin-top:5px; font-style:italic; border-top:1px solid #333; padding-top:5px; width:200px; margin-left:auto; }
        .security-features { font-size:9px; color:#666; margin-top:20px; text-align:center; }
        .watermark { position:absolute; opacity:0.08; font-size:60px; color:#13700bdc; transform:rotate(-45deg); top:30%; left:5%; z-index:0; }
        .barcode-pdf { text-align:center; margin:15px 0; }
        .nav-buttons { display:flex; justify-content:space-between; margin:20px 0; padding:0 15px; }
        .nav-btn { background:#6c757d; color:white; padding:10px 20px; border-radius:8px; text-decoration:none; display:inline-block; }
        .nav-btn:hover { background:#5c636a; color:white; text-decoration:none; }
        .next-page-btn { position:fixed; bottom:20px; right:20px; background:#13700bdc; color:white; width:50px; height:50px; border-radius:50%; display:flex; align-items:center; justify-content:center; box-shadow:0 4px 10px rgba(0,0,0,0.2); z-index:1000; border:none; }
        .table-responsive { overflow-x:auto; -webkit-overflow-scrolling:touch; }
        .permission-badge { background:#0d6efd; color:white; padding:5px 10px; border-radius:20px; font-size:12px; margin-left:10px; }
        .scholarship-badge { background:#17a2b8; color:white; padding:5px 10px; border-radius:20px; font-size:12px; margin-left:10px; }
        .book-warning { background-color:#fff3cd; color:#856404; border:1px solid #ffeaa7; padding:10px; border-radius:8px; margin:10px 0; }
        .permit-details { background-color:#e7f3ff; padding:10px; border-radius:8px; margin:10px 0; border-left:4px solid #0d6efd; }
        .association-warning { background-color:#fff3cd; color:#856404; border:1px solid #ffeaa7; padding:10px; border-radius:8px; margin:10px 0; }
        .association-summary { background-color:#f8f9fa; padding:10px; border-radius:8px; margin:10px 0; border-left:4px solid #17a2b8; }
        @media (max-width: 768px) { .percentage-circle { width:80px; height:80px; font-size:16px; } }
    </style>
</head>
<body>
    <?php include "../include/nav.php";?>

<div class="content" style="padding:10px;">
    <div class="mobile-container" style="">
        <div class="main-page">
            <div class="content-section">
                <!-- Status Card -->
                <div class="status-card <?php 
                    if ($clearanceStatus['clear'] && $clearanceStatus['is_fully_sponsored']) {
                        echo 'status-scholarship';
                    } elseif ($clearanceStatus['clear']) {
                        echo 'status-cleared';
                    } elseif ($permissionStatus['has_permission']) {
                        echo 'status-permitted';
                    } else {
                        echo 'status-not-cleared';
                    }
                ?>">
                    <div class="percentage-circle">
                        <?php echo htmlspecialchars($clearanceStatus['percentage']); ?>%
                    </div>
                    <h3>
                        <?php 
                        if ($clearanceStatus['clear'] && $clearanceStatus['is_fully_sponsored']) {
                            echo 'FULLY SPONSORED - FEES CLEARED';
                        } elseif ($clearanceStatus['clear']) {
                            echo 'FEES CLEARED';
                        } elseif ($permissionStatus['has_permission']) {
                            echo 'SPECIAL PERMISSION GRANTED';
                        } else {
                            echo 'FEES NOT CLEARED';
                        }
                        ?>
                    </h3>
                    <p class="mb-4">
                        <?php 
                        if ($clearanceStatus['clear'] && $clearanceStatus['is_fully_sponsored']) {
                            echo 'You have ' . htmlspecialchars($scholarship) . '% scholarship covering all fees.';
                        } elseif ($clearanceStatus['clear']) {
                            echo 'You have paid ' . htmlspecialchars($clearanceStatus['percentage']) . '% of your required fees.';
                        } elseif ($permissionStatus['has_permission']) {
                            echo 'You have been granted special permission by ' . htmlspecialchars($permissionStatus['permitted_by']) . '.';
                            if ($permissionStatus['days_valid'] > 0 && $permissionStatus['days_valid'] < 999) {
                                echo ' Valid for ' . htmlspecialchars($permissionStatus['days_valid']) . ' more days.';
                            } elseif ($permissionStatus['days_valid'] == 999) {
                                echo ' No expiry date.';
                            }
                        } else {
                            echo 'You need to pay at least ' . htmlspecialchars($maxpay) . '% of your fees to get clearance.';
                        }
                        ?>
                    </p>
                    
                    <!-- Show permit information if available -->
                    <?php if ($permissionStatus['has_permission']): ?>
                    <div class="permit-details">
                        <strong><i class="fas fa-id-card me-2"></i>Permission Details:</strong><br>
                        <small>
                            Granted by: <?php echo htmlspecialchars($permissionStatus['permitted_by']); ?><br>
                            Issued: <?php echo htmlspecialchars(date('F j, Y', strtotime($permissionStatus['created_date']))); ?><br>
                            <?php if ($permissionStatus['expiry_date'] != 'No Expiry'): ?>
                                Expires: <?php echo htmlspecialchars(date('F j, Y', strtotime($permissionStatus['expiry_date']))); ?><br>
                                Days Remaining: <?php echo htmlspecialchars($permissionStatus['days_valid']); ?>
                            <?php else: ?>
                                Status: No Expiry<br>
                                This permission is valid until revoked.
                            <?php endif; ?>
                        </small>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Check for outstanding books -->
                    <?php if ($bookReturnStatus['has_outstanding_books']): ?>
                    <div class="book-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Library Books Outstanding:</strong> You have <?php echo $bookReturnStatus['outstanding_count']; ?> book(s) not returned.
                        Please return all library books before downloading clearance certificate.
                    </div>
                    <?php endif; ?>
                    
                    <!-- Check for association fees -->
                    <?php if ($associationStatus['has_association_balance']): ?>
                    <div class="association-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Association Fees Outstanding:</strong> You have K<?php echo number_format($associationStatus['balance'], 2); ?> association fees balance.
                        Please clear all association fees before downloading clearance certificate.
                    </div>
                    <?php endif; ?>
                    
                    <!-- Payment Summary Table -->
                    <div class="payment-summary">
                        <div class="table-responsive">
                            <table>
                                <tr>
                                    <th>Description</th>
                                    <th>Amount (ZMW)</th>
                                </tr>
                                <tr>
                                    <td>Original Tuition Fees:</td>
                                    <td><?php echo number_format($clearanceStatus['original_fees'], 2); ?></td>
                                </tr>
                                <?php if ($clearanceStatus['scholarship_amount'] > 0): ?>
                                <tr>
                                    <td>Scholarship (<?php echo htmlspecialchars($scholarship); ?>%):</td>
                                    <td>-<?php echo number_format($clearanceStatus['scholarship_amount'], 2); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Net Tuition Fees Payable:</strong></td>
                                    <td><strong><?php echo number_format($clearanceStatus['total_fees'], 2); ?></strong></td>
                                </tr>
                                <?php endif; ?>
                                <tr>
                                    <td>Tuition Fees Paid:</td>
                                    <td><?php echo number_format($clearanceStatus['total_paid'], 2); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Tuition Balance:</strong></td>
                                    <td><strong><?php echo number_format($clearanceStatus['balance'], 2); ?></strong></td>
                                </tr>
                                <?php if ($clearanceStatus['is_fully_sponsored']): ?>
                                <tr>
                                    <td colspan="2" style="background:#d1ecf1; color:#0c5460; text-align:center; font-weight:bold;">
                                        <i class="fas fa-award me-1"></i> FULLY SPONSORED - NO TUITION PAYMENT REQUIRED
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Association Fees Summary -->
                    <?php if ($associationStatus['total_invoice'] > 0): ?>
                    <div class="association-summary">
                        <h6><i class="fas fa-users me-2"></i>Association Fees Summary</h6>
                        <div class="table-responsive">
                            <table>
                                <tr>
                                    <th>Description</th>
                                    <th>Amount (ZMW)</th>
                                </tr>
                                <tr>
                                    <td>Total Association Invoices:</td>
                                    <td><?php echo number_format($associationStatus['total_invoice'], 2); ?></td>
                                </tr>
                                <tr>
                                    <td>Association Fees Paid:</td>
                                    <td><?php echo number_format($associationStatus['total_paid'], 2); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Association Balance:</strong></td>
                                    <td><strong><?php echo number_format($associationStatus['balance'], 2); ?></strong></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Download Section -->
                <div class="status-card">
                    <h4>
                        <i class="fas fa-download me-2"></i>Download Clearance
                        <?php if ($permissionStatus['has_permission']): ?>
                            <span class="permission-badge">Special Permission</span>
                        <?php endif; ?>
                        <?php if ($clearanceStatus['is_fully_sponsored']): ?>
                            <span class="scholarship-badge"><?php echo htmlspecialchars($scholarship); ?>% Scholarship</span>
                        <?php endif; ?>
                    </h4>
                    <p class="mb-4">Download your official fee clearance certificate for academic purposes.</p>
                    
                    <?php if ($canAccessCertificate): ?>
                        <div class="d-flex justify-content-center">
                            <button hidden id="download-pdf" class="btn btn-download">
                                <i class="fas fa-file-pdf me-2"></i>Download PDF Certificate
                            </button>
                        </div>
                        
                        <div class="d-flex justify-content-center mt-3">
                            <a href="?view=certificate" class="btn btn-danger">
                                <i class="fas fa-eye me-2"></i>View Certificate
                            </a>
                        </div>
                        
                        <!-- Barcode for scanning -->
                        <div class="barcode-container">
                            <p class="mb-2"><small>Scan this barcode to verify clearance status</small></p>
                            <svg id="barcode" class="barcode"></svg>
                            <div style="font-size:10px;margin-top:5px;">Document ID: <?php echo htmlspecialchars($documentID); ?> | Code: <?php echo htmlspecialchars($securityCode); ?></div>
                        </div>
                        
                        <p class="mt-3 text-muted text-center">
                            <small>
                                <?php if ($permissionStatus['has_permission']): ?>
                                    <?php if ($permissionStatus['expiry_date'] == 'No Expiry'): ?>
                                        This permission-based clearance has no expiry date.
                                    <?php else: ?>
                                        This temporary clearance is valid until <?php echo htmlspecialchars(date('F j, Y', strtotime($expiryDate))); ?>.
                                    <?php endif; ?>
                                <?php elseif ($clearanceStatus['is_fully_sponsored']): ?>
                                    This clearance is valid as long as your scholarship remains active.
                                <?php else: ?>
                                    This document is officially recognized by the university.
                                <?php endif; ?>
                            </small>
                        </p>
                    <?php else: ?>
                        <div class="d-flex justify-content-center">
                            <button class="btn btn-download" disabled>
                                <i class="fas fa-times-circle me-2"></i>Not Eligible
                            </button>
                        </div>
                        <p class="mt-3 text-danger text-center">
                            <small>
                                <?php if ($bookReturnStatus['has_outstanding_books']): ?>
                                    You need to return all library books (<?php echo $bookReturnStatus['outstanding_count']; ?> outstanding) to download clearance certificate.
                                <?php elseif ($associationStatus['has_association_balance']): ?>
                                    You need to clear all association fees (K<?php echo number_format($associationStatus['balance'], 2); ?> balance) to download clearance certificate.
                                <?php elseif ($scholarship == 100): ?>
                                    <!-- Special case for 100% scholarship - should be eligible -->
                                    You are fully sponsored. Please contact the scholarship office if you see this message.
                                <?php else: ?>
                                    You need to either:
                                    <ul class="text-start mt-2">
                                        <li>Pay at least <?php echo htmlspecialchars($maxpay); ?>% of your fees, OR</li>
                                        <li>Obtain special permission from administration</li>
                                    </ul>
                                <?php endif; ?>
                            </small>
                        </p>
                    <?php endif; ?>
                </div>
                
                <div class="info-section">
                    <h5><i class="fas fa-info-circle me-2"></i>Important Information</h5>
                    <ul>
                        <li>The clearance certificate requires ALL of the following:
                            <ul>
                                <li>Tuition fees: Paid at least <?php echo htmlspecialchars($maxpay); ?>% OR have special permission OR full scholarship</li>
                                <li>Association fees: All association fees must be fully paid</li>
                                <li>Library: All borrowed books must be returned</li>
                            </ul>
                        </li>
                        <li>All library books must be returned before downloading the clearance certificate</li>
                        <li>All association fees must be cleared (zero balance)</li>
                        <li>This document is required for exam registration and other academic purposes</li>
                        <li>The downloaded document contains security features to prevent tampering</li>
                        <li>For any fee-related issues, please contact the accounts office</li>
                        <?php if ($permissionStatus['has_permission']): ?>
                            <li><strong>Special Permission:</strong> Granted by <?php echo htmlspecialchars($permissionStatus['permitted_by']); ?>
                                <?php if ($permissionStatus['expiry_date'] != 'No Expiry'): ?>
                                    | Valid until: <?php echo htmlspecialchars(date('F j, Y', strtotime($permissionStatus['expiry_date']))); ?>
                                <?php else: ?>
                                    | No expiry date
                                <?php endif; ?>
                            </li>
                        <?php endif; ?>
                        <?php if ($clearanceStatus['is_fully_sponsored']): ?>
                            <li><strong>Scholarship Information:</strong> Your scholarship covers <?php echo htmlspecialchars($scholarship); ?>% of tuition fees. No payment is required.</li>
                        <?php endif; ?>
                        <?php if ($bookReturnStatus['has_outstanding_books']): ?>
                            <li><strong>Library Alert:</strong> You have <?php echo $bookReturnStatus['outstanding_count']; ?> outstanding book(s) - return them to the library</li>
                        <?php endif; ?>
                        <?php if ($associationStatus['has_association_balance']): ?>
                            <li><strong>Association Alert:</strong> You have K<?php echo number_format($associationStatus['balance'], 2); ?> association fees balance - pay to the association office</li>
                        <?php endif; ?>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- Certificate Page -->
        <div class="certificate-page">
            <div class="header">
                <h1><i class="fas fa-certificate me-2"></i>Clearance Certificate</h1>
                <p>Official fee clearance document</p>
            </div>
            
            <div class="nav-buttons">
                <a href="?" class="nav-btn"><i class="fas fa-arrow-left me-1"></i> Back</a>
                <button id="download-certificate-pdf" class="nav-btn" style="background:#13700bdc; border:none;"><i class="fas fa-download me-1"></i> Download</button>
            </div>
            
            <div class="certificate-container">
                <div class="watermark"><img src="logo.png" width="200px" alt="logo"/></div>
                
                <div class="certificate-header">
                    <div class="university-name" style="color:#13700bdc; border:none;"><?php echo htmlspecialchars($sname); ?></div>
                    <div class="office-name">OFFICE OF THE ACCOUNTANT</div>
                </div>
                
                <div class="certificate-title">FEE CLEARANCE CERTIFICATE</div>

                <div class="student-info">
                    <div class="info-row"><span class="info-label">Student ID:</span> <?php echo htmlspecialchars($student['studentid'] ?? $userlogin); ?></div>
                    <div class="info-row"><span class="info-label">Full Name:</span> <?php echo htmlspecialchars($student['studentname'] ?? ''); ?></div>
                    <div class="info-row"><span class="info-label">Program:</span> <?php echo htmlspecialchars($student['program'] ?? $program); ?></div>
                    <div class="info-row"><span class="info-label">Intake:</span> <?php echo htmlspecialchars($student['intake'] ?? $intake); ?></div>
                </div>
                
                <?php if ($clearanceStatus['is_fully_sponsored']): ?>
                <div class="status-scholarship-pdf">
                    FULLY SPONSORED - FEES CLEARED<br>
                    This student has <?php echo htmlspecialchars($scholarship); ?>% scholarship covering all tuition fees and is eligible to sit for examinations.
                    <?php if ($associationStatus['total_paid'] > 0): ?>
                    <br>Association fees: Fully paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)
                    <?php endif; ?>
                </div>
                <?php elseif ($clearanceStatus['clear']): ?>
                <div class="status-cleared-pdf">
                    FEE STATUS: CLEARED<br>
                    This student has paid <?php echo htmlspecialchars($clearanceStatus['percentage']); ?>% of the required tuition fees and is eligible to sit for examinations.
                    <?php if ($associationStatus['total_paid'] > 0): ?>
                    <br>Association fees: Fully paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)
                    <?php endif; ?>
                </div>
                <?php else: ?>
                <div class="status-permitted-pdf">
                    SPECIAL PERMISSION GRANTED<br>
                    This student has been granted special permission by <?php echo htmlspecialchars($permissionStatus['permitted_by']); ?>.<br>
                    <?php if ($expiryDate && $expiryDate != 'No Expiry'): ?>
                    Valid until: <?php echo htmlspecialchars(date('F j, Y', strtotime($expiryDate))); ?>
                    <?php endif; ?>
                    <?php if ($associationStatus['total_paid'] > 0): ?>
                    <br>Association fees: Fully paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <!-- Course List Table -->
                <h5>Course List</h5>
                <div class="table-responsive">
                    <table class="certificate-table">
                        <tr>
                            <th>Course</th>
                            <th>Student Signature</th>
                            <th>Invigilator Signature</th>
                            <th>Date</th>
                        </tr>
                        <?php
                        $currentYear1 = date("Y");
                        // Query to get current semester courses for the certificate view
                        $courseQueryCert = "SELECT * FROM results 
                            WHERE studentid = '" . mysqli_real_escape_string($conn, $userlogin) . "' 
                            AND year = '$currentYear1'
                            AND term = '" . mysqli_real_escape_string($conn, $currentSemester) . "'
                            ORDER BY course ASC";
                        $courseResultCert = mysqli_query($conn, $courseQueryCert);
                        if ($courseResultCert && mysqli_num_rows($courseResultCert) > 0) {
                            while ($c = mysqli_fetch_assoc($courseResultCert)) {
                                echo '<tr>
                                        <td>'.htmlspecialchars($c['course']).'</td>
                                        <td></td>
                                        <td></td>
                                        <td><strong>........../......./.............</strong></td>
                                      </tr>';
                            }
                        } else {
                            echo '<tr><td colspan="4">No courses found for the current term.</td></tr>';
                        }
                        ?>
                    </table>
                </div>
                
                <!-- Barcode in Certificate -->
                <div style="max-width:100%; padding:10px;">
                    <div class="barcode-pdf">
                        <svg id="barcode-certificate"></svg>
                        <div style="font-size:10px; margin-top:5px;">Verification Code: <?php echo htmlspecialchars($documentID . ' | ' . $securityCode); ?></div>
                    </div>
                </div>
              
                <div class="signature-container">
                    <div>Date: <?php echo date('F j, Y'); ?></div>
                    <div class="signature-label">Signature of Accountant</div>
                </div>
                
                <div class="security-features">
                    <div>Document ID: <?php echo htmlspecialchars($documentID); ?></div>
                    <div>Security Code: <?php echo htmlspecialchars($securityCode); ?></div>
                    <?php if ($clearanceStatus['is_fully_sponsored']): ?>
                        <div>Scholarship: <?php echo htmlspecialchars($scholarship); ?>% | Fully Sponsored</div>
                    <?php elseif ($permissionStatus['has_permission']): ?>
                        <div>Permission: <?php echo htmlspecialchars($permissionStatus['permitted_by']); ?> 
                            <?php if ($expiryDate && $expiryDate != 'No Expiry'): ?>
                                | Valid until: <?php echo htmlspecialchars(date('F j, Y', strtotime($expiryDate))); ?>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    <?php if ($associationStatus['total_paid'] > 0): ?>
                        <div>Association Fees: Fully Paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <button class="next-page-btn" onclick="window.scrollTo(0,0)"><i class="fas fa-arrow-up"></i></button>
    </div>

    <!-- Hidden certificate container for PDF generation -->
    <div id="certificate-container" style="display: none; padding:20px">
        <div class="certificate" style="margin-top:-20px">
            <div class="watermark"><img src="logo.png" width="200px" alt="logo"/> SECURE DOCUMENT</div>
            <div class="certificate-header">
                <img src="logo.png" width="100px" alt="logo"/>
                <div class="university-name"><?php echo htmlspecialchars($sname); ?></div>
                <div class="office-name">OFFICE OF THE ACCOUNTANT</div>
            </div>
            <div class="certificate-title" style="margin-top:-20px">FEE CLEARANCE CERTIFICATE</div>
            <div class="student-info">
                <div class="info-row" style="margin-top:-20px"><?php echo htmlspecialchars($student['studentid'] ?? $userlogin); ?> | <?php echo htmlspecialchars($student['studentname'] ?? ''); ?> | <?php echo htmlspecialchars($student['program'] ?? $program); ?> | <?php echo htmlspecialchars($student['intake'] ?? $intake); ?></div>
            </div>
            
            <?php if ($expiryDate && $expiryDate != 'No Expiry'): ?>
            <span style="background:red; color:white; padding:5px; border-radius:5px;">Expires On: <?php echo htmlspecialchars(date('F j, Y', strtotime($expiryDate))); ?></span>
            <?php endif; ?>
            
            <?php if ($clearanceStatus['is_fully_sponsored']): ?>
            <div class="status-scholarship-pdf" style="width:99%;">This student has <?php echo htmlspecialchars($scholarship); ?>% scholarship covering all tuition fees and is eligible to sit for examinations.
                <?php if ($associationStatus['total_paid'] > 0): ?>
                <br>Association fees: Fully paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)
                <?php endif; ?>
            </div>
            <?php elseif ($clearanceStatus['clear']): ?>
            <div class="status-cleared-pdf" style="width:99%;">This student has paid <?php echo htmlspecialchars($clearanceStatus['percentage']); ?>% of the required tuition fees and is eligible to sit for examinations.
                <?php if ($associationStatus['total_paid'] > 0): ?>
                <br>Association fees: Fully paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)
                <?php endif; ?>
            </div>
            <?php else: ?>
            <div class="status-permitted-pdf" style="width:99%;">SPECIAL PERMISSION: Granted by <?php echo htmlspecialchars($permissionStatus['permitted_by']); ?>
                <?php if ($expiryDate && $expiryDate != 'No Expiry'): ?>
                    . Valid until: <?php echo htmlspecialchars(date('F j, Y', strtotime($expiryDate))); ?>
                <?php endif; ?>
                <?php if ($associationStatus['total_paid'] > 0): ?>
                <br>Association fees: Fully paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <div class="table-responsive" style="margin-top:-20px">
                <table class="certificate-table">
                    <tr>
                        <th>Course</th>
                        <th>Student Signature</th>
                        <th>Invigilator Signature</th>
                        <th>Chief Invigilator</th>
                        <th>Date</th>
                    </tr>
                    <?php
                        // reuse the same course query used above for the certificate
                        $courseResultPdf = mysqli_query($conn, $courseQueryCert);
                        if ($courseResultPdf && mysqli_num_rows($courseResultPdf) > 0) {
                            while ($c = mysqli_fetch_assoc($courseResultPdf)) {
                                echo '<tr>
                                        <td>'.htmlspecialchars($c['course']).'</td>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                        <td><strong>........../......./.............</strong></td>
                                      </tr>';
                            }
                        } else {
                            echo '<tr><td colspan="5">No courses found for the current term.</td></tr>';
                        }
                    ?>
                </table>
            </div>
            <p>Student................Chief Invigilator......................HOD........................Dean........................Registrar...................</p>
            <div class="barcode-pdf" style="width:100%; padding:10px; margin-top:10px;">
                <svg id="barcode-pdf"></svg>
                <div style="font-size:10px; margin-top:5px;">Verification Code: <?php echo htmlspecialchars($documentID . ' | ' . $securityCode); ?></div>
            </div>
            
            <div class="signature-container" style="margin-top:-20px">
                <div>Date: <?php echo date('F j, Y'); ?></div>
                <img src="sign.png" width="120px" alt="sign"/>
                <div class="signature-label">Signature of Accountant</div>
            </div>
            
            <div class="security-features" style="margin-top:-20px">
                <div>Document ID: <?php echo htmlspecialchars($documentID); ?></div>
                <div>Security Code: <?php echo htmlspecialchars($securityCode); ?></div>
                <?php if ($clearanceStatus['is_fully_sponsored']): ?>
                    <div>Scholarship: <?php echo htmlspecialchars($scholarship); ?>% | Fully Sponsored</div>
                <?php elseif ($permissionStatus['has_permission']): ?>
                    <div>Permission: <?php echo htmlspecialchars($permissionStatus['permitted_by']); ?> 
                        <?php if ($expiryDate && $expiryDate != 'No Expiry'): ?>
                            | Valid until: <?php echo htmlspecialchars(date('F j, Y', strtotime($expiryDate))); ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <?php if ($associationStatus['total_paid'] > 0): ?>
                    <div>Association Fees: Fully Paid (K<?php echo number_format($associationStatus['total_paid'], 2); ?>)</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if ($canAccessCertificate): ?>
    // Prepare barcode data
    const barcodeData = "<?php echo addslashes($documentID . '|' . $securityCode . '|' . $userlogin . '|' . date('Ymd')); ?>";

    // Generate barcode on main page
    if (typeof JsBarcode !== 'undefined') {
        JsBarcode("#barcode", barcodeData, {
            format: "CODE128",
            lineColor: "#13700bdc",
            width: 2,
            height: 40,
            displayValue: true
        });

        JsBarcode("#barcode-certificate", barcodeData, {
            format: "CODE128",
            lineColor: "#000",
            width: 1,
            height: 40,
            displayValue: true
        });

        JsBarcode("#barcode-pdf", barcodeData, {
            format: "CODE128",
            lineColor: "#000",
            width: 2,
            height: 40,
            displayValue: true
        });
    }

    // Helper to convert certificate fragment into downloadable PDF
    function downloadPDF(button) {
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Generating PDF...';
        button.disabled = true;

        // Show the hidden container briefly for html2pdf rendering
        const certificateElement = document.querySelector('#certificate-container .certificate');

        const options = {
            margin: 10,
            filename: 'clearance_certificate_<?php echo addslashes($userlogin); ?>.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: {
                scale: 3,
                useCORS: true,
                logging: false
            },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        };

        html2pdf().set(options).from(certificateElement).save().then(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }).catch((error) => {
            console.error('PDF generation error:', error);
            button.innerHTML = originalText;
            button.disabled = false;
            alert('An error occurred while generating the PDF. Please try again.');
        });
    }

    // Wire up download buttons
    const downloadBtn = document.getElementById('download-pdf');
    if (downloadBtn) {
        downloadBtn.addEventListener('click', function() {
            downloadPDF(this);
        });
    }
    const downloadCertBtn = document.getElementById('download-certificate-pdf');
    if (downloadCertBtn) {
        downloadCertBtn.addEventListener('click', function() {
            downloadPDF(this);
        });
    }

    // Save certificate record via AJAX (non-blocking)
    fetch('save_certificate.php', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            studentid: '<?php echo addslashes($userlogin); ?>',
            document_id: '<?php echo addslashes($documentID); ?>',
            security_code: '<?php echo addslashes($securityCode); ?>',
            generated_on: '<?php echo addslashes($generatedOn); ?>',
            expiry_date: '<?php echo addslashes($expiryDate); ?>',
            permission_granted: <?php echo $permissionStatus['has_permission'] ? 'true' : 'false'; ?>,
            permitted_by: '<?php echo addslashes($permissionStatus['permitted_by']); ?>',
            scholarship_percentage: <?php echo $scholarship; ?>,
            book_clearance: <?php echo !$bookReturnStatus['has_outstanding_books'] ? 'true' : 'false'; ?>,
            association_clearance: <?php echo !$associationStatus['has_association_balance'] ? 'true' : 'false'; ?>,
            clearance_type: '<?php echo $permissionStatus['has_permission'] ? 'permit' : ($clearanceStatus['is_fully_sponsored'] ? 'scholarship' : 'regular'); ?>'
        })
    })
    .then(res => res.json().catch(() => ({})))
    .then(data => console.log('save_certificate response', data))
    .catch(err => console.error('save_certificate error', err));
    <?php endif; ?>

    // Show/hide scroll to top button
    window.addEventListener('scroll', function() {
        const scrollBtn = document.querySelector('.next-page-btn');
        if (window.scrollY > 300) {
            scrollBtn.style.display = 'flex';
        } else {
            scrollBtn.style.display = 'none';
        }
    });

    // Basic client-side protection (non-blocking)
    document.addEventListener("contextmenu", function(e) { /*e.preventDefault();*/ });
    document.addEventListener("keydown", function(e) {
        if (e.key === "F12" || (e.ctrlKey && e.shiftKey && (e.key === "I" || e.key === "J")) || (e.ctrlKey && e.key === "U")) {
            // allowed for debugging; remove restrictions if you want to disable
        }
    });
});
</script>
                <br><br><br><br>

</body>
</html>