<?php
/**
 * Admit Card — Professional Design (SSC-style)
 *
 * Features:
 *   - Institute header with logo
 *   - "ADMIT CARD" title with bilingual subtitle
 *   - Student photo with border (top-right)
 *   - Login credentials box (username + password) — prominent
 *   - Student personal details (name, enrollment, father's name, DOB, course)
 *   - Exam details (date, time, duration, total marks, pass marks)
 *   - Subjects table (subject name + max marks)
 *   - QR code for verification
 *   - Branch signature + contact
 *   - Print-optimized CSS (Print → Save as PDF produces a clean PDF)
 *   - Uses qrcode.js for client-side QR code generation (no PHP library needed)
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$card = $card ?? [];

// Compute the public portal URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host     = $_SERVER['HTTP_HOST'] ?? 'your-website.com';
$portalUrl = $protocol . '://' . $host . $bp . '/branch-exam';
$verifyUrl = $protocol . '://' . $host . $bp . '/verify/' . rawurlencode($card['card_number'] ?? '');

// Student photo URL
$photoUrl = $bp . '/images/avatar-default.png'; // default avatar
if (!empty($card['photo'])) {
    $photoUrl = $bp . '/' . ltrim($card['photo'], '/');
} elseif (!empty($card['student_photo'])) {
    $photoUrl = $bp . '/' . ltrim($card['student_photo'], '/');
}

// Logo URL
$logoUrl = $bp . '/images/logo.png';

// Exam date/time
$examDateStr = '—';
$examTimeStr = '—';
if (!empty($card['start_time'])) {
    $examDateStr = date('d/m/Y', strtotime($card['start_time']));
    $examTimeStr = date('g:i A', strtotime($card['start_time']));
    if (!empty($card['end_time'])) {
        $examTimeStr .= ' to ' . date('g:i A', strtotime($card['end_time']));
    }
}

// Language label
$langLabel = ['en'=>'English','hi'=>'हिंदी','both'=>'English + Hindi'][$card['exam_language'] ?? 'en'] ?? 'English';
?>
<style>
    /* ========== Print Reset ========== */
    @media print {
        body * { visibility: hidden; }
        .print-area, .print-area * { visibility: visible; }
        .print-area { position: absolute; left: 0; top: 0; width: 100%; }
        .no-print { display: none !important; }
        @page { margin: 8mm; size: A4 portrait; }
        body { background: #fff !important; }
    }

    /* ========== Toolbar (screen only) ========== */
    .ac-toolbar {
        max-width: 800px; margin: 20px auto 0; padding: 0 20px;
        display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap;
    }
    .ac-toolbar a { color: #16a085; text-decoration: none; font-size: 0.86rem; font-weight: 600; }
    .ac-toolbar button {
        background: linear-gradient(135deg, #16a085, #117a65); color: #fff;
        border: none; padding: 10px 24px; border-radius: 8px; font-size: 0.88rem;
        font-weight: 700; cursor: pointer; box-shadow: 0 4px 12px rgba(22,160,133,0.3);
        transition: transform 0.2s;
    }
    .ac-toolbar button:hover { transform: translateY(-2px); }

    /* ========== Admit Card Container ========== */
    .print-area {
        max-width: 800px; margin: 20px auto; padding: 0 20px;
    }
    .admit-card {
        background: #fff; border: 3px solid #0d3b3b; border-radius: 12px;
        overflow: hidden; box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        font-family: 'Poppins', 'Inter', sans-serif;
    }

    /* ========== Header ========== */
    .ac-header {
        background: linear-gradient(135deg, #0d3b3b 0%, #16a085 100%);
        color: #fff; padding: 18px 24px;
        display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 16px;
    }
    .ac-header-left { text-align: left; }
    .ac-header-left .inst-name { font-size: 1.3rem; font-weight: 700; letter-spacing: 1px; }
    .ac-header-left .inst-sub { font-size: 0.82rem; opacity: 0.85; margin-top: 2px; }
    .ac-header-center { text-align: center; }
    .ac-header-center img { width: 60px; height: 60px; border-radius: 50%; background: #fff; padding: 4px; }
    .ac-header-right { text-align: right; font-size: 0.78rem; opacity: 0.9; line-height: 1.5; }

    /* ========== Title Bar ========== */
    .ac-title-bar {
        text-align: center; padding: 12px 24px;
        border-bottom: 2px solid #0d3b3b; background: #f4f9f9;
    }
    .ac-title {
        font-size: 1.4rem; font-weight: 700; color: #0d3b3b;
        text-transform: uppercase; letter-spacing: 3px;
        border-bottom: 2px solid #16a085; display: inline-block; padding-bottom: 4px;
    }
    .ac-subtitle { font-size: 0.86rem; color: #666; margin-top: 4px; font-style: italic; }

    /* ========== Body ========== */
    .ac-body { padding: 20px 24px; }

    /* ========== Photo + Login Section ========== */
    .ac-top-section {
        display: grid; grid-template-columns: 1fr 160px; gap: 20px; margin-bottom: 18px;
    }
    .ac-login-box {
        background: linear-gradient(135deg, #0d3b3b, #072525); color: #fff;
        border-radius: 10px; padding: 16px 18px;
    }
    .ac-login-box .login-title {
        font-size: 0.78rem; font-weight: 700; text-transform: uppercase; letter-spacing: 1px;
        text-align: center; margin-bottom: 10px; padding-bottom: 8px;
        border-bottom: 1px solid rgba(255,255,255,0.2);
    }
    .ac-login-row {
        display: flex; justify-content: space-between; align-items: center;
        padding: 6px 0; font-size: 0.86rem;
        border-bottom: 1px dashed rgba(255,255,255,0.15);
    }
    .ac-login-row:last-child { border-bottom: none; }
    .ac-login-label { color: rgba(255,255,255,0.6); font-size: 0.76rem; }
    .ac-login-value { font-family: 'Courier New', monospace; font-weight: 700; font-size: 0.95rem; color: #1abc9c; }
    .ac-login-portal {
        text-align: center; margin-top: 10px; padding-top: 8px;
        border-top: 1px solid rgba(255,255,255,0.2);
        font-size: 0.72rem; color: rgba(255,255,255,0.6);
    }
    .ac-login-portal strong { color: #1abc9c; font-family: monospace; font-size: 0.78rem; }

    /* ========== Photo ========== */
    .ac-photo-box { text-align: center; }
    .ac-photo {
        width: 140px; height: 170px; border: 3px solid #0d3b3b; border-radius: 8px;
        object-fit: cover; background: #f0f0f0; display: block; margin: 0 auto;
    }
    .ac-signature-line {
        margin-top: 8px; font-size: 0.72rem; color: #999;
        border-top: 1px solid #ccc; padding-top: 4px;
    }

    /* ========== Details Table ========== */
    .ac-details-table {
        width: 100%; border-collapse: collapse; margin-bottom: 16px;
        font-size: 0.88rem;
    }
    .ac-details-table td {
        border: 1px solid #d0d0d0; padding: 7px 12px;
    }
    .ac-details-table .label {
        background: #f4f9f9; color: #666; font-weight: 600; width: 30%;
        text-transform: uppercase; font-size: 0.76rem; letter-spacing: 0.5px;
    }
    .ac-details-table .value { color: #0d3b3b; font-weight: 600; }
    .ac-details-table .value.mono { font-family: 'Courier New', monospace; }

    /* ========== Exam Info Box ========== */
    .ac-exam-info {
        background: #fff8e1; border: 1.5px solid #f5d68b; border-radius: 8px;
        padding: 12px 16px; margin-bottom: 16px;
        display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px;
    }
    .ac-exam-info-item { text-align: center; }
    .ac-exam-info-item .ei-label { font-size: 0.72rem; color: #b8731a; text-transform: uppercase; letter-spacing: 0.5px; }
    .ac-exam-info-item .ei-value { font-size: 1.0rem; font-weight: 700; color: #0d3b3b; margin-top: 2px; }

    /* ========== Subjects Table ========== */
    .ac-subjects-title {
        font-size: 0.92rem; font-weight: 700; color: #0d3b3b; margin-bottom: 6px;
        padding-bottom: 4px; border-bottom: 2px solid #16a085;
    }
    .ac-subjects-table {
        width: 100%; border-collapse: collapse; margin-bottom: 16px; font-size: 0.86rem;
    }
    .ac-subjects-table th {
        background: #0d3b3b; color: #fff; padding: 8px 12px;
        text-align: left; font-weight: 600; font-size: 0.82rem;
        text-transform: uppercase; letter-spacing: 0.5px;
    }
    .ac-subjects-table td {
        border: 1px solid #d0d0d0; padding: 7px 12px;
    }
    .ac-subjects-table tr:nth-child(even) td { background: #f9f9f9; }
    .ac-subjects-table .text-center { text-align: center; }
    .ac-subjects-table .total-row td { background: #eafaf1 !important; font-weight: 700; color: #0d3b3b; }

    /* ========== QR + Footer Section ========== */
    .ac-footer-section {
        display: grid; grid-template-columns: 1fr auto; gap: 20px;
        align-items: center; margin-top: 16px; padding-top: 16px;
        border-top: 2px solid #0d3b3b;
    }
    .ac-instructions {
        font-size: 0.78rem; color: #555; line-height: 1.6;
    }
    .ac-instructions strong { color: #0d3b3b; }
    .ac-signature {
        text-align: center; font-size: 0.82rem; color: #666;
    }
    .ac-signature .sig-line {
        border-top: 1.5px solid #0d3b3b; width: 180px; margin: 24px auto 4px;
    }
    .ac-signature .sig-name { font-weight: 700; color: #0d3b3b; }
    .ac-signature .sig-role { font-size: 0.76rem; color: #999; }

    /* ========== QR Code ========== */
    .ac-qr-box { text-align: center; }
    .ac-qr-box img { width: 100px; height: 100px; }
    .ac-qr-box .qr-label { font-size: 0.68rem; color: #999; margin-top: 4px; }

    /* ========== Bottom Bar ========== */
    .ac-bottom-bar {
        background: #0d3b3b; color: rgba(255,255,255,0.7); padding: 8px 24px;
        font-size: 0.72rem; text-align: center; letter-spacing: 0.5px;
    }
    .ac-bottom-bar strong { color: #fff; }

    /* ========== Responsive ========== */
    @media (max-width: 600px) {
        .ac-header { grid-template-columns: 1fr; text-align: center; }
        .ac-header-left, .ac-header-right { text-align: center; }
        .ac-top-section { grid-template-columns: 1fr; }
        .ac-photo-box { order: -1; }
        .ac-exam-info { grid-template-columns: 1fr; }
        .ac-footer-section { grid-template-columns: 1fr; text-align: center; }
        .ac-signature .sig-line { margin: 24px auto; }
    }
</style>

<!-- Toolbar (screen only) -->
<div class="ac-toolbar no-print">
    <a href="<?= $bp ?>/branch/admit-cards">← Back to Admit Cards</a>
    <button onclick="window.print()">
        🖨 Print / Save as PDF
    </button>
</div>

<!-- Admit Card -->
<div class="print-area">
    <div class="admit-card" id="admitCard">

        <!-- Header -->
        <div class="ac-header">
            <div class="ac-header-left">
                <div class="inst-name">GMIND INSTITUTE</div>
                <div class="inst-sub">Gmind Institute of Computer Education</div>
            </div>
            <div class="ac-header-center">
                <img src="<?= htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8') ?>" alt="Logo" onerror="this.style.display='none'">
            </div>
            <div class="ac-header-right">
                <strong><?= htmlspecialchars($card['branch_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong><br>
                Code: <?= htmlspecialchars($card['branch_code'] ?? '', ENT_QUOTES, 'UTF-8') ?><br>
                📞 <?= htmlspecialchars($card['branch_phone'] ?? '', ENT_QUOTES, 'UTF-8') ?><br>
                📍 <?= htmlspecialchars($card['branch_address'] ?? '', ENT_QUOTES, 'UTF-8') ?>
            </div>
        </div>

        <!-- Title Bar -->
        <div class="ac-title-bar">
            <div class="ac-title">Admit Card</div>
            <div class="ac-subtitle">प्रवेश पत्र · Branch Examination Portal</div>
        </div>

        <!-- Body -->
        <div class="ac-body">

            <!-- Top Section: Login box + Photo -->
            <div class="ac-top-section">
                <!-- Login Credentials Box -->
                <div class="ac-login-box">
                    <div class="login-title">🔐 Branch Exam — Login Credentials</div>
                    <div class="ac-login-row">
                        <span class="ac-login-label">Username</span>
                        <span class="ac-login-value"><?= htmlspecialchars($card['login_username'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                    </div>
                    <div class="ac-login-row">
                        <span class="ac-login-label">Password</span>
                        <span class="ac-login-value"><?= htmlspecialchars($card['login_password'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                    </div>
                    <div class="ac-login-portal">
                        Login at:<br>
                        <strong><?= htmlspecialchars($portalUrl, ENT_QUOTES, 'UTF-8') ?></strong>
                    </div>
                </div>

                <!-- Photo -->
                <div class="ac-photo-box">
                    <img class="ac-photo" src="<?= htmlspecialchars($photoUrl, ENT_QUOTES, 'UTF-8') ?>" alt="Student Photo" onerror="this.src='<?= $bp ?>/images/avatar-default.png'">
                    <div class="ac-signature-line">Student Signature</div>
                </div>
            </div>

            <!-- Student Details Table -->
            <table class="ac-details-table">
                <tr>
                    <td class="label">Card Number</td>
                    <td class="value mono" style="color:#16a085;"><?= htmlspecialchars($card['card_number'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td class="label">Enrollment No</td>
                    <td class="value mono"><?= htmlspecialchars($card['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                </tr>
                <tr>
                    <td class="label">Student Name</td>
                    <td class="value" colspan="3"><?= htmlspecialchars($card['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                </tr>
                <tr>
                    <td class="label">Father's Name</td>
                    <td class="value"><?= htmlspecialchars($card['father_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                    <td class="label">Date of Birth</td>
                    <td class="value"><?= !empty($card['dob']) ? date('d/m/Y', strtotime($card['dob'])) : '—' ?></td>
                </tr>
                <tr>
                    <td class="label">Course</td>
                    <td class="value"><?= htmlspecialchars($card['course_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                    <td class="label">Email</td>
                    <td class="value" style="font-size:0.82rem;"><?= htmlspecialchars($card['email'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                </tr>
                <tr>
                    <td class="label">Phone</td>
                    <td class="value mono"><?= htmlspecialchars($card['phone'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                    <td class="label">Language</td>
                    <td class="value"><?= htmlspecialchars($langLabel, ENT_QUOTES, 'UTF-8') ?></td>
                </tr>
            </table>

            <!-- Exam Info Box -->
            <div class="ac-exam-info">
                <div class="ac-exam-info-item">
                    <div class="ei-label">📅 Exam Date</div>
                    <div class="ei-value"><?= $examDateStr ?></div>
                </div>
                <div class="ac-exam-info-item">
                    <div class="ei-label">⏰ Exam Time</div>
                    <div class="ei-value"><?= $examTimeStr ?></div>
                </div>
                <div class="ac-exam-info-item">
                    <div class="ei-label">⏱ Duration</div>
                    <div class="ei-value"><?= (int)($card['duration_minutes'] ?? 60) ?> min</div>
                </div>
            </div>

            <!-- Exam Title -->
            <table class="ac-details-table" style="margin-bottom:12px;">
                <tr>
                    <td class="label">Exam Name</td>
                    <td class="value" colspan="3">
                        <?= htmlspecialchars($card['exam_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                        <?php if (!empty($card['title_hindi'])): ?>
                            <br><span style="font-weight:400;color:#666;font-family:'Noto Sans Devanagari',sans-serif;"><?= htmlspecialchars($card['title_hindi'], ENT_QUOTES, 'UTF-8') ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td class="label">Total Marks</td>
                    <td class="value"><?= (int)($card['total_marks'] ?? 100) ?></td>
                    <td class="label">Pass Marks</td>
                    <td class="value" style="color:#e84118;"><?= (int)($card['pass_marks'] ?? 40) ?></td>
                </tr>
            </table>

            <!-- Subjects Table -->
            <div class="ac-subjects-title">📋 Subjects & Marks Distribution</div>
            <table class="ac-subjects-table">
                <thead>
                    <tr>
                        <th style="width:50%;">Subject</th>
                        <th class="text-center" style="width:25%;">Max Marks</th>
                        <th class="text-center" style="width:25%;">Pass Marks</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Try to fetch subjects from the course's subjects JSON
                    $subjects = [];
                    if (!empty($card['course_id'])) {
                        try {
                            $db = getDb();
                            $stmt = $db->prepare("SELECT subjects FROM courses WHERE id = :cid LIMIT 1");
                            $stmt->execute([':cid' => $card['course_id']]);
                            $courseSubs = $stmt->fetchColumn();
                            if ($courseSubs) {
                                $decoded = json_decode($courseSubs, true);
                                if (is_array($decoded)) $subjects = $decoded;
                            }
                        } catch (\Throwable $e) {}
                    }
                    if (empty($subjects)):
                        // Fallback: show the exam as a single subject
                        $subjects = [['name' => $card['exam_name'] ?? 'Exam', 'max_marks' => (int)($card['total_marks'] ?? 100)]];
                    endif;
                    $totalMax = 0;
                    foreach ($subjects as $sub):
                        $max = (int)($sub['max_marks'] ?? 100);
                        $totalMax += $max;
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($sub['name'] ?? 'Subject', ENT_QUOTES, 'UTF-8') ?></td>
                        <td class="text-center"><?= $max ?></td>
                        <td class="text-center" style="color:#e84118;"><?= (int)round($max * 0.33) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <tr class="total-row">
                        <td>TOTAL</td>
                        <td class="text-center"><?= $totalMax ?></td>
                        <td class="text-center"><?= (int)round($totalMax * 0.33) ?></td>
                    </tr>
                </tbody>
            </table>

            <!-- QR + Signature Section -->
            <div class="ac-footer-section">
                <div class="ac-instructions">
                    <strong>📋 Instructions:</strong>
                    <ol style="margin:4px 0 0 18px;padding:0;line-height:1.7;">
                        <li>Report to the exam center 15 minutes before the scheduled time.</li>
                        <li>Bring this admit card + a valid photo ID proof.</li>
                        <li>Login to <strong><?= htmlspecialchars($portalUrl, ENT_QUOTES, 'UTF-8') ?></strong> with the credentials shown above.</li>
                        <li>The exam will auto-submit when the timer reaches zero.</li>
                        <?php if (!empty($card['instructions'])): ?>
                        <li><?= htmlspecialchars($card['instructions'], ENT_QUOTES, 'UTF-8') ?></li>
                        <?php endif; ?>
                    </ol>
                </div>
                <div style="display:flex;flex-direction:column;align-items:center;gap:12px;">
                    <!-- QR Code (generated client-side by qrcode.js) -->
                    <div class="ac-qr-box">
                        <div id="qrcode"></div>
                        <div class="qr-label">Scan to verify</div>
                    </div>
                </div>
            </div>

            <!-- Signature -->
            <div style="display:flex;justify-content:space-between;margin-top:24px;">
                <div class="ac-signature" style="text-align:left;">
                    <div style="height:40px;"></div>
                    <div class="sig-line" style="margin:0 0 4px;"></div>
                    <div class="sig-name">Student Signature</div>
                </div>
                <div class="ac-signature">
                    <div style="height:40px;"></div>
                    <div class="sig-line"></div>
                    <div class="sig-name">Authorized Signatory</div>
                    <div class="sig-role"><?= htmlspecialchars($card['branch_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                </div>
            </div>

        </div><!-- /ac-body -->

        <!-- Bottom Bar -->
        <div class="ac-bottom-bar">
            Card No: <strong><?= htmlspecialchars($card['card_number'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong>
            &nbsp;·&nbsp;
            Generated: <strong><?= date('d M Y, g:i A') ?></strong>
            &nbsp;·&nbsp;
            Verify at: <strong><?= htmlspecialchars($verifyUrl, ENT_QUOTES, 'UTF-8') ?></strong>
        </div>

    </div><!-- /admit-card -->
</div><!-- /print-area -->

<!-- QR Code Generator (uses QuickChart API for real, scannable QR codes) -->
<script>
(function() {
    var qrData = <?= json_encode($verifyUrl) ?>;
    var qrElement = document.getElementById('qrcode');
    if (!qrElement) return;

    // Use QuickChart API for a REAL, scannable QR code
    // (free, no API key needed, works without any JS library)
    var qrImg = document.createElement('img');
    qrImg.src = 'https://quickchart.io/qr?text=' + encodeURIComponent(qrData) + '&size=200&margin=2&dark=000000&light=ffffff';
    qrImg.width = 100;
    qrImg.height = 100;
    qrImg.style.border = '1px solid #ddd';
    qrImg.style.borderRadius = '4px';
    qrImg.alt = 'QR Code';
    qrImg.onerror = function() {
        // Fallback: show a text link if QR API is unavailable
        qrElement.innerHTML = '<div style="width:100px;height:100px;border:1px solid #ddd;display:flex;align-items:center;justify-content:center;font-size:0.6rem;text-align:center;color:#999;padding:4px;">QR unavailable<br>Visit verify URL</div>';
    };
    qrElement.appendChild(qrImg);
})();
</script>
