<?php
/**
 * Print Queue — Bulk Certificate Printing Page
 *
 * Features:
 *   - Filter by course, date range, month, doc type
 *   - Cart system (select multiple certificates)
 *   - Download combined PDF (all selected in one file)
 *
 * Upload to: /gmind/branch/Views/print_queue/index.php
 */

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$csrf = htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8');
?>
<style>
    .pq-page-header {
        display: flex; justify-content: space-between; align-items: center;
        flex-wrap: wrap; gap: 12px; margin-bottom: 20px;
    }
    .pq-page-header h2 { margin: 0; color: #2c1e4a; font-weight: 700; font-size: 1.4rem; }

    .pq-stats-grid {
        display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        gap: 12px; margin-bottom: 16px;
    }
    .pq-stat-card {
        background: #fff; border-radius: 10px; padding: 16px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        display: flex; align-items: center; gap: 12px;
    }
    .pq-stat-card .icon {
        width: 40px; height: 40px; border-radius: 10px;
        display: flex; align-items: center; justify-content: center;
        font-size: 1.2rem; color: #fff; flex-shrink: 0;
    }
    .pq-stat-card .num { font-size: 1.3rem; font-weight: 700; color: #2c1e4a; line-height: 1; }
    .pq-stat-card .label { font-size: 0.78rem; color: #6b7280; margin-top: 3px; }

    .pq-filter-card {
        background: #fff; border-radius: 10px; padding: 16px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04); margin-bottom: 16px;
    }
    .pq-filter-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: end; }
    .pq-filter-row > div { flex: 1; min-width: 130px; }
    .pq-filter-row label {
        display: block; font-size: 0.76rem; font-weight: 600;
        color: #6b7280; margin-bottom: 4px;
    }
    .pq-filter-row input, .pq-filter-row select {
        width: 100%; padding: 7px 10px; border: 1px solid #d0d5dd;
        border-radius: 6px; font-size: 0.83rem;
    }
    .pq-btn-filter {
        background: #6c3fe8; color: #fff; padding: 7px 16px; border: none;
        border-radius: 6px; font-size: 0.83rem; font-weight: 600; cursor: pointer;
    }
    .pq-btn-reset {
        background: #f3f4f6; color: #6b7280; padding: 7px 14px;
        border: 1px solid #d0d5dd; border-radius: 6px; font-size: 0.83rem;
        text-decoration: none; font-weight: 600;
    }

    /* Cart action bar */
    .pq-cart-bar {
        position: sticky; top: 0; z-index: 50;
        background: linear-gradient(135deg, #6c3fe8, #4a2db8); color: #fff;
        padding: 12px 20px; border-radius: 10px; margin-bottom: 12px;
        display: flex; justify-content: space-between; align-items: center;
        flex-wrap: wrap; gap: 10px; box-shadow: 0 4px 12px rgba(108,63,232,0.3);
    }
    .pq-cart-info { font-size: 0.9rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
    .pq-cart-count {
        background: rgba(255,255,255,0.25); padding: 3px 10px; border-radius: 12px;
        font-weight: 700; min-width: 30px; text-align: center;
    }
    .pq-cart-actions { display: flex; gap: 8px; flex-wrap: wrap; }
    .pq-btn-download {
        background: #dc2626; color: #fff; padding: 8px 18px; border: none;
        border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.85rem;
        display: inline-flex; align-items: center; gap: 6px;
    }
    .pq-btn-download:disabled { opacity: 0.5; cursor: not-allowed; }
    .pq-btn-clear {
        background: rgba(255,255,255,0.2); color: #fff; padding: 8px 14px;
        border: 1px solid rgba(255,255,255,0.3); border-radius: 6px; cursor: pointer;
        font-size: 0.83rem; font-weight: 600;
    }

    /* Table */
    .pq-table-card {
        background: #fff; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        overflow: hidden;
    }
    .pq-table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .pq-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; min-width: 800px; }
    .pq-table thead th {
        background: #f8f4ff; color: #6c3fe8; font-weight: 700; font-size: 0.74rem;
        text-transform: uppercase; letter-spacing: 0.5px; padding: 12px 10px;
        text-align: left; white-space: nowrap; border-bottom: 2px solid #6c3fe8;
    }
    .pq-table tbody td { padding: 10px; border-bottom: 1px solid #f1f1f1; vertical-align: middle; }
    .pq-table tbody tr:hover { background: #faf8ff; }

    .pq-checkbox { width: 18px; height: 18px; cursor: pointer; accent-color: #6c3fe8; }
    .pq-student-name { font-weight: 600; color: #2c1e4a; white-space: nowrap; }
    .pq-enrollment { font-family: monospace; font-size: 0.78rem; color: #6b7280; }
    .pq-doc-type {
        display: inline-block; padding: 3px 10px; border-radius: 12px;
        font-size: 0.7rem; font-weight: 700; text-transform: uppercase;
    }
    .pq-doc-certificate { background: #dbeafe; color: #2563eb; }
    .pq-doc-marksheet   { background: #fef3c7; color: #d97706; }
    .pq-date { color: #4b5563; white-space: nowrap; font-size: 0.82rem; }
    .pq-cert-no { font-family: monospace; font-size: 0.78rem; color: #4b5563; }

    .pq-empty {
        text-align: center; padding: 60px 20px; color: #9ca3af;
    }
    .pq-empty i { font-size: 3rem; opacity: 0.3; margin-bottom: 12px; }

    @media (max-width: 768px) {
        .pq-table thead { display: none; }
        .pq-table, .pq-table tbody, .pq-table tr, .pq-table td {
            display: block; width: 100% !important; min-width: 0 !important;
        }
        .pq-table tr {
            margin-bottom: 12px; border: 1px solid #e9ecef; border-radius: 8px;
            padding: 8px; background: #fff;
        }
        .pq-table tbody td {
            border: none; padding: 6px 4px; display: flex; justify-content: space-between;
            align-items: center; text-align: right;
        }
        .pq-table tbody td::before {
            content: attr(data-label); font-weight: 600; color: #6c3fe8;
            text-align: left; font-size: 0.74rem; text-transform: uppercase;
            padding-right: 10px;
        }
    }
</style>

<div class="container-fluid py-3">
    <!-- Page Header -->
    <div class="pq-page-header">
        <h2><i class="fas fa-print"></i> Print Queue — Bulk Certificate Printing</h2>
    </div>

    <!-- Stats -->
    <div class="pq-stats-grid">
        <div class="pq-stat-card">
            <div class="icon" style="background:linear-gradient(135deg,#6c3fe8,#4a2db8);"><i class="fas fa-file-alt"></i></div>
            <div>
                <div class="num"><?= (int)($stats['total'] ?? 0) ?></div>
                <div class="label">Total Documents</div>
            </div>
        </div>
        <div class="pq-stat-card">
            <div class="icon" style="background:linear-gradient(135deg,#2563eb,#1d4ed8);"><i class="fas fa-award"></i></div>
            <div>
                <div class="num"><?= (int)($stats['cert_count'] ?? 0) ?></div>
                <div class="label">Certificates</div>
            </div>
        </div>
        <div class="pq-stat-card">
            <div class="icon" style="background:linear-gradient(135deg,#d97706,#b45309);"><i class="fas fa-clipboard-list"></i></div>
            <div>
                <div class="num"><?= (int)($stats['ms_count'] ?? 0) ?></div>
                <div class="label">Marksheets</div>
            </div>
        </div>
    </div>

    <!-- Filter -->
    <div class="pq-filter-card">
        <form method="GET" action="<?= $bp ?>/branch/print-queue">
            <div class="pq-filter-row">
                <div>
                    <label>Course</label>
                    <select name="course_id">
                        <option value="">All Courses</option>
                        <?php foreach ($courses as $c): ?>
                        <option value="<?= (int)$c['id'] ?>" <?= ($courseFilter == (string)$c['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name'], ENT_QUOTES) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Month</label>
                    <select name="month">
                        <option value="">All Months</option>
                        <?php foreach ($months as $val => $lbl): ?>
                        <option value="<?= htmlspecialchars($val, ENT_QUOTES) ?>" <?= ($monthFilter === $val) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($lbl, ENT_QUOTES) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Date From</label>
                    <input type="date" name="date_from" value="<?= htmlspecialchars($dateFrom, ENT_QUOTES) ?>">
                </div>
                <div>
                    <label>Date To</label>
                    <input type="date" name="date_to" value="<?= htmlspecialchars($dateTo, ENT_QUOTES) ?>">
                </div>
                <div>
                    <label>Type</label>
                    <select name="doc_type">
                        <option value="">Both</option>
                        <option value="certificate" <?= ($docType === 'certificate') ? 'selected' : '' ?>>Certificate</option>
                        <option value="marksheet" <?= ($docType === 'marksheet') ? 'selected' : '' ?>>Marksheet</option>
                    </select>
                </div>
                <div style="flex: 0 0 auto;">
                    <button type="submit" class="pq-btn-filter"><i class="fas fa-filter"></i> Filter</button>
                </div>
                <div style="flex: 0 0 auto;">
                    <a href="<?= $bp ?>/branch/print-queue" class="pq-btn-reset">Clear</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Cart Action Bar -->
    <div class="pq-cart-bar">
        <div class="pq-cart-info">
            <i class="fas fa-shopping-cart"></i>
            <span>Selected:</span>
            <span class="pq-cart-count" id="cartCount">0</span>
            <span>document(s)</span>
        </div>
        <div class="pq-cart-actions">
            <button type="button" class="pq-btn-clear" onclick="selectAll()">
                <i class="fas fa-check-double"></i> Select All
            </button>
            <button type="button" class="pq-btn-clear" onclick="clearAll()">
                <i class="fas fa-times"></i> Clear
            </button>
            <form method="POST" action="<?= $bp ?>/branch/print-queue/bulk-download" id="bulkForm" style="display:inline;">
                <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                <input type="hidden" name="selected" id="selectedInput" value="">
                <button type="submit" class="pq-btn-download" id="downloadBtn" disabled>
                    <i class="fas fa-file-pdf"></i> Download Combined PDF
                </button>
            </form>
        </div>
    </div>

    <!-- Documents Table -->
    <div class="pq-table-card">
        <?php if (!empty($documents)): ?>
        <div class="pq-table-wrap">
            <table class="pq-table">
                <thead>
                    <tr>
                        <th style="width:40px;"><input type="checkbox" class="pq-checkbox" id="selectAllCb" onchange="toggleAll(this)"></th>
                        <th>Cert No</th>
                        <th>Student</th>
                        <th>Course</th>
                        <th>Type</th>
                        <th>Issued</th>
                        <th>Grade</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($documents as $d): ?>
                    <tr>
                        <td data-label="Select">
                            <input type="checkbox" class="pq-checkbox pq-row-cb" value="<?= (int)$d['id'] ?>" onchange="updateCart()">
                        </td>
                        <td data-label="Cert No">
                            <div class="pq-cert-no"><?= htmlspecialchars($d['certificate_no'] ?? '—', ENT_QUOTES) ?></div>
                            <div class="pq-enrollment"><?= htmlspecialchars($d['enrollment_no'] ?? '', ENT_QUOTES) ?></div>
                        </td>
                        <td data-label="Student">
                            <div class="pq-student-name"><?= htmlspecialchars($d['student_name'] ?? '—', ENT_QUOTES) ?></div>
                        </td>
                        <td data-label="Course">
                            <span style="color:#4b5563;"><?= htmlspecialchars($d['course_name'] ?? '—', ENT_QUOTES) ?></span>
                        </td>
                        <td data-label="Type">
                            <?php
                            $dt = $d['doc_type'] ?? 'certificate';
                            $dtCls = $dt === 'marksheet' ? 'pq-doc-marksheet' : 'pq-doc-certificate';
                            ?>
                            <span class="pq-doc-type <?= $dtCls ?>"><?= htmlspecialchars(ucfirst($dt), ENT_QUOTES) ?></span>
                        </td>
                        <td data-label="Issued">
                            <span class="pq-date"><?= !empty($d['issue_date']) ? date('d M Y', strtotime($d['issue_date'])) : '—' ?></span>
                        </td>
                        <td data-label="Grade">
                            <strong style="color:#16a085;"><?= htmlspecialchars($d['grade'] ?? '—', ENT_QUOTES) ?></strong>
                            <span style="color:#6b7280; font-size:0.78rem;"><?= htmlspecialchars(number_format((float)($d['percentage'] ?? 0), 1), ENT_QUOTES) ?>%</span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="pq-empty">
            <i class="fas fa-inbox"></i>
            <p style="font-size:1.05rem; margin:8px 0;">No approved certificates found</p>
            <p style="font-size:0.85rem; color:#9ca3af;">Once certificates are approved by Super Admin, they will appear here for bulk printing.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function updateCart() {
    const checked = document.querySelectorAll('.pq-row-cb:checked');
    const count = checked.length;
    document.getElementById('cartCount').textContent = count;
    document.getElementById('downloadBtn').disabled = (count === 0);
    const ids = Array.from(checked).map(cb => cb.value);
    document.getElementById('selectedInput').value = ids.join(',');
}

function toggleAll(master) {
    document.querySelectorAll('.pq-row-cb').forEach(cb => {
        cb.checked = master.checked;
    });
    updateCart();
}

function selectAll() {
    document.querySelectorAll('.pq-row-cb').forEach(cb => cb.checked = true);
    document.getElementById('selectAllCb').checked = true;
    updateCart();
}

function clearAll() {
    document.querySelectorAll('.pq-row-cb').forEach(cb => cb.checked = false);
    document.getElementById('selectAllCb').checked = false;
    updateCart();
}

// Confirm before bulk download
document.getElementById('bulkForm')?.addEventListener('submit', function(e) {
    const count = parseInt(document.getElementById('cartCount').textContent) || 0;
    if (count === 0) {
        e.preventDefault();
        alert('Please select at least one document to download.');
        return;
    }
    if (!confirm('Download ' + count + ' document(s) as a combined PDF?')) {
        e.preventDefault();
    }
});
</script>
