<?php

/**

 * Bulk print all student ID cards — 2-up per A4 sheet.

 * Access: Admin only.

 * Optional: ?class=Basic+6 to filter by class.

 */

if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }



$allowed_roles = ['admin', 'headteacher'];

if (!in_array($_SESSION['role'] ?? '', $allowed_roles)) {

    header('Location: ../dashboard.php?error=access_denied');

    exit;

}



require_once '../config.php';

require_once '../includes/canteen_helpers.php';



$conn = getDBConnection();



$class_filter = trim((string) ($_GET['class'] ?? ''));



// Auto-generate missing tokens first

$missing_stmt = $conn->prepare(

    "SELECT id FROM students WHERE status = 'active' AND identity_qr_token IS NULL"

);

$missing_stmt->execute();

$missing = $missing_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$missing_stmt->close();



if (!empty($missing)) {

    $upd = $conn->prepare(

        "UPDATE students SET identity_qr_token = ?, identity_qr_generated_at = ? WHERE id = ?"

    );

    $now = date('Y-m-d H:i:s');

    foreach ($missing as $m) {

        $token = canteen_generate_identity_token($m['id']);

        $upd->bind_param('ssi', $token, $now, $m['id']);

        $upd->execute();

    }

    $upd->close();

}



// Load students

$sql = "SELECT id, first_name, last_name, class, student_id AS student_code,

               photo_path, identity_qr_token

        FROM students WHERE status = 'active'";

$types = '';

$binds = [];

if ($class_filter !== '') {

    $sql   .= " AND class = ?";

    $types .= 's';

    $binds[]= $class_filter;

}

$sql .= " ORDER BY class, first_name, last_name";



$stmt = $conn->prepare($sql);

if ($types) $stmt->bind_param($types, ...$binds);

$stmt->execute();

$students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$stmt->close();



// Classes for filter dropdown — primary: Class Management table; fallback: students

$classes = [];

$cRes = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");

if ($cRes) while ($r = $cRes->fetch_assoc()) $classes[] = $r['class_name'];

$cRes2 = $conn->query("SELECT DISTINCT class FROM students WHERE status = 'active' AND class IS NOT NULL ORDER BY class");

if ($cRes2) while ($r = $cRes2->fetch_assoc()) { if (!in_array($r['class'], $classes)) $classes[] = $r['class']; }

sort($classes);



// School info

$school_info = [];

$sRes = $conn->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('school_name','school_logo')");

while ($r = $sRes->fetch_assoc()) $school_info[$r['setting_key']] = $r['setting_value'];

$school_name = $school_info['school_name'] ?? 'School';

$school_logo = $school_info['school_logo'] ?? null;



$conn->close();

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Print All ID Cards — <?php echo htmlspecialchars($school_name); ?></title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

    <style>

        @media screen {

            body { background: #f1f5f9; padding: 1.5rem; }

            .controls { max-width: 900px; margin: 0 auto 1.5rem; }

            .cards-grid { display: grid; grid-template-columns: repeat(2, 105mm); gap: 10mm; justify-content: center; }

        }



        .id-card {

            width: 105mm;

            min-height: 148mm;

            background: #fff;

            border-radius: 8px;

            overflow: hidden;

            display: flex;

            flex-direction: column;

            break-inside: avoid;

            border: 1px solid #e2e8f0;

        }

        .card-header-bar {

            background: linear-gradient(135deg, #1e3a5f, #1e40af);

            color: #fff;

            padding: 10px 14px;

            display: flex; align-items: center; gap: 8px;

        }

        .logo-img { width: 30px; height: 30px; border-radius: 50%; object-fit: cover; background: #fff; }

        .logo-ph { width: 30px; height: 30px; border-radius: 50%; background: rgba(255,255,255,.2); display: flex; align-items: center; justify-content: center; font-size: 1rem; }

        .school-name-txt { font-size: .7rem; font-weight: 700; line-height: 1.2; }

        .card-type-txt { font-size: .55rem; opacity: .8; }



        .card-body-inner { flex: 1; padding: 12px 14px; display: flex; flex-direction: column; align-items: center; }

        .student-photo-img { width: 65px; height: 65px; border-radius: 50%; object-fit: cover; border: 3px solid #1e3a5f; margin-bottom: 8px; }

        .photo-ph { width: 65px; height: 65px; border-radius: 50%; background: #e2e8f0; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; color: #94a3b8; border: 3px solid #1e3a5f; margin-bottom: 8px; }

        .student-name-txt { font-size: .88rem; font-weight: 700; color: #1e293b; text-align: center; margin-bottom: 3px; }

        .student-meta-txt { font-size: .67rem; color: #475569; text-align: center; margin-bottom: 10px; }

        .student-meta-txt span { background: #f1f5f9; padding: 1px 7px; border-radius: 20px; margin: 1px; display: inline-block; }

        .qr-note-txt { font-size: .57rem; color: #64748b; text-align: center; margin-top: 5px; }

        .card-footer-bar { background: #f8fafc; border-top: 1px solid #e2e8f0; padding: 6px 14px; font-size: .57rem; color: #94a3b8; text-align: center; }



        @media print {

            @page { size: A4 portrait; margin: 10mm; }

            body { background: #fff; padding: 0; }

            .controls, .no-print { display: none !important; }

            .cards-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8mm; }

            .id-card { box-shadow: none; width: 100%; }

        }

    </style>

</head>

<body>



<div class="controls no-print">

    <div class="d-flex align-items-center gap-3 mb-3">

        <div style="background:linear-gradient(135deg,#1e3a5f,#1e40af);width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center">

            <i class="fas fa-id-card text-white"></i>

        </div>

        <div>

            <h5 class="mb-0 fw-bold">Print All Student ID Cards</h5>

            <p class="mb-0 text-muted small"><?php echo count($students); ?> students loaded</p>

        </div>

    </div>

    <div class="d-flex gap-2 flex-wrap align-items-end">

        <form method="GET" class="d-flex gap-2 align-items-end">

            <div>

                <label class="form-label small mb-1 text-muted">Filter by class</label>

                <select name="class" class="form-select form-select-sm" style="min-width:140px">

                    <option value="">All classes</option>

                    <?php foreach ($classes as $c): ?>

                        <option value="<?php echo htmlspecialchars($c); ?>" <?php echo $class_filter === $c ? 'selected' : ''; ?>>

                            <?php echo htmlspecialchars($c); ?>

                        </option>

                    <?php endforeach; ?>

                </select>

            </div>

            <button type="submit" class="btn btn-outline-secondary btn-sm">Filter</button>

        </form>

        <button class="btn btn-primary btn-sm" onclick="window.print()">

            <i class="fas fa-print me-1"></i>Print <?php echo count($students); ?> Cards

        </button>

        <a href="../canteen/settings.php?tab=idcards" class="btn btn-outline-secondary btn-sm">

            <i class="fas fa-arrow-left me-1"></i>Back to Settings

        </a>

    </div>

</div>



<div class="cards-grid" id="cardsGrid">

    <?php foreach ($students as $idx => $s):

        $full_name    = $s['first_name'] . ' ' . $s['last_name'];

        $photo_url    = (!empty($s['photo_path']) && file_exists('../' . $s['photo_path']))

                        ? '../' . $s['photo_path'] : '';

    ?>

    <div class="id-card">

        <div class="card-header-bar">

            <?php if ($school_logo && file_exists('../' . $school_logo)): ?>

                <img src="../<?php echo htmlspecialchars($school_logo); ?>" class="logo-img" alt="">

            <?php else: ?>

                <div class="logo-ph"><i class="fas fa-school"></i></div>

            <?php endif; ?>

            <div>

                <div class="school-name-txt"><?php echo htmlspecialchars($school_name); ?></div>

                <div class="card-type-txt">Student ID Card</div>

            </div>

        </div>

        <div class="card-body-inner">

            <?php if ($photo_url): ?>

                <img src="<?php echo htmlspecialchars($photo_url); ?>" class="student-photo-img" alt="">

            <?php else: ?>

                <div class="photo-ph"><i class="fas fa-user"></i></div>

            <?php endif; ?>

            <div class="student-name-txt"><?php echo htmlspecialchars($full_name); ?></div>

            <div class="student-meta-txt">

                <span><?php echo htmlspecialchars($s['class'] ?? ''); ?></span>

                <span><?php echo htmlspecialchars($s['student_code'] ?? ''); ?></span>

            </div>

            <div id="qr_<?php echo $idx; ?>"></div>

            <div class="qr-note-txt">Show at the fee collection window</div>

        </div>

        <div class="card-footer-bar"><?php echo htmlspecialchars($school_name); ?> · <?php echo date('Y'); ?></div>

    </div>

    <?php endforeach; ?>

</div>



<script>

const students = <?php echo json_encode(array_map(fn($s) => [

    'idx'   => array_search($s, $students),

    'token' => $s['identity_qr_token'] ?? '',

], $students)); ?>;



students.forEach((s, i) => {

    const el = document.getElementById('qr_' + i);

    if (!el || !s.token) return;

    new QRCode(el, {

        text: s.token,

        width: 110,

        height: 110,

        colorDark: '#1e293b',

        colorLight: '#ffffff',

        correctLevel: QRCode.CorrectLevel.M

    });

});

</script>

</body>

</html>

