<?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']   ?? '';
$filter_group = $_GET['filter_group'] ?? '';
$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;

// 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;

// 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();
    }
}

// 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 DISTINCT session as session_name FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC")->fetchAll();
$groups    = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name")->fetchAll();

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();
}

// Build student query with roll range + group filter
$students = [];
if (($exam_id && $exam_details) || ($class_id && $session)) {
    $sql    = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.guardian_name, s.photo, s.group_name, 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'];
        if ($exam_details['group_name']) {
            $sql .= " AND (s.group_name = ? OR UPPER(s.group_name) = UPPER(?))";
            $params[] = $exam_details['group_name'];
            $params[] = $exam_details['group_name'];
        }
        if ($filter_group !== '') {
            $sql .= " AND (s.group_name = ? OR UPPER(s.group_name) = UPPER(?))";
            $params[] = $filter_group;
            $params[] = $filter_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;
        }
    }

    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();
}

$has_results = ((!$exam_id && $class_id && $session) || ($exam_id && $exam_details));
$days_bn = ['Sunday'=>'রবিবার','Monday'=>'সোমবার','Tuesday'=>'মঙ্গলবার','Wednesday'=>'বুধবার','Thursday'=>'বৃহস্পতিবার','Friday'=>'শুক্রবার','Saturday'=>'শনিবার'];
?>
<!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:11px 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.05rem;font-weight:700;text-decoration:none;display:flex;align-items:center;gap:9px}
.top-bar .brand i{color:var(--gold)}
.top-bar .nav-links{display:flex;gap:5px;flex-wrap:wrap}
.top-bar .nav-links a{color:rgba(255,255,255,.8);text-decoration:none;padding:5px 11px;border-radius:20px;font-size:.8rem;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,#06d6a0,#028a5b);padding:13px 20px;color:#fff;display:flex;align-items:center;gap:10px}
.filter-card-header h5{margin:0;font-size:.98rem;font-weight:700}
.filter-card-body{padding:18px 20px}
.form-label{font-size:.78rem;font-weight:700;color:#555;margin-bottom:3px}
.form-control,.form-select{border-radius:10px!important;border:1.5px solid #e0e0e0;font-size:.86rem;padding:7px 11px;transition:border-color .2s,box-shadow .2s}
.form-control:focus,.form-select:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(6,214,160,.15)}

/* divider */
.filter-divider{display:flex;align-items:center;gap:8px;margin:12px 0 8px;color:#999;font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px}
.filter-divider::before,.filter-divider::after{content:'';flex:1;height:1px;background:#ebebeb}

/* BUTTONS */
.btn-search{background:linear-gradient(135deg,var(--teal),#028a5b);color:#fff;border:none;border-radius:10px;padding:8px 22px;font-weight:700;font-size:.88rem;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:7px 18px;font-weight:700;font-size:.86rem;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:7px 18px;font-weight:700;font-size:.86rem;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:7px 14px;font-size:.86rem;transition:all .2s}
.btn-reset:hover{background:#e0e0e0}

/* STATS BAR */
.stats-bar{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px}
.stat-pill{background:#fff;border-radius:50px;padding:6px 14px;font-size:.8rem;font-weight:700;box-shadow:0 2px 8px rgba(0,0,0,.07);display:flex;align-items:center;gap:5px}

/* SEARCH */
.search-wrap{background:#fff;border-radius:50px;box-shadow:0 4px 16px rgba(0,0,0,.1);display:flex;align-items:center;padding:4px 4px 4px 16px;gap:7px;max-width:460px}
.search-wrap input{border:none;outline:none;flex:1;font-size:.88rem;background:transparent}
.search-wrap .btn-go{background:linear-gradient(135deg,var(--teal),#028a5b);color:#fff;border:none;border-radius:50px;padding:6px 16px;font-weight:700;font-size:.82rem}

/* CERTIFICATE CARD */
.cert-card{background:#fff;border-radius:14px;box-shadow:0 4px 18px rgba(0,0,0,.09);margin-bottom:22px;overflow:hidden;border:1px solid #e8e8e8}
.cert-header{background:linear-gradient(135deg,#006747,#004d35);padding:12px 18px;display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:12px}
.cert-header .hdr-logo{display:flex;align-items:center;justify-content:flex-start;flex-shrink:0}
.cert-header .hdr-logo img{max-height:60px;width:auto;object-fit:contain}
.cert-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}
.cert-header .hdr-center{text-align:center}
.cert-header .hdr-center h2{color:#fff;font-size:1.05rem;font-weight:800;margin:0;line-height:1.3}
.cert-header .hdr-center p{color:rgba(255,255,255,.8);font-size:.76rem;margin:2px 0 0}
.cert-header .hdr-center .cert-title{background:linear-gradient(135deg,var(--teal),#028a5b);color:#fff;border-radius:20px;padding:3px 14px;font-size:.8rem;font-weight:800;display:inline-block;margin-top:7px}
.cert-header .hdr-right{display:flex;align-items:center;justify-content:flex-end;flex-shrink:0}
.cert-body{padding:14px 16px}

/* student info grid */
.stu-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;background:linear-gradient(135deg,#f0faf5,#e8f5e9);border-radius:10px;padding:12px;margin-bottom:12px}
.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:.86rem;font-weight:700;color:var(--navy)}
.roll-badge{background:linear-gradient(135deg,var(--green),#004d35);color:#fff;border-radius:8px;padding:2px 10px;font-size:.78rem;font-weight:800;display:inline-block}
.group-badge{background:linear-gradient(135deg,var(--orange),#c96a00);color:#fff;border-radius:8px;padding:2px 9px;font-size:.76rem;font-weight:700;display:inline-block}
.photo-box{width:60px;height:76px;border-radius:8px;border:2px solid #c8e6c9;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.6rem;color:#bbb}

/* attendance table */
.att-table{width:100%;border-collapse:collapse;font-size:.8rem;margin-bottom:10px}
.att-table thead tr{background:linear-gradient(135deg,var(--green),#004d35)}
.att-table thead th{color:#fff;padding:7px 10px;text-align:center;font-weight:700;font-size:.76rem;border:none}
.att-table tbody tr{border-bottom:1px solid #f0f0f0}
.att-table tbody tr:nth-child(even){background:#f9fffe}
.att-table tbody td{padding:8px 10px;text-align:center;vertical-align:middle;border:1px solid #e8e8e8}
.att-table tbody td.subj-name{text-align:left;font-weight:600}
.att-table tbody td.sig-cell{min-width:90px;height:36px}

/* signature */
.sig-row{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-top:10px;font-size:.76rem}
.sig-item{text-align:center}
.sig-line{border-top:1px solid #999;margin:22px auto 3px;width:80%}

/* empty state */
.empty-state{text-align:center;padding:60px 20px;color:#aaa}
.empty-state i{font-size:3.5rem;margin-bottom:14px;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}
  .cert-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}
  .cert-card:last-child{page-break-after:avoid}
  .cert-header{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:10px;padding:10px 14px;-webkit-print-color-adjust:exact;color-adjust:exact}
  .cert-header .hdr-center h2{font-size:1rem!important}
  .cert-header .hdr-center p{font-size:.72rem!important}
  .photo-box{width:52px;height:68px}
  .stu-grid{-webkit-print-color-adjust:exact;color-adjust:exact}
  .att-table thead tr{-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}
  .cert-card{background:var(--print-bg,#fff)!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="bulk_admit_card.php"><i class="fas fa-id-card-alt"></i> বাল্ক এডমিট</a>
    <a href="seat_card.php"><i class="fas fa-chair"></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-clipboard-list fa-lg"></i>
    <h5>বাল্ক হাজিরা পত্র প্রিন্ট</h5>
  </div>
  <div class="filter-card-body">
    <form method="GET" id="filterForm">

      <!-- Row 1: Main filters -->
      <div class="row g-2 align-items-end">
        <div class="col-md-4">
          <label class="form-label"><i class="fas fa-clipboard-list me-1" style="color:var(--teal)"></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(--purple)"></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_attendance_certificate.php" class="btn-reset"><i class="fas fa-redo"></i></a>
        </div>
      </div>

      <!-- Row 2: Roll range + extra group filter -->
      <div class="filter-divider"><i class="fas fa-sliders-h"></i> অতিরিক্ত ফিল্টার</div>
      <div class="row g-2 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" 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" 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']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-5 d-flex align-items-center gap-2 flex-wrap" style="padding-top:20px">
          <?php if ($roll_from !== null || $roll_to !== null || $filter_group !== ''): ?>
            <span class="badge" style="background:var(--teal);color:#fff;padding:6px 12px;border-radius:20px;font-size:.76rem">
              <?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:.76rem"><i class="fas fa-info-circle me-1"></i>রোল রেঞ্জ ও গ্রুপ একসাথে ব্যবহার করা যাবে</small>
        </div>
        <div class="col-md-12 mt-2">
          <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-2 d-flex gap-1 align-items-end pb-1">
              <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 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 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 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>
        </div>
      </div>

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

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

<!-- STATS + SEARCH -->
<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" style="color:var(--green)"><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(--blue)"><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" style="color:var(--teal)" 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="printFiltered()">
      <i class="fas fa-print me-1"></i>ফিল্টার প্রিন্ট
    </button>
    <a href="bulk_admit_card.php?<?php echo http_build_query(array_filter(['exam_id'=>$exam_id,'class_id'=>$class_id,'session'=>$session,'group_name'=>$group_name])); ?>" class="btn-print-all" style="background:linear-gradient(135deg,var(--blue),var(--purple))">
      <i class="fas fa-id-card me-1"></i>এডমিট কার্ড
    </a>
    <button class="btn-print-all" onclick="window.print()">
      <i class="fas fa-print me-1"></i>সব প্রিন্ট
    </button>
  </div>
</div>

<!-- CERTIFICATES -->
<?php foreach ($students as $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; }
    }
  }
  $stu_subjects = $exam_id ? getStudentSubjects($pdo, $exam_id, $student['id']) : $exam_subjects;
  $by_date = [];
  foreach ($stu_subjects as $r) {
    $d = date('Y-m-d', strtotime($r['exam_date']));
    $by_date[$d][] = $r;
  }
?>
<div class="cert-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'])); ?>">

  <!-- Header -->
  <div class="cert-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="cert-title"><i class="fas fa-clipboard-check 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>

  <!-- Body -->
  <div class="cert-body">

    <!-- Student Info -->
    <div class="stu-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>

    <!-- Attendance Table -->
    <table class="att-table">
      <thead>
        <tr>
          <th style="width:12%">তারিখ</th>
          <th style="width:11%">দিন</th>
          <th style="width:35%">বিষয়</th>
          <th style="width:21%">ছাত্র/ছাত্রীর স্বাক্ষর</th>
          <th style="width:21%">কক্ষ পরিদর্শকের স্বাক্ষর</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($by_date as $dk => $rows):
          $subj_parts = [];
          foreach ($rows as $r) $subj_parts[] = $r['subject_name'].($r['subject_code'] ? ' ('.$r['subject_code'].')' : '');
        ?>
        <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 class="sig-cell"></td>
          <td class="sig-cell"></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($by_date)): ?>
          <tr><td colspan="5" style="text-align:center;color:#aaa;font-style:italic">কোনো বিষয় পাওয়া যায়নি</td></tr>
        <?php endif; ?>
      </tbody>
    </table>

    <!-- 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>
</div>
<?php endforeach; ?>

<?php elseif ($has_results && empty($students)): ?>
<div class="empty-state no-print">
  <i class="fas fa-user-slash" style="color:var(--teal);opacity:.3"></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-clipboard-list" style="color:var(--teal);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>
document.getElementById('exam_id').addEventListener('change', function() {
    ['class_id','session','group_name'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.disabled = false;
    });
});

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

document.addEventListener('DOMContentLoaded', function() {
    const inp = document.getElementById('studentSearch');
    const pfBtn = document.getElementById('printFilteredBtn');
    const visNum = document.getElementById('visibleNum');

    if (inp) {
        inp.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('.cert-card');
            let visible = 0;
            cards.forEach(card => {
                if (!terms.length) { card.style.display = 'block'; visible++; return; }
                const match = terms.some(t =>
                    (card.dataset.name||'').includes(t) ||
                    (card.dataset.roll||'').includes(t) ||
                    (card.dataset.id  ||'').includes(t)
                );
                card.style.display = match ? 'block' : 'none';
                if (match) visible++;
            });
            if (visNum) visNum.textContent = visible;
            if (pfBtn) pfBtn.style.display = terms.length ? 'inline-block' : 'none';
        });
    }
});

function printFiltered() {
    document.querySelectorAll('.cert-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) {
    document.getElementById('printBgColor').value = color;
    document.getElementById('printBgColorHex').value = color;
    saveBgColor(color);
    applyBgColor(color);
}
document.getElementById('printBgColor').addEventListener('input', function() {
    document.getElementById('printBgColorHex').value = this.value;
    saveBgColor(this.value);
    applyBgColor(this.value);
});
document.getElementById('printBgColorHex').addEventListener('input', function() {
    if (/^#[0-9a-f]{6}$/i.test(this.value)) {
        document.getElementById('printBgColor').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('attendance_print_bg', color); } catch(e) {}
}
function loadBgColor() {
    try { return localStorage.getItem('attendance_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);
    const style = document.getElementById('customPrintStyle');
    if (style) style.textContent =
        '.cert-card,.cert-body,.cert-header,.stu-grid,.att-table thead tr,.roll-badge,.group-badge,.cert-title{background:'+color+'!important}'
        +'.cert-header .hdr-center h2,.cert-title,.info-item .val,.att-table thead th,.att-table tbody td,.roll-badge,.group-badge{color:'+tc+'!important}'
        +'.cert-header .hdr-center p,.info-item .lbl,.sig-item p{color:'+tcm+'!important}'
        +'.att-table tbody td{border-color:'+tcm+'!important}'
        +'.att-table thead th{border-bottom:2px solid '+tc+'!important}'
        +'.roll-badge,.group-badge,.cert-title{border:1px solid '+tc+'!important}'
        +'.sig-line{border-top-color:'+tcm+'!important}'
        +'@media print{'
        +'.cert-card,.cert-body,.cert-header,.stu-grid,.att-table thead tr,.roll-badge,.group-badge,.cert-title{background:'+color+'!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}'
        +'.cert-header .hdr-center h2,.cert-title,.info-item .val,.att-table thead th,.att-table tbody td,.roll-badge,.group-badge{color:'+tc+'!important}'
        +'.cert-header .hdr-center p,.info-item .lbl,.sig-item p{color:'+tcm+'!important}'
        +'.att-table tbody td{border-color:'+tcm+'!important}'
        +'.att-table thead th{border-bottom:2px solid '+tc+'!important}'
        +'.roll-badge,.group-badge,.cert-title{border:1px solid '+tc+'!important}'
        +'.sig-line{border-top-color:'+tcm+'!important}'
        +'}'
}
// Apply saved color on load
document.addEventListener('DOMContentLoaded', function() {
    const saved = loadBgColor();
    setBgColor(saved);
});

if (window.matchMedia) {
    window.matchMedia('print').addListener(mql => {
        if (!mql.matches) {
            document.querySelectorAll('.temp-hidden-for-print').forEach(c => {
                c.classList.remove('temp-hidden-for-print');
                c.style.display = 'block';
            });
        }
    });
}
</script>
</body>
</html>
