<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

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

$exam_id    = $_GET['exam_id']    ?? '';
$class_id   = $_GET['class_id']   ?? '';
$session    = $_GET['session']    ?? '';
$group_name = $_GET['group_name'] ?? '';
$roll_from  = isset($_GET['roll_from']) && $_GET['roll_from'] !== '' ? (int)$_GET['roll_from'] : null;
$roll_to    = isset($_GET['roll_to'])   && $_GET['roll_to']   !== '' ? (int)$_GET['roll_to']   : null;
$filter_group = $_GET['filter_group'] ?? ''; // extra group filter on top of exam

// Get site settings
$settings     = get_all_settings($pdo);
$site_name    = $settings['site_name']    ?? 'প্রতিষ্ঠানের নাম';
$site_address = $settings['site_address'] ?? 'ঠিকানা, ফোন: ০১৭xxxxxxxx';
$logo_image   = $settings['logo_image']   ?? '';
$logo_size    = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Get exam details
$exam_details  = null;
$exam_subjects = [];

if ($exam_id) {
    $stmt = $pdo->prepare("
        SELECT e.*, c.name as class_name, c.section
        FROM exams e JOIN classes c ON e.class_id = c.id
        WHERE e.id = ?
    ");
    $stmt->execute([$exam_id]);
    $exam_details = $stmt->fetch();

    if ($exam_details) {
        $stmt = $pdo->prepare("
            SELECT es.*, s.name as subject_name, s.code as subject_code
            FROM exam_subjects es JOIN subjects s ON es.subject_id = s.id
            WHERE es.exam_id = ? ORDER BY es.exam_date, es.start_time
        ");
        $stmt->execute([$exam_id]);
        $exam_subjects = $stmt->fetchAll();
    }
}

// Build student query
$students = [];
if (($exam_id && $exam_details) || ($class_id && $session)) {
    $sql    = "SELECT s.*, c.name as class_name, c.section
               FROM students s JOIN classes c ON s.class_id = c.id
               WHERE s.status = 'active'";
    $params = [];

    if ($exam_id && $exam_details) {
        $sql .= " AND s.class_id = ? AND s.session = ?";
        $params[] = $exam_details['class_id'];
        $params[] = $exam_details['session'];
        // filter_group overrides exam group_name; if neither set, no group filter
        $effective_group = ($filter_group !== '') ? $filter_group : $exam_details['group_name'];
        if ($effective_group) {
            $sql .= " AND (s.group_name = ? OR UPPER(s.group_name) = UPPER(?))";
            $params[] = $effective_group;
            $params[] = $effective_group;
        }
    } else {
        $sql .= " AND s.class_id = ? AND s.session = ?";
        $params[] = $class_id;
        $params[] = $session;
        if ($group_name !== '') {
            $sql .= " AND (s.group_name = ? OR UPPER(s.group_name) = UPPER(?))";
            $params[] = $group_name;
            $params[] = $group_name;
        }
    }

    // Roll range filter
    if ($roll_from !== null) {
        $sql .= " AND CAST(s.roll_number AS UNSIGNED) >= ?";
        $params[] = $roll_from;
    }
    if ($roll_to !== null) {
        $sql .= " AND CAST(s.roll_number AS UNSIGNED) <= ?";
        $params[] = $roll_to;
    }

    $sql .= " ORDER BY CAST(s.roll_number AS UNSIGNED), s.first_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
}

// Seat arrangements
$seat_arrangements = [];
if ($exam_id && !empty($students)) {
    $student_ids  = array_column($students, 'id');
    $placeholders = str_repeat('?,', count($student_ids) - 1) . '?';
    $stmt = $pdo->prepare("
        SELECT sa.*, s.student_id FROM seat_arrangements sa
        JOIN students s ON sa.student_id = s.id
        WHERE sa.exam_id = ? AND sa.student_id IN ($placeholders)
    ");
    $stmt->execute(array_merge([$exam_id], $student_ids));
    foreach ($stmt->fetchAll() as $r) {
        $seat_arrangements[$r['student_id']] = $r;
    }
}

function getStudentSubjects($pdo, $exam_id, $student_id) {
    $stmt = $pdo->prepare("
        SELECT es.*, s.name as subject_name, s.code as subject_code
        FROM exam_subjects es JOIN subjects s ON es.subject_id = s.id
        JOIN student_subjects ss ON es.subject_id = ss.subject_id
        WHERE es.exam_id = ? AND ss.student_id = ?
        ORDER BY es.exam_date, es.start_time
    ");
    $stmt->execute([$exam_id, $student_id]);
    return $stmt->fetchAll();
}

// Dropdowns
$all_exams = $pdo->query("
    SELECT e.id, e.name, c.name as class_name, c.section, e.session, e.group_name
    FROM exams e JOIN classes c ON e.class_id = c.id ORDER BY e.created_at DESC
")->fetchAll();
$classes  = $pdo->query("SELECT id, name, section FROM classes WHERE status='active' ORDER BY name, section")->fetchAll();
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status='active' ORDER BY session_name DESC")->fetchAll();
$groups   = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll();

$has_results = ((!$exam_id && $class_id && $session) || ($exam_id && $exam_details));
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>বাল্ক এডমিট কার্ড</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{font-family:'Hind Siliguri',sans-serif!important}
i[class*="fa-"],i[class*="fa-"]::before{font-family:'Font Awesome 6 Free','FontAwesome'!important;font-weight:900!important}
:root{
  --navy:#1a1a2e;--purple:#7209b7;--teal:#06d6a0;--orange:#fb8500;
  --pink:#e63946;--green:#006747;--blue:#4361ee;--gold:#ffd700;
}
body{background:#f0f2f8;color:#1a1a2e}

/* ── TOP BAR ── */
.top-bar{background:linear-gradient(135deg,var(--navy),#16213e);padding:12px 24px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 4px 20px rgba(0,0,0,.25)}
.top-bar .brand{color:#fff;font-size:1.1rem;font-weight:700;text-decoration:none;display:flex;align-items:center;gap:10px}
.top-bar .brand i{color:var(--gold)}
.top-bar .nav-links{display:flex;gap:6px;flex-wrap:wrap}
.top-bar .nav-links a{color:rgba(255,255,255,.8);text-decoration:none;padding:5px 12px;border-radius:20px;font-size:.82rem;transition:all .2s}
.top-bar .nav-links a:hover{background:rgba(255,255,255,.15);color:#fff}

/* ── FILTER CARD ── */
.filter-card{background:#fff;border-radius:16px;box-shadow:0 6px 24px rgba(0,0,0,.08);overflow:hidden;margin-bottom:20px}
.filter-card-header{background:linear-gradient(135deg,var(--purple),var(--blue));padding:14px 20px;color:#fff;display:flex;align-items:center;gap:10px}
.filter-card-header h5{margin:0;font-size:1rem;font-weight:700}
.filter-card-body{padding:20px}

/* ── FORM CONTROLS ── */
.form-label{font-size:.8rem;font-weight:700;color:#555;margin-bottom:4px}
.form-control,.form-select{border-radius:10px!important;border:1.5px solid #e0e0e0;font-size:.88rem;padding:8px 12px;transition:border-color .2s,box-shadow .2s}
.form-control:focus,.form-select:focus{border-color:var(--purple);box-shadow:0 0 0 3px rgba(114,9,183,.12)}
.input-group-text{border-radius:10px 0 0 10px!important;background:#f5f5f5;border:1.5px solid #e0e0e0;color:#888}

/* ── FILTER SECTION DIVIDERS ── */
.filter-divider{display:flex;align-items:center;gap:8px;margin:14px 0 10px;color:#888;font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px}
.filter-divider::before,.filter-divider::after{content:'';flex:1;height:1px;background:#e8e8e8}

/* ── BUTTONS ── */
.btn-search{background:linear-gradient(135deg,var(--purple),var(--blue));color:#fff;border:none;border-radius:10px;padding:9px 24px;font-weight:700;font-size:.9rem;transition:all .2s}
.btn-search:hover{opacity:.88;transform:translateY(-1px);color:#fff}
.btn-print-all{background:linear-gradient(135deg,var(--green),#004d35);color:#fff;border:none;border-radius:10px;padding:8px 20px;font-weight:700;font-size:.88rem;transition:all .2s}
.btn-print-all:hover{opacity:.88;color:#fff}
.btn-print-filtered{background:linear-gradient(135deg,var(--orange),#c96a00);color:#fff;border:none;border-radius:10px;padding:8px 20px;font-weight:700;font-size:.88rem;transition:all .2s;display:none}
.btn-print-filtered:hover{opacity:.88;color:#fff}
.btn-reset{background:#f0f0f0;color:#555;border:none;border-radius:10px;padding:8px 16px;font-size:.88rem;transition:all .2s}
.btn-reset:hover{background:#e0e0e0}

/* ── STATS BAR ── */
.stats-bar{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px}
.stat-pill{background:#fff;border-radius:50px;padding:7px 16px;font-size:.82rem;font-weight:700;box-shadow:0 2px 8px rgba(0,0,0,.07);display:flex;align-items:center;gap:6px}
.stat-pill.sp-total{color:var(--blue)}
.stat-pill.sp-visible{color:var(--green)}
.stat-pill i{font-size:.9rem}

/* ── SEARCH BAR ── */
.search-wrap{background:#fff;border-radius:50px;box-shadow:0 4px 16px rgba(0,0,0,.1);display:flex;align-items:center;padding:5px 5px 5px 18px;gap:8px;max-width:500px}
.search-wrap input{border:none;outline:none;flex:1;font-size:.9rem;background:transparent}
.search-wrap .btn-go{background:linear-gradient(135deg,var(--green),#004d35);color:#fff;border:none;border-radius:50px;padding:7px 18px;font-weight:700;font-size:.85rem}

/* ── ADMIT CARD ── */
.admit-card{background:#fff;border-radius:14px;box-shadow:0 4px 18px rgba(0,0,0,.09);margin-bottom:24px;overflow:hidden;border:1px solid #e8e8e8}
.admit-card-header{background:linear-gradient(135deg,var(--navy),#16213e);padding:12px 18px;display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:12px}
.admit-card-header .hdr-logo{display:flex;align-items:center;justify-content:flex-start;flex-shrink:0}
.admit-card-header .hdr-logo img{max-height:60px;width:auto;object-fit:contain}
.admit-card-header .hdr-logo .logo-placeholder{width:52px;height:52px;background:rgba(255,255,255,.15);border-radius:50%;display:flex;align-items:center;justify-content:center;color:rgba(255,255,255,.5);font-size:1.4rem}
.admit-card-header .hdr-center{text-align:center}
.admit-card-header .hdr-center h2{color:#fff;font-size:1.1rem;font-weight:800;margin:0;line-height:1.3}
.admit-card-header .hdr-center p{color:rgba(255,255,255,.8);font-size:.76rem;margin:3px 0 0}
.admit-card-header .hdr-center .exam-title{background:linear-gradient(135deg,var(--gold),#e6b800);color:var(--navy);border-radius:20px;padding:3px 14px;font-size:.8rem;font-weight:800;display:inline-block;margin-top:7px}
.admit-card-header .hdr-right{display:flex;align-items:center;justify-content:flex-end;flex-shrink:0}
.admit-card-body{padding:16px}

.student-info-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;background:linear-gradient(135deg,#f8f9ff,#f0f4ff);border-radius:10px;padding:14px;margin-bottom:14px}
.info-item{display:flex;flex-direction:row;align-items:baseline;gap:6px;flex-wrap:wrap}
.info-item{display:flex;flex-direction:row;align-items:baseline;gap:6px;flex-wrap:wrap}
.info-item .lbl{font-size:.76rem;font-weight:700;color:#777;white-space:nowrap;min-width:110px;flex-shrink:0}
.info-item .lbl::after{content:':'}
.info-item .val{font-size:.88rem;font-weight:700;color:var(--navy)}
.photo-box{width:64px;height:80px;border-radius:8px;border:2px solid #e0e0e0;overflow:hidden;display:flex;align-items:center;justify-content:center;background:#f5f5f5;flex-shrink:0}
.photo-box img{width:100%;height:100%;object-fit:cover}
.photo-box i{font-size:1.8rem;color:#bbb}

/* roll/group badges */
.roll-badge{background:linear-gradient(135deg,var(--blue),var(--purple));color:#fff;border-radius:8px;padding:3px 10px;font-size:.8rem;font-weight:800;display:inline-block}
.group-badge{background:linear-gradient(135deg,var(--orange),#c96a00);color:#fff;border-radius:8px;padding:3px 10px;font-size:.78rem;font-weight:700;display:inline-block}

/* exam table */
.exam-table{width:100%;border-collapse:collapse;font-size:.82rem;margin-bottom:12px}
.exam-table thead tr{background:linear-gradient(135deg,var(--navy),#16213e)}
.exam-table thead th{color:#fff;padding:8px 10px;text-align:center;font-weight:700;font-size:.78rem;border:none}
.exam-table tbody tr{border-bottom:1px solid #f0f0f0;transition:background .15s}
.exam-table tbody tr:hover{background:#f8f9ff}
.exam-table tbody td{padding:7px 10px;text-align:center;vertical-align:middle}
.exam-table tbody td.subj-name{text-align:left;font-weight:600}

/* instructions */
.instructions-box{background:linear-gradient(135deg,#e8f5e9,#f1f8e9);border-left:4px solid var(--green);border-radius:0 8px 8px 0;padding:7px 14px;font-size:.78rem;margin-bottom:12px;display:flex;flex-wrap:wrap;align-items:center;gap:4px 8px}
.instructions-box .instr-title{color:var(--green);font-weight:800;font-size:.8rem;white-space:nowrap;margin-right:4px}
.instructions-box .instr-item{color:#2d6a4f;font-size:.76rem}
.instructions-box .instr-item i{color:var(--green);font-size:.6rem;vertical-align:middle}
.instructions-box .instr-sep{color:var(--green);font-weight:700;opacity:.5}

/* signature */
.sig-row{display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-top:12px;font-size:.78rem}
.sig-item{text-align:center}
.sig-line{border-top:1px solid #999;margin:24px auto 4px;width:80%}

/* empty state */
.empty-state{text-align:center;padding:60px 20px;color:#aaa}
.empty-state i{font-size:4rem;margin-bottom:16px;display:block}

/* ── PRINT ── */
@media print{
  .no-print{display:none!important}
  body{background:#fff;font-size:10px;margin:0;padding:0;-webkit-print-color-adjust:exact;color-adjust:exact}
  .admit-card{box-shadow:none;border:1px solid #000;margin:0 0 8px;padding:0;border-radius:0;page-break-after:always;break-after:page;-webkit-print-color-adjust:exact;color-adjust:exact}
  .admit-card:last-child{page-break-after:avoid}
  .admit-card-header{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:10px;-webkit-print-color-adjust:exact;color-adjust:exact}
  .admit-card-header .hdr-center h2{font-size:1rem!important}
  .admit-card-header .hdr-center p{font-size:.72rem!important}
  .photo-box{width:56px;height:72px}
  .student-info-grid{-webkit-print-color-adjust:exact;color-adjust:exact}
  .exam-table thead tr{-webkit-print-color-adjust:exact;color-adjust:exact}
  .instructions-box{-webkit-print-color-adjust:exact;color-adjust:exact}
  .roll-badge,.group-badge{-webkit-print-color-adjust:exact;color-adjust:exact}
  .temp-hidden-for-print{display:none!important}
  .admit-card,.admit-card-body,.admit-card-header,.student-info-grid,.exam-table thead tr,.roll-badge,.group-badge,.exam-title{background:var(--print-bg,#fff)!important}
  .admit-card-header .hdr-center h2,.exam-title,.info-item .val,.exam-table thead th,.exam-table tbody td,.roll-badge,.group-badge{color:var(--print-text,#000)!important}
  .admit-card-header .hdr-center p,.info-item .lbl,.sig-item p{color:var(--print-text-muted,#666)!important}
}
</style>
<style id="customPrintStyle"></style>
</head>
<body>

<!-- ── TOP BAR ── -->
<div class="top-bar no-print">
  <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
  <div class="nav-links">
    <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
    <a href="routine.php"><i class="fas fa-calendar"></i> রুটিন</a>
    <a href="admit_card.php"><i class="fas fa-id-card"></i> এডমিট কার্ড</a>
    <a href="seat_card.php"><i class="fas fa-chair"></i> সীট কার্ড</a>
    <a href="attendance.php"><i class="fas fa-clipboard-check"></i> হাজিরা</a>
  </div>
</div>

<div class="container-fluid py-4 px-4">

<!-- ── FILTER CARD ── -->
<div class="filter-card no-print">
  <div class="filter-card-header">
    <i class="fas fa-id-card-alt fa-lg"></i>
    <h5>বাল্ক এডমিট কার্ড প্রিন্ট</h5>
  </div>
  <div class="filter-card-body">
    <form method="GET" id="filterForm">

      <!-- Row 1: Exam / Class / Session -->
      <div class="row g-3 align-items-end">
        <div class="col-md-4">
          <label class="form-label"><i class="fas fa-clipboard-list me-1 text-purple" style="color:var(--purple)"></i>পরীক্ষা নির্বাচন</label>
          <select class="form-select" id="exam_id" name="exam_id">
            <option value="">— পরীক্ষা নির্বাচন করুন —</option>
            <?php foreach ($all_exams as $ex): ?>
              <option value="<?php echo $ex['id']; ?>" <?php echo ($exam_id == $ex['id']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($ex['name']); ?> —
                <?php echo htmlspecialchars($ex['class_name'].' '.$ex['section']); ?>
                <?php if ($ex['group_name']): ?>(<?php echo htmlspecialchars($ex['group_name']); ?>)<?php endif; ?>
                [<?php echo htmlspecialchars($ex['session']); ?>]
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label"><i class="fas fa-chalkboard me-1" style="color:var(--blue)"></i>ক্লাস</label>
          <select class="form-select" id="class_id" name="class_id">
            <option value="">— ক্লাস —</option>
            <?php foreach ($classes as $cls): ?>
              <option value="<?php echo $cls['id']; ?>" <?php echo ($class_id == $cls['id']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($cls['name'].' '.$cls['section']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label"><i class="fas fa-calendar-alt me-1" style="color:var(--teal)"></i>সেশন</label>
          <select class="form-select" id="session" name="session">
            <option value="">— সেশন —</option>
            <?php foreach ($sessions as $sess): ?>
              <option value="<?php echo $sess['session_name']; ?>" <?php echo ($session == $sess['session_name']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($sess['session_name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label"><i class="fas fa-users me-1" style="color:var(--orange)"></i>গ্রুপ</label>
          <select class="form-select" id="group_name" name="group_name">
            <option value="">— সব গ্রুপ —</option>
            <option value="" <?php echo ($group_name === '') ? 'selected' : ''; ?>>সাধারণ</option>
            <?php foreach ($groups as $grp): ?>
              <option value="<?php echo $grp['group_name']; ?>" <?php echo ($group_name == $grp['group_name']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($grp['group_name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2 d-flex gap-2">
          <button type="submit" class="btn-search flex-fill"><i class="fas fa-search me-1"></i>দেখুন</button>
          <a href="bulk_admit_card.php" class="btn-reset"><i class="fas fa-redo"></i></a>
        </div>
      </div>

      <!-- Row 2: Roll Range + Group Filter (compact) -->
      <div class="filter-divider"><i class="fas fa-filter"></i> অতিরিক্ত ফিল্টার</div>
      <div class="row g-3 align-items-end">
        <div class="col-md-2">
          <label class="form-label"><i class="fas fa-sort-numeric-up me-1" style="color:var(--blue)"></i>রোল থেকে</label>
          <input type="number" class="form-control" name="roll_from" id="roll_from"
                 placeholder="যেমন: ১" min="1"
                 value="<?php echo $roll_from !== null ? $roll_from : ''; ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label"><i class="fas fa-sort-numeric-down me-1" style="color:var(--pink)"></i>রোল পর্যন্ত</label>
          <input type="number" class="form-control" name="roll_to" id="roll_to"
                 placeholder="যেমন: ৫০" min="1"
                 value="<?php echo $roll_to !== null ? $roll_to : ''; ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label"><i class="fas fa-layer-group me-1" style="color:var(--orange)"></i>গ্রুপ ফিল্টার (পরীক্ষার উপরে)</label>
          <select class="form-select" name="filter_group" id="filter_group">
            <option value="">— সব গ্রুপ —</option>
            <?php foreach ($groups as $grp): ?>
              <option value="<?php echo $grp['group_name']; ?>" <?php echo ($filter_group == $grp['group_name']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($grp['group_name'].' ('.$grp['group_code'].')'); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-5">
          <label class="form-label" style="color:transparent">.</label>
          <div class="d-flex align-items-center gap-2 flex-wrap">
            <?php if ($roll_from !== null || $roll_to !== null || $filter_group !== ''): ?>
              <span class="badge" style="background:var(--purple);padding:6px 12px;border-radius:20px;font-size:.78rem">
                <?php if ($roll_from !== null || $roll_to !== null): ?>
                  <i class="fas fa-hashtag me-1"></i>রোল: <?php echo $roll_from ?? '১'; ?> – <?php echo $roll_to ?? '∞'; ?>
                <?php endif; ?>
                <?php if ($filter_group !== ''): ?>
                  &nbsp;<i class="fas fa-users me-1"></i><?php echo htmlspecialchars($filter_group); ?>
                <?php endif; ?>
              </span>
            <?php endif; ?>
            <small class="text-muted" style="font-size:.78rem"><i class="fas fa-info-circle me-1"></i>রোল রেঞ্জ ও গ্রুপ ফিল্টার একসাথে ব্যবহার করা যাবে</small>
          </div>
        </div>
      </div>

      <div class="filter-divider"><i class="fas fa-palette"></i> প্রিন্ট কাস্টমাইজেশন</div>
      <div class="row g-2 align-items-end">
        <div class="col-md-3">
          <label class="form-label"><i class="fas fa-fill me-1" style="color:var(--purple)"></i>কার্ড ব্যাকগ্রাউন্ড কালার</label>
          <div class="d-flex gap-2">
            <input type="color" class="form-control form-control-color" id="printBgColor" value="#ffffff" style="width:50px;height:36px;padding:2px;cursor:pointer">
            <input type="text" class="form-control" id="printBgColorHex" value="#ffffff" style="max-width:110px;font-size:.82rem" placeholder="#ffffff">
          </div>
        </div>
        <div class="col-md-3 d-flex gap-1 align-items-end pb-1">
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#f5f5f5,#e0e0e0);border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setBgColor('#ffffff')">সাদা</button>
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#fffde7,#fff9c4);border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setBgColor('#fffde7')">হলুদ</button>
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#e8f5e9,#c8e6c9);border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setBgColor('#e8f5e9')">সবুজ</button>
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#e3f2fd,#bbdefb);border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setBgColor('#e3f2fd')">নীল</button>
        </div>
        <div class="col-md-3">
          <label class="form-label"><i class="fas fa-heading me-1" style="color:var(--navy)"></i>হেডিং ব্যাকগ্রাউন্ড কালার</label>
          <div class="d-flex gap-2">
            <input type="color" class="form-control form-control-color" id="printHdrColor" value="#1a1a2e" style="width:50px;height:36px;padding:2px;cursor:pointer">
            <input type="text" class="form-control" id="printHdrColorHex" value="#1a1a2e" style="max-width:110px;font-size:.82rem" placeholder="#1a1a2e">
          </div>
        </div>
        <div class="col-md-3 d-flex gap-1 align-items-end pb-1">
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#1a1a2e,#16213e);color:#fff;border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setHdrColor('#1a1a2e')">নেভি</button>
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#7209b7,#4361ee);color:#fff;border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setHdrColor('#7209b7')">বেগুনি</button>
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#006747,#004d35);color:#fff;border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setHdrColor('#006747')">সবুজ</button>
          <button type="button" class="btn btn-sm" style="background:linear-gradient(135deg,#c0392b,#922b21);color:#fff;border:none;border-radius:8px;padding:6px 12px;font-weight:600;font-size:.78rem" onclick="setHdrColor('#c0392b')">লাল</button>
        </div>
      </div>
      <div class="row g-2 align-items-end mt-2">
        <div class="col-md-3">
          <label class="form-label"><i class="fas fa-arrows-alt-v me-1" style="color:var(--teal)"></i>প্যাডিং কমান/বাড়ান</label>
          <div class="d-flex align-items-center gap-2">
            <input type="range" class="form-range" id="paddingSlider" min="-10" max="30" step="1" value="14">
            <span class="badge" style="background:var(--purple);min-width:40px;font-size:.75rem" id="paddingValue">14px</span>
          </div>
        </div>
        <div class="col-md-3 d-flex gap-1 align-items-end pb-1">
          <label class="form-label" style="color:transparent">.</label>
          <div class="d-flex gap-1">
            <button class="btn btn-sm" style="background:linear-gradient(135deg,#e0e0e0,#ccc);border:none;border-radius:8px;padding:6px 14px;font-weight:600;font-size:.78rem" onclick="setPadding(-10)">শূন্য</button>
            <button class="btn btn-sm" style="background:linear-gradient(135deg,#e0e0e0,#ccc);border:none;border-radius:8px;padding:6px 14px;font-weight:600;font-size:.78rem" onclick="setPadding(6)">সর্বনিম্ন</button>
            <button class="btn btn-sm" style="background:linear-gradient(135deg,#e0e0e0,#ccc);border:none;border-radius:8px;padding:6px 14px;font-weight:600;font-size:.78rem" onclick="setPadding(14)">মাঝারি</button>
            <button class="btn btn-sm" style="background:linear-gradient(135deg,#e0e0e0,#ccc);border:none;border-radius:8px;padding:6px 14px;font-weight:600;font-size:.78rem" onclick="setPadding(24)">সর্বোচ্চ</button>
          </div>
        </div>
        <div class="col-md-6">
          <label class="form-label" style="color:transparent">.</label>
          <div class="form-text mt-0"><i class="fas fa-info-circle me-1"></i>প্যাডিং পরিবর্তন করলে প্রিন্ট ও প্রিভিউ উভয় ক্ষেত্রেই কার্ডের ভেতরের ফাকা জায়গা কমবে/বাড়বে।</div>
        </div>
      </div>

    </form>
  </div>
</div>

<?php if ($has_results && !empty($students)): ?>

<!-- ── STATS + SEARCH BAR ── -->
<div class="no-print d-flex align-items-center justify-content-between flex-wrap gap-3 mb-3">
  <div class="stats-bar">
    <div class="stat-pill sp-total"><i class="fas fa-users"></i> মোট: <strong><?php echo count($students); ?></strong> জন</div>
    <?php if ($roll_from !== null || $roll_to !== null): ?>
      <div class="stat-pill" style="color:var(--purple)"><i class="fas fa-hashtag"></i> রোল: <?php echo $roll_from ?? '১'; ?>–<?php echo $roll_to ?? '∞'; ?></div>
    <?php endif; ?>
    <?php if ($filter_group !== ''): ?>
      <div class="stat-pill" style="color:var(--orange)"><i class="fas fa-users"></i> গ্রুপ: <?php echo htmlspecialchars($filter_group); ?></div>
    <?php endif; ?>
    <div class="stat-pill sp-visible" id="visibleCount"><i class="fas fa-eye"></i> দেখাচ্ছে: <strong id="visibleNum"><?php echo count($students); ?></strong> জন</div>
  </div>
  <div class="d-flex gap-2 align-items-center flex-wrap">
    <div class="search-wrap">
      <i class="fas fa-search" style="color:#aaa"></i>
      <input type="text" id="studentSearch" placeholder="নাম, রোল, আইডি বা কমা দিয়ে একাধিক...">
      <button class="btn-go" onclick="clearSearch()"><i class="fas fa-times"></i></button>
    </div>
    <button class="btn-print-filtered" id="printFilteredBtn" onclick="printFilteredAdmitCards()">
      <i class="fas fa-print me-1"></i>ফিল্টার প্রিন্ট
    </button>
    <button class="btn-print-all" onclick="printAdmitCards()">
      <i class="fas fa-print me-1"></i>সব প্রিন্ট
    </button>
  </div>
</div>

<!-- ── ADMIT CARDS ── -->
<?php foreach ($students as $idx => $student):
  $photo_ok = false; $photo_src = '';
  if (!empty($student['photo'])) {
    foreach (['../'.$student['photo'], $student['photo'], '../uploads/students/'.basename($student['photo'])] as $p) {
      if (file_exists($p)) { $photo_ok = true; $photo_src = $p; break; }
    }
  }
  // student subjects
  $stu_subjects = $exam_id ? getStudentSubjects($pdo, $exam_id, $student['id']) : $exam_subjects;
  // group by date
  $by_date = [];
  foreach ($stu_subjects as $r) {
    $d = date('Y-m-d', strtotime($r['exam_date']));
    $by_date[$d][] = $r;
  }
  $days_bn = ['Sunday'=>'রবিবার','Monday'=>'সোমবার','Tuesday'=>'মঙ্গলবার','Wednesday'=>'বুধবার','Thursday'=>'বৃহস্পতিবার','Friday'=>'শুক্রবার','Saturday'=>'শনিবার'];
?>
<div class="admit-card"
     data-name="<?php echo strtolower(htmlspecialchars($student['first_name'].' '.$student['last_name'])); ?>"
     data-roll="<?php echo strtolower(htmlspecialchars($student['roll_number'])); ?>"
     data-id="<?php echo strtolower(htmlspecialchars($student['student_id'])); ?>">

  <!-- Card Header -->
  <div class="admit-card-header">
    <!-- লোগো বামে -->
    <div class="hdr-logo">
      <?php if ($logo_image): ?>
        <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height:<?php echo $logo_size; ?>px">
      <?php else: ?>
        <div class="logo-placeholder"><i class="fas fa-graduation-cap"></i></div>
      <?php endif; ?>
    </div>
    <!-- প্রতিষ্ঠানের নাম ও ঠিকানা মাঝে -->
    <div class="hdr-center">
      <h2><?php echo htmlspecialchars($site_name); ?></h2>
      <p><?php echo htmlspecialchars($site_address); ?></p>
      <div class="exam-title"><i class="fas fa-id-card me-1"></i>এডমিট কার্ড — <?php echo htmlspecialchars($exam_details ? $exam_details['name'] : 'পরীক্ষা'); ?><?php if ($exam_details && !empty($exam_details['session'])): ?> (<?php echo htmlspecialchars($exam_details['session']); ?>)<?php endif; ?></div>
    </div>
    <!-- ডানে শিক্ষার্থীর ছবি -->
    <div class="hdr-right">
      <div class="photo-box" style="border-color:rgba(255,255,255,.3)">
        <?php if ($photo_ok): ?>
          <img src="<?php echo htmlspecialchars($photo_src); ?>" alt="ছবি">
        <?php else: ?>
          <i class="fas fa-user"></i>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Card Body -->
  <div class="admit-card-body">

    <!-- Student Info -->
    <div class="student-info-grid">
      <div>
        <div class="info-item mb-2">
          <span class="lbl">ছাত্র/ছাত্রীর নাম</span>
          <span class="val"><?php echo htmlspecialchars($student['first_name'].' '.$student['last_name']); ?></span>
        </div>
        <div class="info-item mb-2">
          <span class="lbl">শ্রেণি</span>
          <span class="val"><?php echo htmlspecialchars($student['class_name'].' '.$student['section']); ?></span>
        </div>
        <div class="info-item">
          <span class="lbl">গ্রুপ</span>
          <span class="val">
            <?php if (!empty($student['group_name'])): ?>
              <span class="group-badge"><?php echo htmlspecialchars($student['group_name']); ?></span>
            <?php else: ?>সাধারণ<?php endif; ?>
          </span>
        </div>
      </div>
      <div>
        <div class="info-item mb-2">
          <span class="lbl">রোল নম্বর</span>
          <span class="val"><span class="roll-badge"><?php echo htmlspecialchars($student['roll_number']); ?></span></span>
        </div>
        <div class="info-item mb-2">
          <span class="lbl">আইডি নম্বর</span>
          <span class="val"><?php echo htmlspecialchars($student['student_id']); ?></span>
        </div>
        <div class="info-item">
          <span class="lbl">অভিভাবকের নাম</span>
          <span class="val"><?php echo htmlspecialchars($student['guardian_name'] ?? '—'); ?></span>
        </div>
      </div>
    </div>

    <!-- Exam Table -->
    <table class="exam-table">
      <thead>
        <tr>
          <th style="width:13%">তারিখ</th>
          <th style="width:12%">দিন</th>
          <th style="width:35%">বিষয়</th>
          <th style="width:22%">সময়</th>
          <th style="width:10%">মার্কস</th>
          <?php if ($exam_id && isset($seat_arrangements[$student['id']])): ?>
            <th style="width:8%">রুম/সিট</th>
          <?php endif; ?>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($by_date as $dk => $rows):
          $subj_parts = $time_parts = $marks_parts = [];
          foreach ($rows as $r) {
            $subj_parts[] = $r['subject_name'].($r['subject_code'] ? ' ('.$r['subject_code'].')' : '');
            $time_parts[] = date('h:i A', strtotime($r['start_time'])).' - '.date('h:i A', strtotime($r['end_time']));
            $marks_parts[] = $r['marks'] ?? '-';
          }
          $time_parts  = array_unique($time_parts);
          $marks_parts = array_unique($marks_parts);
        ?>
        <tr>
          <td><?php echo date('d/m/Y', strtotime($dk)); ?></td>
          <td><?php echo $days_bn[date('l', strtotime($dk))]; ?></td>
          <td class="subj-name"><?php echo implode(' / ', $subj_parts); ?></td>
          <td><?php echo implode(' / ', $time_parts) ?: '—'; ?></td>
          <td><?php echo implode(' / ', $marks_parts) ?: '—'; ?></td>
          <?php if ($exam_id && isset($seat_arrangements[$student['id']])): ?>
            <td><?php $s=$seat_arrangements[$student['id']]; echo htmlspecialchars(($s['room_number']??'').'/'.($s['seat_number']??'')); ?></td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($by_date)): ?>
          <tr><td colspan="6" style="text-align:center;color:#aaa;font-style:italic">কোনো বিষয় পাওয়া যায়নি</td></tr>
        <?php endif; ?>
      </tbody>
    </table>

    <!-- Instructions -->
    <div class="instructions-box">
      <span class="instr-title"><i class="fas fa-info-circle me-1"></i>নির্দেশাবলী:</span>
      <span class="instr-item"><i class="fas fa-circle-dot me-1"></i>পরীক্ষার্থীকে অবশ্যই এই এডমিট কার্ড সাথে আনতে হবে</span>
      <span class="instr-sep">|</span>
      <span class="instr-item"><i class="fas fa-circle-dot me-1"></i>পরীক্ষাগারে ঢোকার সময় অবশ্যই এই এডমিট কার্ড দেখাতে হবে</span>
      <span class="instr-sep">|</span>
      <span class="instr-item"><i class="fas fa-circle-dot me-1"></i>পরীক্ষার সময় সঠিক সময় মেনে চলতে হবে</span>
    </div>

    <!-- Signature -->
    <div class="sig-row">
      <div class="sig-item"><div class="sig-line"></div><p>পরীক্ষার্থীর স্বাক্ষর</p></div>
      <div class="sig-item"><div class="sig-line"></div><p>পরীক্ষা নিরীক্ষকের স্বাক্ষর</p></div>
      <div class="sig-item"><div class="sig-line"></div><p>প্রধান শিক্ষক / পরীক্ষা নিরীক্ষক</p></div>
    </div>

  </div><!-- /admit-card-body -->
</div><!-- /admit-card -->
<?php endforeach; ?>

<?php elseif ($has_results && empty($students)): ?>
<div class="empty-state no-print">
  <i class="fas fa-user-slash"></i>
  <p class="fw-bold fs-5">কোনো ছাত্র/ছাত্রী পাওয়া যায়নি</p>
  <small>নির্বাচিত মানদণ্ড পরিবর্তন করে আবার চেষ্টা করুন</small>
</div>
<?php elseif (!$has_results): ?>
<div class="empty-state no-print">
  <i class="fas fa-id-card" style="color:var(--purple);opacity:.3"></i>
  <p class="fw-bold fs-5">পরীক্ষা বা ক্লাস/সেশন নির্বাচন করুন</p>
  <small>উপরের ফিল্টার ব্যবহার করে এডমিট কার্ড দেখুন</small>
</div>
<?php endif; ?>

</div><!-- /container-fluid -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ── exam_id change: keep other fields enabled ──
const $exam = document.getElementById('exam_id');
if ($exam) $exam.addEventListener('change', function() {
    ['class_id','session','group_name'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.disabled = false;
    });
});

// ── search ──
function clearSearch() {
    var inp = document.getElementById('studentSearch');
    if (inp) { inp.value = ''; inp.dispatchEvent(new Event('keyup')); }
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput   = document.getElementById('studentSearch');
    const printFiltered = document.getElementById('printFilteredBtn');
    const visibleNum    = document.getElementById('visibleNum');

    if (searchInput) {
        searchInput.addEventListener('keyup', function() {
            const raw   = this.value.trim().toLowerCase();
            const terms = raw.split(',').map(t => t.trim()).filter(t => t.length > 0);
            const cards = document.querySelectorAll('.admit-card');
            let visible = 0;

            cards.forEach(card => {
                if (terms.length === 0) {
                    card.style.display = 'block'; visible++; return;
                }
                const name = card.dataset.name || '';
                const roll = card.dataset.roll || '';
                const sid  = card.dataset.id   || '';
                const found = terms.some(t => name.includes(t) || roll.includes(t) || sid.includes(t));
                card.style.display = found ? 'block' : 'none';
                if (found) visible++;
            });

            if (visibleNum) visibleNum.textContent = visible;
            if (printFiltered) printFiltered.style.display = terms.length > 0 ? 'inline-block' : 'none';
        });
    }
});

function printAdmitCards() {
    setTimeout(() => window.print(), 100);
}

function printFilteredAdmitCards() {
    document.querySelectorAll('.admit-card').forEach(c => {
        if (c.style.display === 'none') c.classList.add('temp-hidden-for-print');
    });
    setTimeout(() => {
        window.print();
        setTimeout(() => {
            document.querySelectorAll('.temp-hidden-for-print').forEach(c => {
                c.classList.remove('temp-hidden-for-print');
                c.style.display = 'block';
            });
        }, 200);
    }, 100);
}

// ----- Print BG Color Customization -----
function setBgColor(color) {
    const bg = document.getElementById('printBgColor'), hex = document.getElementById('printBgColorHex');
    if (bg) bg.value = color;
    if (hex) hex.value = color;
    saveBgColor(color);
    applyBgColor(color);
}
const $bg = document.getElementById('printBgColor'), $hex = document.getElementById('printBgColorHex');
if ($bg) $bg.addEventListener('input', function() {
    if ($hex) $hex.value = this.value;
    saveBgColor(this.value);
    applyBgColor(this.value);
});
if ($hex) $hex.addEventListener('input', function() {
    if (/^#[0-9a-f]{6}$/i.test(this.value)) {
        if ($bg) $bg.value = this.value;
        saveBgColor(this.value);
        applyBgColor(this.value);
    }
});
function getTextColor(hex, muted) {
    hex = hex.replace('#','');
    const r = parseInt(hex.substr(0,2),16), g = parseInt(hex.substr(2,2),16), b = parseInt(hex.substr(4,2),16);
    const lum = (r*299 + g*587 + b*114) / 1000;
    if (muted) return lum > 160 ? '#666' : '#bbb';
    return lum > 160 ? '#000' : '#fff';
}
function saveBgColor(color) {
    try { localStorage.setItem('admit_print_bg', color); } catch(e) {}
}
function loadBgColor() {
    try { return localStorage.getItem('admit_print_bg') || '#ffffff'; } catch(e) { return '#ffffff'; }
}
function applyBgColor(color) {
    document.documentElement.style.setProperty('--print-bg', color);
    const tc = getTextColor(color), tcm = getTextColor(color,true);
    document.documentElement.style.setProperty('--print-text', tc);
    document.documentElement.style.setProperty('--print-text-muted', tcm);
    _rebuildCustomStyle();
}
// ----- Header BG Color Customization -----
function setHdrColor(color) {
    const hdr = document.getElementById('printHdrColor'), hhex = document.getElementById('printHdrColorHex');
    if (hdr) hdr.value = color;
    if (hhex) hhex.value = color;
    saveHdrColor(color);
    applyHdrColor(color);
}
const $hdr = document.getElementById('printHdrColor'), $hhex = document.getElementById('printHdrColorHex');
if ($hdr) $hdr.addEventListener('input', function() {
    if ($hhex) $hhex.value = this.value;
    saveHdrColor(this.value);
    applyHdrColor(this.value);
});
if ($hhex) $hhex.addEventListener('input', function() {
    if (/^#[0-9a-f]{6}$/i.test(this.value)) {
        if ($hdr) $hdr.value = this.value;
        saveHdrColor(this.value);
        applyHdrColor(this.value);
    }
});
function saveHdrColor(color) {
    try { localStorage.setItem('admit_print_hdr', color); } catch(e) {}
}
function loadHdrColor() {
    try { return localStorage.getItem('admit_print_hdr') || '#1a1a2e'; } catch(e) { return '#1a1a2e'; }
}
function applyHdrColor(color) {
    document.documentElement.style.setProperty('--print-hdr', color);
    const tc = getTextColor(color), tcm = getTextColor(color, true);
    document.documentElement.style.setProperty('--print-hdr-text', tc);
    document.documentElement.style.setProperty('--print-hdr-muted', tcm);
    _rebuildCustomStyle();
}
function _rebuildCustomStyle() {
    const bg  = (document.getElementById('printBgColor')  || {value:'#ffffff'}).value;
    const hdr = (document.getElementById('printHdrColor') || {value:'#1a1a2e'}).value;
    const tc    = getTextColor(bg),        tcm    = getTextColor(bg, true);
    const htc   = getTextColor(hdr),       htcm   = getTextColor(hdr, true);
    const style = document.getElementById('customPrintStyle');
    if (!style) return;
    style.textContent =
        /* ── screen preview ── */
        '.admit-card,.admit-card-body,.student-info-grid{background:'+bg+'}'
        +'.admit-card-header,.exam-table thead tr{background:'+hdr+'}'
        +'.roll-badge,.group-badge,.exam-title{background:'+hdr+'}'
        +'.admit-card-header .hdr-center h2,.exam-title,.exam-table thead th,.roll-badge,.group-badge{color:'+htc+'}'
        +'.admit-card-header .hdr-center p{color:'+htcm+'}'
        +'.info-item .val,.exam-table tbody td{color:'+tc+'}'
        +'.info-item .lbl,.sig-item p{color:'+tcm+'}'
        +'.exam-table tbody td{border-color:'+tcm+'}'
        +'.exam-table thead th{border-bottom:2px solid '+htc+'}'
        +'.roll-badge,.group-badge,.exam-title{border:1px solid '+htc+'}'
        +'.sig-line{border-top-color:'+tcm+'}'
        /* ── print ── */
        +'@media print{'
        +'.admit-card,.admit-card-body,.student-info-grid{background:'+bg+'!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}'
        +'.admit-card-header,.exam-table thead tr,.roll-badge,.group-badge,.exam-title{background:'+hdr+'!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}'
        +'.admit-card-header .hdr-center h2,.exam-title,.exam-table thead th,.roll-badge,.group-badge{color:'+htc+'!important}'
        +'.admit-card-header .hdr-center p{color:'+htcm+'!important}'
        +'.info-item .val,.exam-table tbody td{color:'+tc+'!important}'
        +'.info-item .lbl,.sig-item p{color:'+tcm+'!important}'
        +'.exam-table tbody td{border-color:'+tcm+'!important}'
        +'.exam-table thead th{border-bottom:2px solid '+htc+'!important}'
        +'.roll-badge,.group-badge,.exam-title{border:1px solid '+htc+'!important}'
        +'.sig-line{border-top-color:'+tcm+'!important}'
        +'}'
}
// ----- Padding Customization -----
function setPadding(val) {
    val = parseInt(val);
    if (isNaN(val)) val = 14;
    var sl = document.getElementById('paddingSlider');
    if (sl) sl.value = val;
    var pv = document.getElementById('paddingValue');
    if (pv) pv.textContent = val + 'px';
    document.documentElement.style.setProperty('--card-padding', val + 'px');
    try { localStorage.setItem('admit_card_padding', val); } catch(e) {}
    applyPadding(val);
}
function applyPadding(val) {
    val = parseInt(val);
    if (isNaN(val)) val = 14;
    // body padding: 0 minimum, header uses ratio
    const bodyP  = Math.max(0, val) + 'px';
    const hdrPV  = Math.max(0, Math.round(val * 0.7)) + 'px';
    const hdrPH  = Math.max(0, Math.round(val * 1.1)) + 'px';
    // when val < 0 apply negative margin to squeeze rows
    const rowMg  = val < 0 ? Math.max(-8, val) + 'px' : '0px';
    document.querySelectorAll('.admit-card-body').forEach(el => {
        el.style.setProperty('padding', bodyP, 'important');
    });
    document.querySelectorAll('.admit-card-header').forEach(el => {
        el.style.setProperty('padding', hdrPV+' '+hdrPH, 'important');
    });
    document.querySelectorAll('.student-info-grid').forEach(el => {
        el.style.setProperty('padding', Math.max(4, Math.round(val*0.8))+'px', 'important');
        el.style.setProperty('gap', Math.max(2, Math.round(val*0.6))+'px', 'important');
        el.style.setProperty('margin-bottom', rowMg === '0px' ? '10px' : rowMg, 'important');
    });
    document.querySelectorAll('.exam-table tbody td, .exam-table thead th').forEach(el => {
        el.style.setProperty('padding', Math.max(2, Math.round(val*0.5))+'px '+ Math.max(4, Math.round(val*0.7))+'px', 'important');
    });
    document.querySelectorAll('.instructions-box').forEach(el => {
        el.style.setProperty('padding', Math.max(3, Math.round(val*0.5))+'px '+ Math.max(6, val)+'px', 'important');
        el.style.setProperty('margin-bottom', Math.max(4, Math.round(val*0.6))+'px', 'important');
    });
    document.querySelectorAll('.sig-row').forEach(el => {
        el.style.setProperty('margin-top', Math.max(4, Math.round(val*0.7))+'px', 'important');
    });
    document.querySelectorAll('.sig-line').forEach(el => {
        el.style.setProperty('margin-top', Math.max(12, val+8)+'px', 'important');
    });
}
const $slider = document.getElementById('paddingSlider');
if ($slider) $slider.addEventListener('input', function() {
    setPadding(this.value);
});
// Apply saved color + padding on load
document.addEventListener('DOMContentLoaded', function() {
    const saved = loadBgColor();
    if (document.getElementById('printBgColor')) setBgColor(saved);
    const savedHdr = loadHdrColor();
    if (document.getElementById('printHdrColor')) setHdrColor(savedHdr);
    const savedPad = parseInt(localStorage.getItem('admit_card_padding')) || 14;
    if (document.getElementById('paddingSlider')) setPadding(savedPad);
    // ensure padding works for dynamically loaded cards too
    const observer = new MutationObserver(function() {
        try {
            var sl = document.getElementById('paddingSlider');
            var val = sl ? parseInt(sl.value) : 14;
            if (isNaN(val)) val = 14;
            applyPadding(val);
        } catch(e) {}
    });
    observer.observe(document.getElementById('visibleCount')?.closest('.container-fluid') || document.body, { childList: true, subtree: true });
});
</script>
</body>
</html>
