<?php
/**
 * ID Cards List — Generate single + Bulk print multiple
 *
 * Upload to: /gmind/branch/Views/id_cards/index.php
 */

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

    .idc-stats-grid {
        display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 12px; margin-bottom: 16px;
    }
    .idc-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;
    }
    .idc-stat-card .icon {
        width: 42px; height: 42px; border-radius: 10px;
        display: flex; align-items: center; justify-content: center;
        font-size: 1.2rem; color: #fff; flex-shrink: 0;
    }
    .idc-stat-card .num { font-size: 1.4rem; font-weight: 700; color: #2c1e4a; line-height: 1; }
    .idc-stat-card .label { font-size: 0.78rem; color: #6b7280; margin-top: 3px; }

    .idc-filter-card {
        background: #fff; border-radius: 10px; padding: 16px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04); margin-bottom: 16px;
    }
    .idc-filter-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: end; }
    .idc-filter-row > div { flex: 1; min-width: 150px; }
    .idc-filter-row label {
        display: block; font-size: 0.76rem; font-weight: 600;
        color: #6b7280; margin-bottom: 4px;
    }
    .idc-filter-row input, .idc-filter-row select {
        width: 100%; padding: 7px 10px; border: 1px solid #d0d5dd;
        border-radius: 6px; font-size: 0.83rem;
    }
    .idc-btn-filter {
        background: #16a085; color: #fff; padding: 7px 16px; border: none;
        border-radius: 6px; font-size: 0.83rem; font-weight: 600; cursor: pointer;
    }
    .idc-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 */
    .idc-cart-bar {
        position: sticky; top: 0; z-index: 50;
        background: linear-gradient(135deg, #6d2126, #4a1418); 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(109,33,38,0.3);
    }
    .idc-cart-info { font-size: 0.9rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
    .idc-cart-count {
        background: rgba(255,255,255,0.25); padding: 3px 10px; border-radius: 12px;
        font-weight: 700; min-width: 30px; text-align: center;
    }
    .idc-cart-actions { display: flex; gap: 8px; flex-wrap: wrap; }
    .idc-btn-print {
        background: #16a085; 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;
    }
    .idc-btn-print:disabled { opacity: 0.5; cursor: not-allowed; }
    .idc-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 */
    .idc-table-card {
        background: #fff; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        overflow: hidden;
    }
    .idc-table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .idc-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; min-width: 700px; }
    .idc-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;
    }
    .idc-table tbody td { padding: 10px; border-bottom: 1px solid #f1f1f1; vertical-align: middle; }
    .idc-table tbody tr:hover { background: #faf8ff; }

    .idc-checkbox { width: 18px; height: 18px; cursor: pointer; accent-color: #6d2126; }
    .idc-avatar {
        width: 32px; height: 32px; border-radius: 50%; object-fit: cover;
        border: 2px solid #e9ecef; background: #f8f9fa;
        display: inline-flex; align-items: center; justify-content: center;
        color: #9ca3af; font-size: 0.9rem;
    }
    .idc-student-name { font-weight: 600; color: #2c1e4a; white-space: nowrap; }
    .idc-enrollment { font-family: monospace; font-size: 0.78rem; color: #6b7280; }
    .idc-course { color: #4b5563; white-space: nowrap; max-width: 140px; overflow: hidden; text-overflow: ellipsis; }
    .idc-btn-generate {
        background: #6d2126; color: #fff; padding: 5px 12px; border: none;
        border-radius: 5px; font-size: 0.75rem; font-weight: 600; text-decoration: none;
        display: inline-flex; align-items: center; gap: 4px;
    }
    .idc-btn-generate:hover { background: #4a1418; color: #fff; }

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

    @media (max-width: 768px) {
        .idc-table thead { display: none; }
        .idc-table, .idc-table tbody, .idc-table tr, .idc-table td {
            display: block; width: 100% !important; min-width: 0 !important;
        }
        .idc-table tr {
            margin-bottom: 12px; border: 1px solid #e9ecef; border-radius: 8px;
            padding: 8px; background: #fff;
        }
        .idc-table tbody td {
            border: none; padding: 6px 4px; display: flex; justify-content: space-between;
            align-items: center; text-align: right;
        }
        .idc-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="idc-page-header">
        <h2><i class="fas fa-id-card"></i> ID Cards Management</h2>
    </div>

    <!-- Stats -->
    <div class="idc-stats-grid">
        <div class="idc-stat-card">
            <div class="icon" style="background:linear-gradient(135deg,#6d2126,#4a1418);"><i class="fas fa-users"></i></div>
            <div>
                <div class="num"><?= count($students) ?></div>
                <div class="label">Total Students</div>
            </div>
        </div>
        <div class="idc-stat-card">
            <div class="icon" style="background:linear-gradient(135deg,#16a085,#117a65);"><i class="fas fa-id-card"></i></div>
            <div>
                <div class="num">2</div>
                <div class="label">Cards per A4 Page</div>
            </div>
        </div>
    </div>

    <!-- Filter -->
    <div class="idc-filter-card">
        <form method="GET" action="<?= $bp ?>/branch/id-cards">
            <div class="idc-filter-row">
                <div>
                    <label>Search</label>
                    <input type="text" name="search" placeholder="Name, enrollment, phone..."
                           value="<?= htmlspecialchars($search ?? '', ENT_QUOTES) ?>">
                </div>
                <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 style="flex: 0 0 auto;">
                    <button type="submit" class="idc-btn-filter"><i class="fas fa-filter"></i> Filter</button>
                </div>
                <div style="flex: 0 0 auto;">
                    <a href="<?= $bp ?>/branch/id-cards" class="idc-btn-reset">Clear</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Cart Action Bar -->
    <div class="idc-cart-bar">
        <div class="idc-cart-info">
            <i class="fas fa-print"></i>
            <span>Selected:</span>
            <span class="idc-cart-count" id="cartCount">0</span>
            <span>student(s)</span>
        </div>
        <div class="idc-cart-actions">
            <button type="button" class="idc-btn-clear" onclick="selectAll()">
                <i class="fas fa-check-double"></i> Select All
            </button>
            <button type="button" class="idc-btn-clear" onclick="clearAll()">
                <i class="fas fa-times"></i> Clear
            </button>
            <form method="POST" action="<?= $bp ?>/branch/id-cards/bulk-print" 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="idc-btn-print" id="printBtn" disabled>
                    <i class="fas fa-print"></i> Print Selected ID Cards (A4)
                </button>
            </form>
        </div>
    </div>

    <!-- Students Table -->
    <div class="idc-table-card">
        <?php if (!empty($students)): ?>
        <div class="idc-table-wrap">
            <table class="idc-table">
                <thead>
                    <tr>
                        <th style="width:40px;"><input type="checkbox" class="idc-checkbox" id="selectAllCb" onchange="toggleAll(this)"></th>
                        <th style="width:50px;">Photo</th>
                        <th>Student</th>
                        <th>Enrollment</th>
                        <th>Course</th>
                        <th>Phone</th>
                        <th style="text-align:right;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $s):
                        $photoPath = '';
                        if (!empty($s['photo'])) {
                            $candidates = [
                                $s['photo'],
                                $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($s['photo'], '/'),
                                $_SERVER['DOCUMENT_ROOT'] . '/gmind/' . ltrim($s['photo'], '/'),
                                '/home/advaysin/public_html/' . ltrim($s['photo'], '/'),
                                '/home/advaysin/public_html/gmind/' . ltrim($s['photo'], '/'),
                            ];
                            foreach ($candidates as $c) {
                                if (file_exists($c)) {
                                    $photoPath = (defined('BASE_PATH') ? BASE_PATH : '/gmind') . '/' . ltrim($s['photo'], '/');
                                    break;
                                }
                            }
                        }
                    ?>
                    <tr>
                        <td data-label="Select">
                            <input type="checkbox" class="idc-checkbox idc-row-cb" value="<?= (int)$s['id'] ?>" onchange="updateCart()">
                        </td>
                        <td data-label="Photo">
                            <?php if (!empty($photoPath)): ?>
                                <img src="<?= htmlspecialchars($photoPath, ENT_QUOTES) ?>" alt="Photo" class="idc-avatar">
                            <?php else: ?>
                                <div class="idc-avatar"><i class="fas fa-user"></i></div>
                            <?php endif; ?>
                        </td>
                        <td data-label="Student">
                            <div class="idc-student-name"><?= htmlspecialchars($s['name'] ?? '—', ENT_QUOTES) ?></div>
                        </td>
                        <td data-label="Enrollment">
                            <span class="idc-enrollment"><?= htmlspecialchars($s['enrollment_no'] ?? '—', ENT_QUOTES) ?></span>
                        </td>
                        <td data-label="Course">
                            <span class="idc-course" title="<?= htmlspecialchars($s['course_name'] ?? '', ENT_QUOTES) ?>">
                                <?= htmlspecialchars($s['course_name'] ?? '—', ENT_QUOTES) ?>
                            </span>
                        </td>
                        <td data-label="Phone">
                            <span style="color:#4b5563; white-space:nowrap;"><?= htmlspecialchars($s['phone'] ?? '—', ENT_QUOTES) ?></span>
                        </td>
                        <td data-label="Action" style="text-align:right;">
                            <a href="<?= $bp ?>/branch/id-cards/generate/<?= (int)$s['id'] ?>" target="_blank" class="idc-btn-generate">
                                <i class="fas fa-id-card"></i> Generate
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="idc-empty">
            <i class="fas fa-id-card"></i>
            <p style="font-size:1.05rem; margin:8px 0;">No students found</p>
            <p style="font-size:0.85rem; color:#9ca3af;">Add students first to generate ID cards.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

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

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

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

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

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 student.');
        return;
    }
    if (!confirm('Generate ID cards for ' + count + ' student(s)?\n\nCards will be arranged 2 per row on A4 page.')) {
        e.preventDefault();
    }
});
</script>
