<?php
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$cards = $cards ?? [];
$exams = $exams ?? [];
$students = $students ?? [];
?>
<div class="admin-section">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:10px;">
        <h2 style="margin:0;font-size:1.1rem;color:#0d3b3b;">Admit Cards</h2>
        <button onclick="document.getElementById('genForm').style.display='block';this.style.display='none';" style="background:#16a085;color:#fff;border:none;padding:10px 20px;border-radius:8px;font-size:0.86rem;cursor:pointer;font-weight:600;">+ Generate Admit Card</button>
    </div>

    <!-- Generate form -->
    <div id="genForm" style="display:none;background:#fff;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
        <h3 style="margin:0 0 14px;font-size:1rem;color:#0d3b3b;">Generate Admit Card + Set Login Credentials</h3>
        <p style="margin:0 0 14px;font-size:0.8rem;color:#666;">The student will use these credentials to log in to the <strong>Branch Exam</strong> portal (your-website/branch-exam) and take the exam. The password will be hashed and saved to their account; the plain-text version is stored on the admit card for printing.</p>

        <form method="POST" action="<?= $bp ?>/branch/admit-cards/generate">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px;">
                <div>
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Student *</label>
                    <select name="student_id" id="studentSelect" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;">
                        <option value="">— Select Student —</option>
                        <?php foreach ($students as $s): ?>
                            <option value="<?= (int)$s['id'] ?>"
                                    data-enrollment="<?= htmlspecialchars($s['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-phone="<?= htmlspecialchars($s['phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-email="<?= htmlspecialchars($s['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                                <?= htmlspecialchars($s['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                (<?= htmlspecialchars($s['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Exam *</label>
                    <select name="exam_id" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;">
                        <option value="">— Select Exam —</option>
                        <?php foreach ($exams as $e): ?>
                            <option value="<?= (int)$e['id'] ?>">
                                <?= htmlspecialchars($e['title'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                <?= !empty($e['title_hindi']) ? ' / ' . htmlspecialchars($e['title_hindi'], ENT_QUOTES, 'UTF-8') : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div style="background:#eaf0fb;padding:14px;border-radius:8px;margin-bottom:14px;">
                <h4 style="margin:0 0 10px;font-size:0.86rem;color:#1a4fa0;">🔐 Branch Exam Portal Login Credentials</h4>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <div>
                        <label style="display:block;font-size:0.76rem;font-weight:600;color:#0d3b3b;margin-bottom:3px;">Username <span style="color:#999;font-weight:400;">(defaults to enrollment no.)</span></label>
                        <input type="text" name="login_username" id="loginUsername" placeholder="auto-filled from enrollment" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.86rem;font-family:monospace;">
                    </div>
                    <div>
                        <label style="display:block;font-size:0.76rem;font-weight:600;color:#0d3b3b;margin-bottom:3px;">Password <span style="color:#999;font-weight:400;">(auto-generated if blank)</span></label>
                        <div style="display:flex;gap:6px;">
                            <input type="text" name="login_password" id="loginPassword" placeholder="leave blank for auto" style="flex:1;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.86rem;font-family:monospace;">
                            <button type="button" onclick="generateRandomPassword()" style="padding:10px 14px;background:#7f8c8d;color:#fff;border:none;border-radius:6px;font-size:0.78rem;cursor:pointer;font-weight:600;">🎲 Random</button>
                        </div>
                    </div>
                </div>
                <p style="margin:10px 0 0;font-size:0.74rem;color:#666;">These credentials will be PRINTED on the admit card AND set as the student's actual login for the portal. If a card already exists for this student + exam, it will be regenerated with the new credentials.</p>
            </div>

            <div style="display:flex;gap:10px;">
                <button type="submit" style="padding:11px 26px;background:#27ae60;color:#fff;border:none;border-radius:8px;font-size:0.86rem;cursor:pointer;font-weight:600;">✓ Generate Admit Card</button>
                <button type="button" onclick="document.getElementById('genForm').style.display='none';document.getElementById('showGenBtn').style.display='inline-block';" style="padding:11px 20px;background:#fff;color:#666;border:1px solid #ddd;border-radius:8px;font-size:0.86rem;cursor:pointer;">Cancel</button>
            </div>
        </form>
    </div>

    <!-- Admit cards list -->
    <div style="background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
        <?php if (empty($cards)): ?>
            <div style="text-align:center;padding:50px 20px;color:#999;">
                <p style="margin:0 0 14px;">No admit cards generated yet.</p>
                <p style="margin:0;font-size:0.82rem;">Click "Generate Admit Card" above to create one for a student.</p>
            </div>
        <?php else: ?>
        <table style="width:100%;border-collapse:collapse;font-size:0.84rem;">
            <thead><tr style="background:#f8f9fa;border-bottom:2px solid #dee2e6;">
                <th style="padding:10px;text-align:left;">Card No</th>
                <th style="padding:10px;text-align:left;">Student</th>
                <th style="padding:10px;text-align:left;">Exam</th>
                <th style="padding:10px;text-align:left;">Login Username</th>
                <th style="padding:10px;text-align:center;">Status</th>
                <th style="padding:10px;text-align:right;">View</th>
            </tr></thead>
            <tbody>
            <?php foreach ($cards as $c): ?>
                <tr style="border-bottom:1px solid #f0f0f0;">
                    <td style="padding:10px;font-family:monospace;font-weight:600;color:#16a085;"><?= htmlspecialchars($c['card_number'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td style="padding:10px;font-weight:600;"><?= htmlspecialchars($c['student_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?><br><span style="font-weight:400;color:#999;font-size:0.76rem;"><?= htmlspecialchars($c['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?></span></td>
                    <td style="padding:10px;color:#666;"><?= htmlspecialchars($c['exam_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                    <td style="padding:10px;font-family:monospace;color:#1a4fa0;font-weight:600;"><?= htmlspecialchars($c['login_username'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                    <td style="padding:10px;text-align:center;"><span style="padding:2px 8px;border-radius:10px;font-size:0.7rem;font-weight:600;color:#fff;background:<?= ($c['status'] ?? '')==='issued'?'#27ae60':'#f39c12' ?>;"><?= htmlspecialchars(ucfirst($c['status'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span></td>
                    <td style="padding:10px;text-align:right;"><a href="<?= $bp ?>/branch/admit-cards/<?= (int)$c['id'] ?>/view" style="background:#3498db;color:#fff;text-decoration:none;padding:5px 12px;border-radius:4px;font-size:0.74rem;font-weight:600;">View / Print</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<script>
// Auto-fill username + suggest password when student is selected
function autofillCredentials() {
    var sel = document.getElementById('studentSelect');
    if (!sel) return;
    var opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) return;
    var enrollment = opt.dataset.enrollment || '';
    var phone = opt.dataset.phone || '';

    // Default username = enrollment_no
    var usernameInput = document.getElementById('loginUsername');
    if (enrollment && !usernameInput.value) usernameInput.value = enrollment;

    // Only auto-suggest password if it's currently empty (don't overwrite admin's input)
    var passwordInput = document.getElementById('loginPassword');
    if (!passwordInput.value) {
        var phoneDigits = phone.replace(/\D/g, '');
        if (phoneDigits.length >= 6) {
            passwordInput.value = phoneDigits.slice(-6);
        } else if (phoneDigits.length >= 4) {
            passwordInput.value = phoneDigits;
        }
        // If phone is short/missing, leave blank — server will auto-generate
    }
}

document.getElementById('studentSelect').addEventListener('change', autofillCredentials);
// Also fire once on page load in case the dropdown has a pre-selected value
document.addEventListener('DOMContentLoaded', autofillCredentials);

// Generate a random 6-digit password
function generateRandomPassword() {
    var pwd = '';
    for (var i = 0; i < 6; i++) pwd += Math.floor(Math.random() * 10);
    document.getElementById('loginPassword').value = pwd;
}
</script>
