<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

$pdo = getDB();
$message = '';
$certificate_data = null;

// ============================================
// HELPER FUNCTIONS WITH DUPLICATE GUARDS
// ============================================
if (!function_exists('sanitize')) {
    function sanitize($input) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('logActivity')) {
    function logActivity($cert_id, $action, $user_id) {
        // Basic log stub
    }
}

// ============================================
// PURE PHP CODE 128 BARCODE GENERATOR
// ============================================
function generateCode128Barcode($registration_no) {
    $code128_map = [
        ' ' => 0, '!' => 1, '"' => 2, '#' => 3, '$' => 4, '%' => 5, '&' => 6, "'" => 7,
        '(' => 8, ')' => 9, '*' => 10, '+' => 11, ',' => 12, '-' => 13, '.' => 14, '/' => 15,
        '0' => 16, '1' => 17, '2' => 18, '3' => 19, '4' => 20, '5' => 21, '6' => 22, '7' => 23,
        '8' => 24, '9' => 25, ':' => 26, ';' => 27, '<' => 28, '=' => 29, '>' => 30, '?' => 31,
        '@' => 32, 'A' => 33, 'B' => 34, 'C' => 35, 'D' => 36, 'E' => 37, 'F' => 38, 'G' => 39,
        'H' => 40, 'I' => 41, 'J' => 42, 'K' => 43, 'L' => 44, 'M' => 45, 'N' => 46, 'O' => 47,
        'P' => 48, 'Q' => 49, 'R' => 50, 'S' => 51, 'T' => 52, 'U' => 53, 'V' => 54, 'W' => 55,
        'X' => 56, 'Y' => 57, 'Z' => 58, '[' => 59, '\\' => 60, ']' => 61, '^' => 62, '_' => 63,
        '`' => 64, 'a' => 65, 'b' => 66, 'c' => 67, 'd' => 68, 'e' => 69, 'f' => 70, 'g' => 71,
        'h' => 72, 'i' => 73, 'j' => 74, 'k' => 75, 'l' => 76, 'm' => 77, 'n' => 78, 'o' => 79,
        'p' => 80, 'q' => 81, 'r' => 82, 's' => 83, 't' => 84, 'u' => 85, 'v' => 86, 'w' => 87,
        'x' => 88, 'y' => 89, 'z' => 90, '{' => 91, '|' => 92, '}' => 93, '~' => 94
    ];
    
    $patterns = [
        '212222', '222122', '222221', '121223', '121322', '131222', '122213', '122312', '132212', '221213',
        '221312', '231212', '112232', '122132', '122231', '113222', '123122', '123221', '223211', '221132',
        '221231', '213212', '223112', '312131', '311222', '321122', '321221', '312212', '322112', '322211',
        '212123', '212321', '232121', '111323', '131123', '131321', '112313', '132113', '132311', '211313',
        '231113', '231311', '112133', '112331', '132131', '113123', '113321', '133121', '313121', '211331',
        '231131', '213113', '213311', '213131', '311123', '311321', '331121', '312113', '312311', '332111',
        '314111', '221411', '431111', '111224', '111422', '121124', '121421', '141122', '141221', '112214',
        '112412', '122114', '122411', '142112', '142211', '241211', '221114', '413111', '241112', '134111',
        '111242', '121142', '121241', '114212', '124112', '124211', '411212', '421112', '421211', '212141',
        '214121', '412121', '111143', '111341', '131141', '114113', '114311', '411113', '411311', '113141',
        '114131', '311141', '411131', '211412', '211214', '211232', '233111', '211112', '111211'
    ];
    
    $start_code = 104; // Code B default start
    $bars = $patterns[$start_code];
    $sum = $start_code;
    
    for ($i = 0; $i < strlen($registration_no); $i++) {
        $char = $registration_no[$i];
        $val = $code128_map[$char] ?? 0;
        $sum += $val * ($i + 1);
        $bars .= $patterns[$val];
    }
    
    $check_digit = $sum % 103;
    $bars .= $patterns[$check_digit];
    $bars .= '2331112'; // Stop pattern
    
    $width = 300;
    $height = 60;
    $img = imagecreatetruecolor($width, $height);
    
    $white = imagecolorallocate($img, 255, 255, 255);
    $black = imagecolorallocate($img, 0, 0, 0);
    
    imagefill($img, 0, 0, $white);
    
    $x = 10;
    $y = 5;
    $bar_height = 48;
    $module_width = 2;
    
    for ($i = 0; $i < strlen($bars); $i++) {
        $w = (int)$bars[$i];
        if ($i % 2 === 0) {
            imagefilledrectangle($img, $x, $y, $x + ($w * $module_width) - 1, $y + $bar_height, $black);
        }
        $x += $w * $module_width;
    }
    
    ob_start();
    imagepng($img);
    $barcode_data = ob_get_clean();
    imagedestroy($img);
    
    return base64_encode($barcode_data);
}

// ============================================
// SCANNABLE QR CODE GENERATOR
// ============================================
function generateQRCode($data) {
    $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=".urlencode($data);
    $qr_image = @file_get_contents($qr_url);
    
    if ($qr_image !== false) {
        return base64_encode($qr_image);
    }
    
    // GD Fallback Frame
    $img = imagecreatetruecolor(200, 200);
    $white = imagecolorallocate($img, 255, 255, 255);
    $black = imagecolorallocate($img, 0, 0, 0);
    imagefill($img, 0, 0, $white);
    imagestring($img, 2, 20, 90, "QR API Unavailable", $black);
    
    ob_start();
    imagepng($img);
    $qr_data = ob_get_clean();
    imagedestroy($img);
    return base64_encode($qr_data);
}

// Function to extract and format QR data
function prepareQRData($certificate, $user_email, $user_name) {
    return [
        'certificate_info' => [
            'registration_no' => $certificate['registration_no'],
            'certificate_no' => $certificate['certificate_no'],
            'student_name' => $certificate['name'],
            'father_name' => $certificate['father_name'],
            'mother_name' => $certificate['mother_name'],
            'degree' => $certificate['degree'],
            'gpa' => $certificate['grade_point_average'],
            'year_of_passing' => $certificate['year_of_passing'],
            'faculty' => $certificate['faculty'],
            'gender' => $certificate['gender']
        ],
        'generation_info' => [
            'generated_by' => $user_email,
            'generated_by_name' => $user_name,
            'generated_date' => date('Y-m-d H:i:s'),
            'generated_timestamp' => time(),
            'generated_ip' => $_SERVER['REMOTE_ADDR']
        ],
        'verification' => [
            'verify_url' => (defined('APP_URL') ? APP_URL : 'https://www.osrskuast.net') . '/verify_certificate.php?cert_no=' . $certificate['certificate_no'],
            'issued_by' => 'SKUAST-K University',
            'status' => $certificate['certificate_status']
        ]
    ];
}

// Handle search
if (isset($_POST['search']) && !empty($_POST['registration_no'])) {
    $registration_no = sanitize($_POST['registration_no']);
    try {
        $stmt = $pdo->prepare("SELECT * FROM certificates WHERE registration_no = ?");
        $stmt->execute([$registration_no]);
        $certificate_data = $stmt->fetch();
        
        if (!$certificate_data) {
            $message = '<div class="error">No certificate found with registration number: ' . htmlspecialchars($registration_no) . '</div>';
        }
    } catch(PDOException $e) {
        $message = '<div class="error">Database error: ' . $e->getMessage() . '</div>';
        error_log("Search error: " . $e->getMessage());
    }
}

// Handle GET request with registration number
if (isset($_GET['reg']) && empty($_POST)) {
    $registration_no = sanitize($_GET['reg']);
    try {
        $stmt = $pdo->prepare("SELECT * FROM certificates WHERE registration_no = ?");
        $stmt->execute([$registration_no]);
        $certificate_data = $stmt->fetch();
        
        if (!$certificate_data) {
            $message = '<div class="error">No certificate found with registration number: ' . htmlspecialchars($registration_no) . '</div>';
        }
    } catch(PDOException $e) {
        $message = '<div class="error">Database error: ' . $e->getMessage() . '</div>';
        error_log("Search error: " . $e->getMessage());
    }
}

// Handle certificate generation
if (isset($_POST['generate']) && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM certificates WHERE id = ?");
        $stmt->execute([$id]);
        $cert = $stmt->fetch();
        
        if ($cert) {
            // Get user info for QR code
            $user_stmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
            $user_stmt->execute([$_SESSION['user_id']]);
            $user = $user_stmt->fetch();
            
            // Prepare data for QR code with all vital information
            $qr_data = prepareQRData(
                $cert, 
                $_SESSION['user_email'] ?? $user['email'] ?? 'Unknown', 
                $_SESSION['user_name'] ?? $user['full_name'] ?? 'Unknown'
            );
            
            // Generate QR code with full data
            $qr_code = generateQRCode(json_encode($qr_data));
            
            // Generate barcode depicting registration number
            $barcode = generateCode128Barcode($cert['registration_no']);
            
            // Update certificate with barcode and QR code
            $update_sql = "UPDATE certificates SET 
                barcode = ?,
                qr_code = ?,
                certificate_status = 'generated',
                generated_by = ?,
                generated_date = NOW()
                WHERE id = ?";
            
            $stmt = $pdo->prepare($update_sql);
            if ($stmt->execute([$barcode, $qr_code, $_SESSION['user_id'], $id])) {
                logActivity($id, 'generated', $_SESSION['user_id']);
                $message = '<div class="success">✅ Certificate generated successfully!<br>
                    <small>Barcode depicts registration number: ' . htmlspecialchars($cert['registration_no']) . '<br>
                    QR Code contains all certificate data with generator information</small></div>';
                
                // Refresh data
                $stmt = $pdo->prepare("SELECT * FROM certificates WHERE id = ?");
                $stmt->execute([$id]);
                $certificate_data = $stmt->fetch();
            }
        }
    } catch(Exception $e) {
        $message = '<div class="error">Error generating certificate: ' . $e->getMessage() . '</div>';
        error_log("Certificate generation error: " . $e->getMessage());
    }
}

// Get generator user info
$generated_by_user = null;
if ($certificate_data && !empty($certificate_data['generated_by'])) {
    try {
        $stmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
        $stmt->execute([$certificate_data['generated_by']]);
        $generated_by_user = $stmt->fetch();
    } catch(PDOException $e) {
        error_log("Error fetching user: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Certificate - SKUAST-K Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Stencil&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Times New Roman', Times, serif; background: #f0f0f0; }
        
        .sidebar { width: 250px; background: #1a202c; color: white; height: 100vh; position: fixed; padding: 20px 0; overflow-y: auto; font-family: 'Segoe UI', sans-serif; z-index: 1000; }
        .sidebar h2 { padding: 0 20px 20px; border-bottom: 1px solid #4a5568; font-size: 18px; }
        .sidebar .user-info { padding: 20px; border-bottom: 1px solid #4a5568; margin-bottom: 20px; }
        .sidebar .user-info .name { font-weight: bold; font-size: 16px; }
        .sidebar .user-info .email { font-size: 12px; color: #a0aec0; }
        .sidebar a { display: block; padding: 12px 20px; color: #a0aec0; text-decoration: none; transition: all 0.3s; }
        .sidebar a:hover, .sidebar a.active { background: #4a5568; color: white; }
        .sidebar a i { width: 20px; margin-right: 10px; }
        
        .main-content { margin-left: 250px; padding: 30px; }
        .header { background: white; padding: 20px 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; font-family: 'Segoe UI', sans-serif; }
        .header h1 { font-size: 24px; color: #2d3748; }
        .search-section { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); margin-bottom: 20px; font-family: 'Segoe UI', sans-serif; }
        
        .btn { background: #667eea; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-size: 14px; transition: all 0.3s; text-decoration: none; display: inline-block; font-family: 'Segoe UI', sans-serif; }
        .btn:hover { background: #5a67d8; }
        .btn-secondary { background: #718096; }
        .btn-secondary:hover { background: #4a5568; }
        .btn-success { background: #38a169; }
        .btn-success:hover { background: #2f855a; }
        .btn-warning { background: #d69e2e; }
        .btn-warning:hover { background: #b7791f; }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; }
        
        .error { background: #fee; color: #c33; padding: 12px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #c33; font-family: 'Segoe UI', sans-serif; }
        .success { background: #efe; color: #2d7d2d; padding: 12px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #2d7d2d; font-family: 'Segoe UI', sans-serif; }
        
        .certificate-preview { display: none; margin-top: 20px; }
        .certificate-preview.show { display: block; }
        
        .certificate-wrapper {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            max-width: 1050px;
            margin: 0 auto;
        }
        
        /* CERTIFICATE LAYOUT - PROPER SPACING BETWEEN LEFT AND RIGHT */
        .certificate {
            background: #fff;
            border: 0px solid #333;
            padding: 30px 40px 35px 40px;
            position: relative; /* REQUIRED: Anchors absolute elements inside the border */
            color: #111;
            box-sizing: border-box;
            font-family: 'Times New Roman', Times, serif;
        }
        
        /* University Header - Centered */
        .cert-header-title {
            text-align: center;
            margin-top: 5px;
        }
        .cert-header-title .univ-main {
            font-size: 28px;
            font-weight: 900;
            letter-spacing: 2px;
            text-transform: uppercase;
            color: #1a202c;
            line-height: 1.2;
        }
        .cert-header-title .univ-sub {
            font-size: 18px;
            font-weight: bold;
            letter-spacing: 1px;
            text-transform: uppercase;
            margin-top: 2px;
        }
        .cert-header-title .univ-motto {
            font-size: 14px;
            font-weight: bold;
            margin-top: 3px;
            font-style: italic;
        }

        /* Logo - Centered */
        .university-logo-center {
            text-align: center;
            margin: 15px 0 10px 0;
        }
        .university-logo-center img, .logo-fallback {
            width: 120px;
            height: 100px;
            margin: 0 auto;
        }
        .logo-fallback {
            border-radius: 50%;
            border: 2px solid #333;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 38px;
            color: #333;
        }
        .logo-img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            border-radius: 50%;
        }

        /* MAIN CONTENT WRAPPER - FLEX WITH PROPER SPACING */
       .cert-content-wrapper {
            width: 100%;
            margin: 15px 0 10px 0;
            text-align: center;
        }

        /* LEFT CONTENT - FILLS AVAILABLE SPACE */
       .cert-left-content {
            width: 100%;
            text-align: center;
            /* Optional: prevents text collision if student names are extremely long */
            padding: 0 120px; 
            box-sizing: border-box;
        }
        /* RIGHT SIDEBAR - FIXED WIDTH */
        .cert-right-sidebar {
            position: absolute;
            top: 155px;      /* Snaps photo level with "FACULTY OF AGRICULTURE" */
            right: 40px;     /* Matches certificate inner right margin */
            width: 140px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2px;
            z-index: 10;
        }

        /* Faculty Title - Centered */
        .faculty-title {
            font-size: 22px;
            font-weight: 900;
            letter-spacing: 2px;
            text-transform: uppercase;
            color: #1a202c;
            text-align: center;
            margin: 0 0 15px 0;
        }

        /* Student Name - Centered */
        .student-title {
            font-size: 26px;
            font-weight: 900;
            text-transform: uppercase;
            color: #1a202c;
            text-align: center;
            margin-bottom: 5px;
            letter-spacing: 1px;
        }

        /* Parents Line - Centered */
        .parents-line {
            font-size: 18px;
            font-weight: bold;
            text-transform: uppercase;
            color: #2d3748;
            text-align: center;
            margin-bottom: 12px;
        }

        /* Registration Statement - Centered */
        .reg-no-statement {
            font-size: 17px;
            color: #2d3748;
            text-align: center;
            margin-bottom: 5px;
            line-height: 1.6;
        }

        .reg-no-statement strong {
            color: #1a202c;
            font-weight: 900;
            font-size: 19px;
        }

        /* Degree Title - Centered */
        .degree-title {
            font-size: 24px;
            font-weight: 900;
            text-transform: uppercase;
            color: #1a202c;
            text-align: center;
            margin: 5px 0 10px 0;
            letter-spacing: 1px;
        }

        /* Photo Box - No border */
        .photo-box {
            width: 140px;
            height: 170px;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            background: transparent;
            border: 4px solid #ccc;
        }

        .photo-box img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .photo-box span {
            text-align: center;
            padding: 10px;
            color: #666;
            font-size: 12px;
            font-weight: bold;
        }

        .photo-caption {
            font-size: 11px;
            color: #333;
            text-align: center;
            font-weight: 600;
            margin-top: -3px;
        }

        /* Barcode - Centered */
        .side-barcode-box {
            margin-top: 5px;
            padding: 5px 0;
            text-align: center;
            width: 100%;
            display: flex;
            justify-content: center;
        }

        .side-barcode-box img {
            max-width: 160px;
            height: auto;
            display: block;
        }

        /* Testimony Text - Centered with max-width */
        .testimony-text {
            font-size: 17px;
            line-height: 1.8;
            margin: 10px auto 30px auto;
            text-align: center;
            max-width: 800px;
        }

        .testimony-text strong {
            font-size: 18px;
            font-weight: bold;
        }

        .testimony-text .gpa-value {
            font-size: 20px;
            font-weight: 900;
        }

        /* Footer Row - Evenly Spaced */
        .cert-footer-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            margin-top: 25px;
            padding-top: 10px;
            text-align: center;
            width: 100%;
        }

        .footer-date-block {
            font-size: 16px;
            font-weight: bold;
            line-height: 1.6;
            text-align: left;
            min-width: 150px;
        }

        .footer-date-block .date-line {
            display: inline-block;
            width: 120px;
            border-bottom: 1px solid #333;
            margin-left: 5px;
        }

        .signature-block {
            text-align: center;
            flex: 1;
        }

        .signature-block .sig-title {
            font-size: 20px;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-top: 5px;
        }

        .signature-block .sig-line {
            width: 140px;
            border-top: 2px solid #333;
            margin: 5px auto 3px auto;
        }

        .bottom-qr-box {
            width: 90px;
            text-align: center;
        }

        .bottom-qr-box img {
            width: 120px;
            height: 120px;
            border: 4px solid #ccc;
        }

        .bottom-qr-box .qr-cap {
            font-size: 10px;
            font-weight: bold;
            margin-top: 2px;
        }

        .certificate-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 20px;
            justify-content: center;
            font-family: 'Segoe UI', sans-serif;
        }

        .search-box { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
        .search-box input[type="text"] { flex: 1; min-width: 200px; padding: 10px; border: 1px solid #e2e8f0; border-radius: 5px; font-size: 14px; }

        .info-box { background: #f7fafc; padding: 15px; border-radius: 5px; margin: 10px 0; border: 1px solid #e2e8f0; font-family: 'Segoe UI', sans-serif; }
        .info-box p { margin: 5px 0; color: #4a5568; }

        /* Responsive */
        @media (max-width: 768px) {
            .cert-content-wrapper {
                flex-direction: column;
                align-items: center;
                gap: 20px;
            }
            
            .cert-right-sidebar {
                flex: 0 0 auto;
                width: 100%;
                max-width: 200px;
            }
            
            .cert-footer-row {
                flex-direction: column;
                align-items: center;
                gap: 15px;
            }
            
            .footer-date-block {
                text-align: center;
            }
        }

        @media print {
            .sidebar, .header, .search-section, .btn, .info-box, .certificate-actions, .no-print { display: none !important; }
            .main-content { margin-left: 0 !important; padding: 0 !important; }
            .certificate-preview { display: block !important; }
            .certificate-wrapper { box-shadow: none !important; padding: 0 !important; }
            .certificate { border: 2px solid #000 !important; padding: 20px !important; }
            /* Specific text centering adjustments */
.faculty-title, 
.student-title, 
.parents-line, 
.reg-no-statement, 
.degree-title {
    text-align: center;
    width: 100%;
}
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <h2>SKUAST-K Portal</h2>
        <div class="user-info">
            <div class="name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'User'); ?></div>
            <div class="email"><?php echo htmlspecialchars($_SESSION['user_email'] ?? 'email'); ?></div>
        </div>
        <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="add_certificate.php"><i class="fas fa-plus-circle"></i> Add Certificate</a>
        <a href="bulk_upload.php"><i class="fas fa-upload"></i> Bulk Upload</a>
        <a href="map_photo.php"><i class="fas fa-image"></i> Map Photo</a>
        <a href="generate_certificate.php" class="active"><i class="fas fa-file-pdf"></i> Generate Certificate</a>
        <a href="view_certificates.php"><i class="fas fa-list"></i> View All</a>
        <a href="logout.php" style="margin-top: 30px; border-top: 1px solid #4a5568; padding-top: 20px;"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
    
    <div class="main-content">
        <div class="header">
            <h1>Generate Certificate</h1>
            <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        </div>
        
        <?php echo $message; ?>
        
        <!-- Search Section -->
        <div class="search-section">
            <h3><i class="fas fa-search"></i> Search Student</h3>
            <form method="POST" action="">
                <div class="search-box">
                    <input type="text" name="registration_no" placeholder="Enter Registration Number" 
                           value="<?php echo isset($_POST['registration_no']) ? htmlspecialchars($_POST['registration_no']) : (isset($_GET['reg']) ? htmlspecialchars($_GET['reg']) : ''); ?>" required>
                    <button type="submit" name="search" class="btn"><i class="fas fa-search"></i> Search</button>
                </div>
            </form>
        </div>
        
        <!-- Certificate Preview Section -->
        <?php if ($certificate_data): ?>
        <div class="certificate-preview show" id="certificatePreview">
            <div class="certificate-actions no-print">
                <form method="POST" action="" style="display: inline;">
                    <input type="hidden" name="id" value="<?php echo $certificate_data['id']; ?>">
                    <button type="submit" name="generate" class="btn btn-success" <?php echo $certificate_data['certificate_status'] == 'generated' ? 'disabled' : ''; ?>>
                        <i class="fas fa-sync-alt"></i> Generate QR & Barcode
                    </button>
                </form>
                <button onclick="window.print()" class="btn btn-secondary"><i class="fas fa-print"></i> Print Certificate</button>
                <button onclick="downloadCertificate()" class="btn btn-warning"><i class="fas fa-download"></i> Download</button>
            </div>
            
            <div class="certificate-wrapper">
                <div class="certificate" id="certificate">
                    
                    <!-- Main University Header -->
                    <div class="cert-header-title" style="color: transparent;">
                        <div class="univ-main" style="color: transparent;">SHER-E-KASHMIR</div>
                        <div class="univ-sub" style="color: transparent;">UNIVERSITY OF AGRICULTURAL SCIENCES AND TECHNOLOGY OF KASHMIR</div>
                        <div class="univ-motto" style="color: transparent;">(A Leading University In Mountain Agriculture)</div>
                    </div>

                    <!-- Center University Logo -->
                    <div class="university-logo-center">
                      <!--  <div class="">
                            <img src="images/Emblem colour.jpg" alt="SKUAST-K Logo" class="logo-img">
                        </div> -->
                    </div>

                    <!-- Certificate Content Wrapper - Proper spacing between left and right -->
                    <div class="cert-content-wrapper">
                        
                        <!-- LEFT CONTENT - Fills available space -->
                        <div class="cert-left-content">
                            <div class="faculty-title" style="font-family: 'Stencil', serif; color: maroon; font-size: 27.75px; font-weight: bold;">
                                <?php echo htmlspecialchars($certificate_data['faculty'] ?? 'FACULTY OF AGRICULTURE'); ?>
                            </div></br>

                           <div class="student-title" style="font-family: Arial, sans-serif; color: black; font-size: 20.25px; font-weight: bold;">
                                <?php echo htmlspecialchars($certificate_data['name'] ?? 'VIHAAN SINGH'); ?>
                            </div></br>
                            
                            <div class="parents-line" style="font-family: Arial, sans-serif; color: black; font-size: 16px; font-weight: bold;">
                                <?php echo htmlspecialchars($certificate_data['father_name'] ?? 'RANJIT SINGH'); ?> &amp; <?php echo htmlspecialchars($certificate_data['mother_name'] ?? 'HARPREET KAUR'); ?>
                            </div>

                            <div class="reg-no-statement" style="color: black; font-size: 14px;">
                                Registration No. <strong><?php echo htmlspecialchars($certificate_data['registration_no']); ?></strong> is hereby admitted to the Degree of
                            </div> </br></br>

                            <div class="degree-title" style="font-family: 'Stencil', serif; color: maroon; font-size: 25px; font-weight: regular;">
                                <?php echo htmlspecialchars($certificate_data['degree'] ?? 'B.TECH'); ?>
                            </div>
                        </div>
                        
                        <!-- RIGHT SIDEBAR - Fixed width with photo and barcode -->
                        <div class="cert-right-sidebar">
                            <div class="photo-box">
                                <?php if (!empty($certificate_data['photo'])): ?>
                                    <img src="data:image/jpeg;base64,<?php echo base64_encode($certificate_data['photo']); ?>" alt="Student Photo">
                                <?php else: ?>
                                    <span>Photograph here</span>
                                <?php endif; ?>
                            </div>
                            <div class="photo-caption">Photograph of the bearer</div>

                            <div class="side-barcode-box">
                                <?php if (!empty($certificate_data['barcode'])): ?>
                                    <img src="data:image/png;base64,<?php echo $certificate_data['barcode']; ?>" alt="Barcode">
                                <?php endif; ?>
                            </div>
                        </div>
                        
                    </div>

                    <!-- Full Width Narrative Paragraph - Centered -->
                    <div class="testimony-text" style="font-family: 'Arial ; color: black; font-size: 14px; font-weight: regular;">
                        in testimony of having successfully completed all the prescribed requirements of the degree on 
                        with an Overall Grade Point Average of <strong class="gpa-value"><?php echo htmlspecialchars($certificate_data['grade_point_average'] ?? '7.500'); ?></strong> out of <strong>10.00</strong>
                    </div>

                    <!-- Bottom Signatures & Details Row - Evenly Spaced -->
                   <div class="cert-footer-row" style="color: transparent;">
                        <div class="footer-date-block" style="color: transparent;">
                            Date : <span class="date-line" style="border-bottom-color: transparent;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><br>
                            Shalimar, Srinagar, J&amp;K
                        </div>
                    
                        <div class="signature-block" style="color: transparent;">
                            <div class="sig-line" style="border-top-color: transparent;"></div>
                            <div class="sig-title" style="color: transparent;">Registrar</div>
                        </div>
                    
                        <div class="signature-block" style="color: transparent;">
                            <div class="sig-line" style="border-top-color: transparent;"></div>
                            <div class="sig-title" style="color: transparent;">Vice Chancellor</div>
                        </div>
                    
                        <div class="bottom-qr-box">
                            <?php if (!empty($certificate_data['qr_code'])): ?>
                                <img src="data:image/png;base64,<?php echo $certificate_data['qr_code']; ?>" alt="QR Code" style="display: block;">
                                <div class="qr-cap" style="color: transparent;"></div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Generator Info Footer Box -->
           <!-- <div class="info-box no-print">
                <p><strong>Status:</strong> <?php echo ucfirst($certificate_data['certificate_status']); ?></p>
                <?php if (!empty($certificate_data['generated_by'])): ?>
                    <p><strong>Generated Date:</strong> <?php echo date('d M Y H:i:s', strtotime($certificate_data['generated_date'] ?? 'now')); ?></p>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>-->

    <script>
        function downloadCertificate() {
            const certificate = document.getElementById('certificate');
            const html = certificate.outerHTML;
            const win = window.open('', '_blank', 'width=1050,height=850');
            
            win.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Certificate - <?php echo htmlspecialchars($certificate_data['name'] ?? 'Student'); ?></title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Times New Roman', Times, serif; 
                            background: white;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            min-height: 100vh;
                            padding: 20px;
                        }
                        ${Array.from(document.styleSheets).reduce((acc, sheet) => {
                            try {
                                const rules = sheet.cssRules || sheet.rules;
                                if (rules) {
                                    for(let rule of rules) {
                                        acc += rule.cssText;
                                    }
                                }
                            } catch(e) {}
                            return acc;
                        }, '')}
                    </style>
                </head>
                <body>
                    ${html}
                    <script>
                        window.onload = function() {
                            window.print();
                        };
                    <\/script>
                </body>
                </html>
            `);
            win.document.close();
        }
    </script>
</body>
</html>