<?php
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$documents = $documents ?? [];
$stats = $stats ?? ['total' => 0, 'pending' => 0, 'approved' => 0, 'rejected' => 0];
$statusColors = ['pending_approval' => '#f39c12', 'generated' => '#27ae60', 'rejected' => '#e84118', 'cancelled' => '#999'];
$statusLabels = ['pending_approval' => 'Pending Approval', 'generated' => 'Approved & Generated', 'rejected' => 'Rejected', 'cancelled' => 'Cancelled'];
$docTypeLabels = ['certificate' => '📜 Certificate', 'marksheet' => '📋 Marksheet'];
$csrfToken = $csrfToken ?? ($_SESSION['csrf_token'] ?? '');
?>
<style>
.cart-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(135deg, #0d3b3b, #16a085);
    color: #fff;
    padding: 14px 24px;
    display: none;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 -4px 20px rgba(0,0,0,0.3);
    z-index: 9999;
    flex-wrap: wrap;
    gap: 10px;
}
.cart-bar.active { display: flex; }
.cart-bar .cart-info { font-size: 0.9rem; font-weight: 600; }
.cart-bar .cart-count {
    background: #fff;
    color: #0d3b3b;
    padding: 2px 12px;
    border-radius: 20px;
    font-weight: 700;
    margin: 0 4px;
}
.cart-bar .cart-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.cart-bar .cart-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 0.84rem;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.cart-bar .btn-download { background: #27ae60; color: #fff; }
.cart-bar .btn-print { background: #007bff; color: #fff; }
.cart-bar .btn-clear { background: #e84118; color: #fff; }
.cart-bar .cart-options { display: flex; align-items: center; gap: 6px; font-size: 0.8rem; }
.cart-bar .cart-options input { cursor: pointer; }
.bulk-checkbox { width: 18px; height: 18px; cursor: pointer; }
</style>

<div class="admin-section">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px;">
        <div>
            <h1 style="margin:0;font-size:1.2rem;color:#0d3b3b;">📜 Certificate & Marksheet Status</h1>
            <p style="margin:4px 0 0;font-size:0.82rem;color:#666;">Track all requests. Select multiple to bulk download or print.</p>
        </div>
        <a href="<?= $bp ?>/branch/cert-gen/new" style="background:linear-gradient(135deg,#16a085,#117a65);color:#fff;text-decoration:none;padding:11px 22px;border-radius:8px;font-size:0.86rem;font-weight:600;box-shadow:0 4px 12px rgba(22,160,133,0.25);">
            + New Student Registration
        </a>
    </div>

    <!-- Stats -->
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:18px;">
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);border-left:4px solid #0d3b3b;">
            <div style="font-size:1.6rem;font-weight:700;color:#0d3b3b;"><?= (int)$stats['total'] ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;">Total Requests</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);border-left:4px solid #f39c12;">
            <div style="font-size:1.6rem;font-weight:700;color:#f39c12;"><?= (int)$stats['pending'] ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;">Pending Approval</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);border-left:4px solid #27ae60;">
            <div style="font-size:1.6rem;font-weight:700;color:#27ae60;"><?= (int)$stats['approved'] ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;">Approved (PDF Ready)</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);border-left:4px solid #e84118;">
            <div style="font-size:1.6rem;font-weight:700;color:#e84118;"><?= (int)$stats['rejected'] ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;">Rejected</div>
        </div>
    </div>

    <!-- Documents table -->
    <div style="background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06);margin-bottom:80px;">
        <?php if (empty($documents)): ?>
            <div style="text-align:center;padding:60px 20px;color:#999;">
                <div style="font-size:3rem;margin-bottom:10px;">📜</div>
                <p style="margin:0 0 6px;font-size:1rem;color:#666;">No certificate/marksheet requests yet</p>
                <p style="margin:0 0 16px;font-size:0.84rem;">Click "New Student Registration" above to start.</p>
                <a href="<?= $bp ?>/branch/cert-gen/new" style="background:#16a085;color:#fff;text-decoration:none;padding:9px 20px;border-radius:6px;font-size:0.82rem;font-weight:600;">+ Register New Student</a>
            </div>
        <?php else: ?>
            <div style="overflow-x:auto;">
                <table style="width:100%;border-collapse:collapse;font-size:0.84rem;">
                    <thead><tr style="background:#f8f9fa;border-bottom:2px solid #dee2e6;">
                        <th style="padding:11px;text-align:center;width:40px;">
                            <input type="checkbox" class="bulk-checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                        </th>
                        <th style="padding:11px;text-align:left;">Doc Number</th>
                        <th style="padding:11px;text-align:left;">Type</th>
                        <th style="padding:11px;text-align:left;">Student</th>
                        <th style="padding:11px;text-align:center;">Session</th>
                        <th style="padding:11px;text-align:center;">Grade</th>
                        <th style="padding:11px;text-align:center;">%</th>
                        <th style="padding:11px;text-align:center;">Status</th>
                        <th style="padding:11px;text-align:left;">Submitted</th>
                        <th style="padding:11px;text-align:right;">Actions</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($documents as $d):
                        $subjectsData = [];
                        if (!empty($d['subjects_json'])) {
                            $subjectsData = json_decode($d['subjects_json'], true) ?: [];
                        }
                        $fromLabel = $subjectsData['from_label'] ?? '';
                        $toLabel = $subjectsData['to_label'] ?? '';
                        if (empty($fromLabel) && !empty($d['session_from'])) {
                            $dt = \DateTime::createFromFormat('Y-m-d', $d['session_from']);
                            if ($dt) $fromLabel = strtoupper($dt->format('M Y'));
                        }
                        if (empty($toLabel) && !empty($d['session_to'])) {
                            $dt = \DateTime::createFromFormat('Y-m-d', $d['session_to']);
                            if ($dt) $toLabel = strtoupper($dt->format('M Y'));
                        }
                        $isGenerated = ($d['status'] ?? '') === 'generated';
                    ?>
                        <tr style="border-bottom:1px solid #f0f0f0;" id="row-<?= (int)$d['id'] ?>">
                            <td style="padding:11px;text-align:center;">
                                <?php if ($isGenerated): ?>
                                <input type="checkbox" class="bulk-checkbox row-checkbox" value="<?= (int)$d['id'] ?>" onchange="updateCart()">
                                <?php else: ?>
                                <span style="color:#ccc;">—</span>
                                <?php endif; ?>
                            </td>
                            <td style="padding:11px;font-family:monospace;font-weight:600;color:#16a085;"><?= htmlspecialchars($d['certificate_no'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                            <td style="padding:11px;"><?= $docTypeLabels[$d['doc_type']] ?? htmlspecialchars(ucfirst($d['doc_type'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                            <td style="padding:11px;font-weight:600;color:#0d3b3b;"><?= htmlspecialchars($d['student_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                            <td style="padding:11px;text-align:center;font-size:0.78rem;">
                                <?php if (!empty($fromLabel) || !empty($toLabel)): ?>
                                    <strong style="color:#6c3fe8;"><?= htmlspecialchars($fromLabel ?: '—') ?></strong>
                                    <span style="color:#999;"> → </span>
                                    <strong style="color:#6c3fe8;"><?= htmlspecialchars($toLabel ?: '—') ?></strong>
                                <?php else: ?>
                                    <span style="color:#ccc;">—</span>
                                <?php endif; ?>
                            </td>
                            <td style="padding:11px;text-align:center;font-weight:600;color:#1a4fa0;"><?= htmlspecialchars($d['grade'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                            <td style="padding:11px;text-align:center;font-weight:600;color:#16a085;"><?= htmlspecialchars($d['percentage'] ?? '0', ENT_QUOTES, 'UTF-8') ?>%</td>
                            <td style="padding:11px;text-align:center;">
                                <span style="padding:3px 10px;border-radius:12px;font-size:0.72rem;font-weight:600;color:#fff;background:<?= $statusColors[$d['status']] ?? '#999' ?>;">
                                    <?= htmlspecialchars($statusLabels[$d['status']] ?? ucfirst($d['status'] ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            </td>
                            <td style="padding:11px;font-size:0.76rem;color:#999;"><?= !empty($d['created_at']) ? date('d M Y', strtotime($d['created_at'])) : '—' ?></td>
                            <td style="padding:11px;text-align:right;white-space:nowrap;">
                                <?php if ($isGenerated): ?>
                                    <a href="<?= $bp ?>/branch/cert-gen/<?= (int)$d['id'] ?>/download" style="background:#27ae60;color:#fff;text-decoration:none;padding:4px 8px;border-radius:4px;font-size:0.7rem;font-weight:600;" title="Download PDF">⬇</a>
                                    <a href="<?= $bp ?>/branch/cert-gen/<?= (int)$d['id'] ?>/download-combined" style="background:#16a085;color:#fff;text-decoration:none;padding:4px 8px;border-radius:4px;font-size:0.7rem;font-weight:600;" title="Combined Cert+Marksheet" target="_blank">🔗</a>
                                <?php elseif (($d['status'] ?? '') === 'pending_approval'): ?>
                                    <span style="color:#f39c12;font-size:0.7rem;">⏳</span>
                                <?php elseif (($d['status'] ?? '') === 'rejected'): ?>
                                    <span style="color:#e84118;font-size:0.7rem;">✗</span>
                                <?php endif; ?>
                                <a href="<?= $bp ?>/branch/cert-gen/edit/<?= (int)$d['id'] ?>" style="background:#007bff;color:#fff;text-decoration:none;padding:4px 8px;border-radius:4px;font-size:0.7rem;font-weight:600;" title="Edit">✎</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- ✅ CART BAR (fixed at bottom) -->
<div class="cart-bar" id="cartBar">
    <div class="cart-info">
        🛒 <span class="cart-count" id="cartCount">0</span> document(s) selected
    </div>
    <div class="cart-options">
        <label style="cursor:pointer;">
            <input type="checkbox" id="includeBoth"> Include both Cert + Marksheet for each student
        </label>
    </div>
    <div class="cart-actions">
        <form method="POST" action="<?= $bp ?>/branch/cert-gen/bulk-download" id="downloadForm" target="_blank" style="display:inline;">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="cert_ids" id="downloadIds" value="">
            <input type="hidden" name="include_both" id="downloadIncludeBoth" value="0">
            <input type="hidden" name="mode" value="download">
            <button type="submit" class="cart-btn btn-download" onclick="return prepareBulk('download')">
                ⬇ Download Selected
            </button>
        </form>
        <form method="POST" action="<?= $bp ?>/branch/cert-gen/bulk-download" id="printForm" target="_blank" style="display:inline;">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="cert_ids" id="printIds" value="">
            <input type="hidden" name="include_both" id="printIncludeBoth" value="0">
            <input type="hidden" name="mode" value="print">
            <button type="submit" class="cart-btn btn-print" onclick="return prepareBulk('print')">
                🖨 Print Selected
            </button>
        </form>
        <button class="cart-btn btn-clear" onclick="clearSelection()">✕ Clear</button>
    </div>
</div>

<script>
function toggleSelectAll(checkbox) {
    document.querySelectorAll('.row-checkbox').forEach(cb => {
        cb.checked = checkbox.checked;
    });
    updateCart();
}

function updateCart() {
    const checked = document.querySelectorAll('.row-checkbox:checked');
    const count = checked.length;
    const cartBar = document.getElementById('cartBar');
    const cartCount = document.getElementById('cartCount');

    cartCount.textContent = count;
    if (count > 0) {
        cartBar.classList.add('active');
    } else {
        cartBar.classList.remove('active');
    }

    // Update select-all checkbox state
    const allCheckboxes = document.querySelectorAll('.row-checkbox');
    const selectAll = document.getElementById('selectAll');
    if (allCheckboxes.length > 0 && count === allCheckboxes.length) {
        selectAll.checked = true;
    } else {
        selectAll.checked = false;
    }
}

function prepareBulk(mode) {
    const checked = document.querySelectorAll('.row-checkbox:checked');
    if (checked.length === 0) {
        alert('Please select at least one document.');
        return false;
    }

    const ids = Array.from(checked).map(cb => cb.value);
    const includeBoth = document.getElementById('includeBoth').checked ? '1' : '0';

    if (mode === 'download') {
        document.getElementById('downloadIds').value = ids.join(',');
        document.getElementById('downloadIncludeBoth').value = includeBoth;
    } else {
        document.getElementById('printIds').value = ids.join(',');
        document.getElementById('printIncludeBoth').value = includeBoth;
    }

    return true;
}

function clearSelection() {
    document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = false);
    document.getElementById('selectAll').checked = false;
    document.getElementById('includeBoth').checked = false;
    updateCart();
}
</script>
