<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/site_settings.php';

// Load site settings
$settings = get_all_settings($pdo);
$school_name = isset($_GET['school_name']) ? trim($_GET['school_name']) : ($settings['site_name'] ?? 'প্রতিষ্ঠান নাম');
$school_address = isset($_GET['school_address']) ? trim($_GET['school_address']) : ($settings['site_address'] ?? 'ঠিকানা, জেলা, দেশ');
$logo_image = $settings['logo_image'] ?? null;
$logo_size_default = isset($settings['logo_size']) ? intval($settings['logo_size']) : 80;
$logo_size = isset($_GET['logo_size']) ? (int)$_GET['logo_size'] : $logo_size_default;
$logo_size = max(40, min(150, $logo_size)); // Constrain between 40-150px
$school_name_size = isset($_GET['school_name_size']) ? (int)$_GET['school_name_size'] : 100;
$school_name_size = max(70, min(150, $school_name_size)); // Constrain between 70-150%

// Filter parameters
$exam = isset($_GET['exam']) ? trim($_GET['exam']) : '';
$manual_exam = isset($_GET['manual_exam']) ? trim($_GET['manual_exam']) : '';
$exam = ($exam === 'other' && $manual_exam !== '') ? $manual_exam : $exam;
$session = isset($_GET['session']) ? trim($_GET['session']) : '';
$manual_session = isset($_GET['manual_session']) ? trim($_GET['manual_session']) : '';
$session = ($session === 'other' && $manual_session !== '') ? $manual_session : $session;
$class_id = isset($_GET['class_id']) && is_numeric($_GET['class_id']) ? (int)$_GET['class_id'] : null;
$group = isset($_GET['group']) ? trim($_GET['group']) : '';
$manual_group = isset($_GET['manual_group']) ? trim($_GET['manual_group']) : '';
$group = ($group === 'other' && $manual_group !== '') ? $manual_group : $group;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$border = isset($_GET['border']) && $_GET['border'] == '1';
$watermark = isset($_GET['watermark']) ? trim($_GET['watermark']) : '';
$bg_design = isset($_GET['bg_design']) ? trim($_GET['bg_design']) : 'none';
$watermark_opacity = isset($_GET['watermark_opacity']) ? (int)$_GET['watermark_opacity'] : 15;
$watermark_size = isset($_GET['watermark_size']) ? (int)$_GET['watermark_size'] : 60;
$watermark_type = isset($_GET['watermark_type']) ? trim($_GET['watermark_type']) : 'text'; // 'text' or 'logo'
$use_logo_watermark = isset($_GET['use_logo_watermark']) && $_GET['use_logo_watermark'] == '1';

// Prepare dropdowns
try { $classes_list = $pdo->query("SELECT id, name, section FROM classes ORDER BY name")->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { $classes_list = []; }
try { $sessions_list = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN); } catch (Exception $e) { $sessions_list = []; }
try { 
    $groups_list = $pdo->query("SELECT DISTINCT group_name FROM student_groups WHERE group_name IS NOT NULL ORDER BY group_name")->fetchAll(PDO::FETCH_COLUMN); 
} catch (Exception $e) { 
    try {
        $groups_list = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL ORDER BY group_name")->fetchAll(PDO::FETCH_COLUMN);
    } catch (Exception $e2) { $groups_list = []; }
}
try { $exams_list = $pdo->query("SELECT DISTINCT exam_type FROM results WHERE exam_type IS NOT NULL ORDER BY exam_type")->fetchAll(PDO::FETCH_COLUMN); } catch (Exception $e) { $exams_list = []; }

// Build query
$where = ["s.status = 'active'"];
$params = [];
if (!empty($class_id)) { $where[] = 's.class_id = ?'; $params[] = $class_id; }
if (!empty($session)) { $where[] = 's.session = ?'; $params[] = $session; }
if (!empty($group)) { $where[] = 's.group_name = ?'; $params[] = $group; }
if (!empty($search)) { 
    $where[] = '(s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR s.roll_number LIKE ?)'; 
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]); 
}

$sql = "SELECT s.*, c.name as class_name, c.section FROM students s LEFT JOIN classes c ON s.class_id = c.id";
if (!empty($where)) $sql .= ' WHERE ' . implode(' AND ', $where);
$sql .= ' ORDER BY c.name, s.roll_number LIMIT 500';

// Debug: যদি search থাকে তাহলে দেখান
// error_log("Search: " . $search . " | SQL: " . $sql);

// Subject statements
$stmt_student_subjects = $pdo->prepare("SELECT sub.*, ss.is_fourth_subject FROM student_subjects ss JOIN subjects sub ON ss.subject_id = sub.id WHERE ss.student_id = ? ORDER BY sub.name");
$stmt_class_subjects = $pdo->prepare("SELECT sub.* FROM class_subjects cs JOIN subjects sub ON cs.subject_id = sub.id WHERE cs.class_id = ? ORDER BY sub.name");

// Execute
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="bn">
<head>
    <meta charset="utf-8">
    <title>Admit Card - <?= htmlspecialchars($exam ?: 'পরীক্ষা') ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap');
        @page { size: A4; margin: 0; padding: 0; }
        * { box-sizing: border-box; }
        body { font-family: 'Hind Siliguri', sans-serif; margin:0; padding:8px; background:#f0f4f8; color:#2c3e50 }
        .controls { padding:16px; background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-bottom:3px solid #764ba2; position:sticky; top:0; z-index:100; border-radius:4px; }
        .controls form { display:flex; gap:10px; flex-wrap:wrap; align-items:center; }
        .controls label { color:#fff; font-weight:600; font-size:13px; }
        .controls select, .controls input { padding:8px 10px; border:none; border-radius:4px; font-size:13px; }
        .controls input[type="range"] { width:70px; }
        .controls span { color:#fff; font-size:12px; margin-left:4px; }
        .controls button { padding:8px 18px; background:#fff; color:#667eea; border:none; border-radius:4px; cursor:pointer; font-weight:700; transition:0.3s; }
        .controls button:hover { background:#f0f4f8; transform:translateY(-2px); box-shadow:0 4px 8px rgba(0,0,0,0.15); }
        
        .page { 
            width:210mm; height:297mm; box-sizing:border-box; padding:16mm; margin:12px auto; position:relative; background:#fff; 
            box-shadow:0 8px 20px rgba(0,0,0,0.1); border-radius:8px; overflow:hidden; page-break-after:always;
        }
        
        /* Background Logo */
        .page-bg-logo {
            position:absolute; top:0; left:0; right:0; bottom:0;
            background-position:center; background-size:35%; background-repeat:no-repeat;
            opacity:0.06; z-index:-1; pointer-events:none; border-radius:8px;
        }
        
        /* Decorative Alponas Border - Margin Only */
        .page.border::before {
            content: '';
            position:absolute; top:0; left:0; right:0; bottom:0;
            border:12px solid #d4af37;
            border-radius:12px;
            box-shadow:inset 0 0 8px rgba(212,175,55,0.3), 0 8px 20px rgba(0,0,0,0.1);
            pointer-events:none;
            background:
                repeating-linear-gradient(90deg, #d4af37 0px, #d4af37 2px, transparent 2px, transparent 8px) 0 0 / 100% 6px no-repeat,
                repeating-linear-gradient(90deg, #d4af37 0px, #d4af37 2px, transparent 2px, transparent 8px) 0 calc(100% - 6px) / 100% 6px no-repeat,
                repeating-linear-gradient(0deg, #d4af37 0px, #d4af37 2px, transparent 2px, transparent 8px) 0 0 / 6px 100% no-repeat,
                repeating-linear-gradient(0deg, #d4af37 0px, #d4af37 2px, transparent 2px, transparent 8px) calc(100% - 6px) 0 / 6px 100% no-repeat;
        }
        
        /* Alpona Corners */
        .page.border::after {
            content: '';
            position:absolute; top:0; left:0; right:0; bottom:0;
            background:
                radial-gradient(circle at 12px 12px, #d4af37 3px, transparent 3px),
                radial-gradient(circle at calc(100% - 12px) 12px, #d4af37 3px, transparent 3px),
                radial-gradient(circle at 12px calc(100% - 12px), #d4af37 3px, transparent 3px),
                radial-gradient(circle at calc(100% - 12px) calc(100% - 12px), #d4af37 3px, transparent 3px);
            background-size: 100% 100%, 100% 100%, 100% 100%, 100% 100%;
            background-repeat: no-repeat;
            border-radius:12px;
            pointer-events:none;
            z-index:2;
        }
        
        header { 
            text-align:center; margin-bottom:12px; display:flex; align-items:center; gap:12px; 
            padding-bottom:10px; border-bottom:3px solid #667eea;
        }
        .logo-img { 
            width:<?= $logo_size ?>px; height:<?= $logo_size ?>px; flex:0 0 <?= $logo_size ?>px; 
            border-radius:50%; border:3px solid #667eea; overflow:hidden; aspect-ratio:1/1;
            box-shadow:0 4px 12px rgba(102,126,234,0.3);
        }
        .logo-img img { width:100%; height:100%; object-fit:contain; }
        .school-block { flex:1; }
        .school-name { 
            font-size:clamp(16px, <?= $school_name_size ?>%, 22px); font-weight:700; color:#2c3e50; letter-spacing:0.5px;
            margin:0; font-family: 'Hind Siliguri', serif;
        }
        .school-addr { 
            font-size:clamp(11px, 2.5vw, 13px); margin-top:4px; line-height:1.5; color:#555;
            font-style:italic;
        }
        .exam-title { 
            margin-top:6px; font-size:clamp(14px, 3.5vw, 18px); font-weight:700; color:#667eea;
            text-transform:uppercase; letter-spacing:1px;
        }
        
        .info-grid { 
            display:grid; grid-template-columns: 1fr 1fr; gap:10px; margin-top:12px; 
        }
        .info-table { 
            width:100%; border-collapse:collapse; font-size:clamp(11px, 2vw, 13px); font-family: 'Hind Siliguri', sans-serif;
            background:rgba(102,126,234,0.08); border-radius:8px; overflow:hidden; border:1px solid rgba(102,126,234,0.15);
        }
        .info-table td { 
            padding:8px 10px; vertical-align:middle; border-bottom:1px solid rgba(102,126,234,0.1);
        }
        .info-table tr:last-child td { border-bottom:none; }
        .label { 
            width:40%; font-weight:700; color:#fff; background:#667eea; text-transform:uppercase; font-size:clamp(11px, 2.2vw, 13px); letter-spacing:0.4px; padding:8px 10px;
        }
        .photo { 
            width:100px; height:120px; border:3px solid #667eea; display:block; border-radius:8px;
            box-shadow:0 6px 16px rgba(102,126,234,0.25); object-fit:cover;
        }
        
        .subjects { margin-top:12px; }
        .subjects table { 
            width:100%; border-collapse:collapse; font-size:clamp(11px, 2vw, 13px); font-family: 'Hind Siliguri', sans-serif;
            border-radius:8px; overflow:hidden; background:rgba(255,255,255,0.3); border:1px solid rgba(102,126,234,0.15);
        }
        .subjects th { 
            background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color:#fff; padding:10px; text-align:left; font-weight:600;
        }
        .subjects td { 
            padding:8px 10px; border-bottom:1px solid rgba(102,126,234,0.1);
        }
        .subjects tr:last-child td { border-bottom:none; }
        .fourth-subject { 
            background:linear-gradient(90deg, #fff2cc 0%, #ffe680 100%);
            font-weight:600; color:#8b6e00;
        }
        
        .footer { 
            font-size:clamp(10px, 1.8vw, 12px); 
            display:flex; gap:16px; justify-content:space-between; 
            padding-top:8px; margin-top:12px; border-top:2px solid #667eea; color:#666;
        }
        .page-break { page-break-after: always; }
        
        /* Watermark */
        .watermark { 
            position:absolute; top:50%; left:50%; transform:translate(-50%, -50%) rotate(-45deg);
            white-space:nowrap; z-index:0; pointer-events:none;
            font-family:'Georgia', serif; letter-spacing:3px;
        }
        .watermark-logo {
            position:absolute; top:50%; left:50%; transform:translate(-50%, -50%) rotate(-25deg);
            z-index:0; pointer-events:none;
        }
        .watermark-logo img {
            width:100%; height:100%; object-fit:contain;
        }
        
        /* Background Designs - only on borders/margins, disabled when border is active */
        .page::after {
            content: '';
            position:absolute; top:0; left:0; right:0; bottom:0;
            pointer-events:none; border-radius:8px;
            z-index:-1;
        }
        .page.border::after { display:none !important; }
        .page.border .page::after { display:none !important; }
        .bg-dots::after { background-image: radial-gradient(circle, rgba(102,126,234,0.08) 1px, transparent 1px); background-size: 20px 20px; }
        .bg-grid::after { background-image: linear-gradient(rgba(102,126,234,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(102,126,234,0.05) 1px, transparent 1px); background-size: 25px 25px; }
        .bg-diagonal::after { background-image: repeating-linear-gradient(45deg, rgba(102,126,234,0.03), rgba(102,126,234,0.03) 10px, transparent 10px, transparent 20px); }
        .bg-waves::after { background-image: url("data:image/svg+xml,%3Csvg width='40' height='12' viewBox='0 0 40 12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 6c5-5 15-5 20 0s15 5 20 0' stroke='rgba(102,126,234,0.1)' fill='none' stroke-width='1'/%3E%3C/svg%3E"); background-repeat: repeat-x; background-position: 0 0; background-size: auto 40px; }
        .bg-mandala::after { background-image: radial-gradient(circle at 20% 50%, rgba(212,175,55,0.05) 0%, transparent 50%), radial-gradient(circle at 80% 80%, rgba(102,126,234,0.05) 0%, transparent 50%); }
        .bg-gradient::after { background:linear-gradient(135deg, rgba(102,126,234,0.02) 0%, rgba(212,175,55,0.02) 100%); }
        
        /* Tablet/Mobile Responsiveness */
        @media (max-width: 1024px) {
            .page { width:100%; height:auto; min-height:297mm; margin:8px auto; padding:12mm; }
            .info-grid { grid-template-columns: 1fr; gap:8px; }
            header { gap:10px; }
            .logo-img { width:60px; height:60px; }
        }
        
        @media (max-width: 768px) {
            .page { padding:10mm; margin:4px auto; }
            .controls { padding:12px; font-size:12px; }
            .controls select, .controls input { padding:6px 8px; font-size:12px; }
            .logo-img { width:50px; height:50px; }
            .photo { width:80px; height:100px; }
            header { gap:8px; margin-bottom:10px; }
        }
        
        @media (max-width: 480px) {
            .page { width:calc(100% - 8px); padding:8mm; margin:4px; }
            .controls form { gap:6px; }
            .controls label { font-size:11px; }
            .controls input[type="text"], .controls select { padding:5px 6px; font-size:11px; }
            .info-grid { gap:6px; margin-top:8px; }
            .logo-img { width:40px; height:40px; border-width:2px; }
            .photo { width:70px; height:90px; border-width:2px; }
            header { margin-bottom:8px; }
            .school-name { font-size:14px; }
        }
        
        @media print { 
            body { background:#fff; padding:0; margin:0; }
            .page { margin:0; box-shadow:none; border-radius:0; width:210mm; height:297mm; padding:16mm; page-break-after:always; }
            .info-grid { display:grid; grid-template-columns: 1fr 1fr; gap:10px; margin-top:12px; }
            .page-bg-logo { display:block !important; opacity:0.06; }
            .page.border::before { display:block !important; }
            .page.border::after { display:block !important; }
            .controls { display:none !important; } 
            .watermark { display:none !important; }
            .page-break { page-break-after: always; }
        }
    </style>
    <script>
        function toggleOther(selectEl, otherId){
            var other = document.getElementById(otherId);
            other.style.display = (selectEl.value === 'other') ? 'inline-block' : 'none';
        }
    </script>
</head>
<body>

<div class="controls">
    <form method="get" action="">
        <label>Session:
            <select name="session" onchange="toggleOther(this,'manual_session')">
                <option value="">--</option>
                <?php foreach($sessions_list as $sopt): ?>
                    <option value="<?= htmlspecialchars($sopt) ?>"<?= $sopt === $session ? ' selected' : '' ?>><?= htmlspecialchars($sopt) ?></option>
                <?php endforeach; ?>
                <option value="other"<?= ($session && $session === $manual_session) ? ' selected' : '' ?>>Other</option>
            </select>
            <input id="manual_session" name="manual_session" placeholder="Manual session" style="display:<?= ($session === 'other' ? 'inline-block' : (strlen($manual_session)?'inline-block':'none')) ?>;margin-left:6px" value="<?= htmlspecialchars($manual_session) ?>">
        </label>

        <label>Class:
            <select name="class_id">
                <option value="">--</option>
                <?php foreach($classes_list as $c): ?>
                    <option value="<?= $c['id'] ?>"<?= $c['id']==$class_id ? ' selected' : '' ?>><?= htmlspecialchars($c['name'].' '.$c['section']) ?></option>
                <?php endforeach; ?>
            </select>
        </label>

        <label>Group:
            <select name="group" onchange="toggleOther(this,'manual_group')">
                <option value="">--</option>
                <?php foreach($groups_list as $g): if(empty($g)) continue; ?>
                    <option value="<?= htmlspecialchars($g) ?>"<?= $g === $group ? ' selected' : '' ?>><?= htmlspecialchars($g) ?></option>
                <?php endforeach; ?>
                <option value="other"<?= ($group && $group === $manual_group) ? ' selected' : '' ?>>Other</option>
            </select>
            <input id="manual_group" name="manual_group" placeholder="Manual group" style="display:<?= ($group === 'other' ? 'inline-block' : (strlen($manual_group)?'inline-block':'none')) ?>;margin-left:6px" value="<?= htmlspecialchars($manual_group) ?>">
        </label>

        <label>Exam:
            <select name="exam" onchange="toggleOther(this,'manual_exam')">
                <option value="">--</option>
                <?php foreach($exams_list as $e): if(empty($e)) continue; ?>
                    <option value="<?= htmlspecialchars($e) ?>"<?= $e === $exam ? ' selected' : '' ?>><?= htmlspecialchars($e) ?></option>
                <?php endforeach; ?>
                <option value="other"<?= ($exam && $exam === $manual_exam) ? ' selected' : '' ?>>Other</option>
            </select>
            <input id="manual_exam" name="manual_exam" placeholder="Manual exam" style="display:<?= ($exam === 'other' ? 'inline-block' : (strlen($manual_exam)?'inline-block':'none')) ?>;margin-left:6px" value="<?= htmlspecialchars($manual_exam) ?>">
        </label>

        <label>Search:
            <input type="text" name="search" placeholder="Name / ID / Roll" value="<?= htmlspecialchars($search) ?>" autocomplete="off">
            <?php if (!empty($search)): ?>
                <span style="color:#28a745;font-weight:600;margin-left:6px">✓ খুঁজছি: <?= htmlspecialchars($search) ?></span>
            <?php endif; ?>
        </label>

        <label style="margin-left:8px">Border:
            <input type="checkbox" name="border" value="1" <?= $border ? 'checked' : '' ?>>
        </label>

        <label>Watermark:
            <input type="text" name="watermark" placeholder="Custom watermark text" value="<?= htmlspecialchars($watermark) ?>" maxlength="30">
        </label>

        <label>Watermark Opacity:
            <input type="range" name="watermark_opacity" min="5" max="50" value="<?= $watermark_opacity ?>" style="width:80px">
            <span><?= $watermark_opacity ?>%</span>
        </label>

        <label>Watermark Size:
            <input type="range" name="watermark_size" min="20" max="200" value="<?= $watermark_size ?>" style="width:80px" oninput="document.getElementById('watermarkSizeValue').textContent = this.value">
            <span id="watermarkSizeValue"><?= $watermark_size ?></span>px
        </label>

        <label>Use Logo as Watermark:
            <input type="checkbox" name="use_logo_watermark" value="1" <?= $use_logo_watermark ? 'checked' : '' ?>>
        </label>

        <label>Logo Size:
            <input type="range" name="logo_size" min="40" max="150" value="<?= $logo_size ?>" style="width:80px" oninput="document.getElementById('logoSizeValue').textContent = this.value">
            <span id="logoSizeValue"><?= $logo_size ?></span>px
        </label>

        <label>School Name Size:
            <input type="range" name="school_name_size" min="70" max="150" value="<?= $school_name_size ?>" style="width:80px" oninput="document.getElementById('schoolNameSizeValue').textContent = this.value">
            <span id="schoolNameSizeValue"><?= $school_name_size ?></span>%
        </label>

        <label>Background:
            <select name="bg_design">
                <option value="none"<?= $bg_design === 'none' ? ' selected' : '' ?>>None</option>
                <option value="dots"<?= $bg_design === 'dots' ? ' selected' : '' ?>>Dots</option>
                <option value="grid"<?= $bg_design === 'grid' ? ' selected' : '' ?>>Grid</option>
                <option value="diagonal"<?= $bg_design === 'diagonal' ? ' selected' : '' ?>>Diagonal Lines</option>
                <option value="waves"<?= $bg_design === 'waves' ? ' selected' : '' ?>>Waves</option>
                <option value="mandala"<?= $bg_design === 'mandala' ? ' selected' : '' ?>>Mandala</option>
                <option value="gradient"<?= $bg_design === 'gradient' ? ' selected' : '' ?>>Soft Gradient</option>
            </select>
        </label>

        <button type="submit">Filter</button>
        <button type="button" onclick="window.print()" style="background:#28a745;color:#fff;margin-left:4px">🖨️ Print</button>
    </form>
    <?php if (count($students) > 0): ?>
        <div style="display:inline-block;margin-left:12px;padding:6px 12px;background:#e8f4f8;border-radius:4px;font-size:13px;color:#0066cc;font-weight:600">
            মোট শিক্ষার্থী: <?= count($students) ?> জন
        </div>
    <?php elseif (isset($_GET['filter']) || !empty($class_id) || !empty($search) || !empty($session) || !empty($group)): ?>
        <div style="display:inline-block;margin-left:12px;padding:8px 12px;background:#fff3cd;border-radius:4px;font-size:13px;color:#856404;font-weight:600">
            ⚠️ কোন ফলাফল পাওয়া যায়নি
        </div>
    <?php endif; ?>
</div>

<?php foreach ($students as $idx => $s): ?>
    <div class="page<?= $border ? ' border' : '' ?> bg-<?= htmlspecialchars($bg_design) ?>">
        <?php if ($logo_image && file_exists(__DIR__ . '/' . $logo_image)): ?>
            <div class="page-bg-logo" style="background-image:url('<?= htmlspecialchars($logo_image) ?>');"></div>
        <?php endif; ?>
        <?php if ($use_logo_watermark && $logo_image && file_exists(__DIR__ . '/' . $logo_image)): ?>
            <div class="watermark-logo" style="width:<?= $watermark_size + 100 ?>px;height:<?= $watermark_size + 100 ?>px;opacity:<?= $watermark_opacity / 100 ?>">
                <img src="<?= htmlspecialchars($logo_image) ?>" alt="Watermark">
            </div>
        <?php elseif (!empty($watermark)): ?>
            <div class="watermark" style="font-size:<?= $watermark_size ?>px;color:rgba(200,200,200,<?= $watermark_opacity / 100 ?>)">
                <?= htmlspecialchars($watermark) ?>
            </div>
        <?php endif; ?>
        <div style="position:relative;z-index:1">
        <header>
            <?php if ($logo_image && file_exists(__DIR__ . '/' . $logo_image)): ?>
                <div class="logo-img"><img src="<?= htmlspecialchars($logo_image) ?>" alt="Logo"></div>
            <?php else: ?>
                <div class="logo-img" style="background:#eee;display:flex;align-items:center;justify-content:center;font-weight:700;color:#666;">Logo</div>
            <?php endif; ?>
            <div class="school-block">
                <div class="school-name"><?= htmlspecialchars($school_name) ?></div>
                <div class="school-addr"><?= nl2br(htmlspecialchars($school_address)) ?></div>
                <div class="exam-title"><?= htmlspecialchars($exam ?: 'পরীক্ষা') ?></div>
            </div>
        </header>

        <section class="info-grid">
            <div>
                <table class="info-table">
                    <tr><td class="label">নাম</td><td><?= htmlspecialchars(($s['first_name'] ?? '') . ' ' . ($s['last_name'] ?? '')) ?></td></tr>
                    <tr><td class="label">ছাত্র আইডি</td><td><?= htmlspecialchars($s['student_id'] ?? '-') ?></td></tr>
                    <tr><td class="label">রোল</td><td><?= htmlspecialchars($s['roll_number'] ?? '-') ?></td></tr>
                    <tr><td class="label">শ্রেণি</td><td><?= htmlspecialchars(($s['class_name'] ?? '-') . ' ' . ($s['section'] ?? '')) ?></td></tr>
                    <tr><td class="label">জন্মতারিখ</td><td><?= htmlspecialchars($s['date_of_birth'] ?? '-') ?></td></tr>
                    <tr><td class="label">রক্তের গ্রুপ</td><td><?= htmlspecialchars($s['blood_group'] ?? '-') ?></td></tr>
                </table>
            </div>

            <div style="display:flex;gap:12px;align-items:flex-start">
                <div style="flex:1">
                    <table class="info-table">
                        <tr><td class="label">পিতা/অভিভাবক</td><td><?= htmlspecialchars($s['guardian_name'] ?? '-') ?></td></tr>
                        <tr><td class="label">অভিভাবকের ফোন</td><td><?= htmlspecialchars($s['guardian_phone'] ?? $s['phone'] ?? '-') ?></td></tr>
                        <tr><td class="label">ঠিকানা</td><td><?= htmlspecialchars($s['address'] ?? '-') ?></td></tr>
                        <tr><td class="label">ভর্তি তারিখ</td><td><?= htmlspecialchars($s['admission_date'] ?? '-') ?></td></tr>
                    </table>
                </div>

                <div style="width:130px;text-align:center">
                    <?php if (!empty($s['photo']) && file_exists(__DIR__ . '/' . $s['photo'])): ?>
                        <img src="<?= htmlspecialchars($s['photo']) ?>" alt="photo" class="photo">
                    <?php else: ?>
                        <div class="photo" style="display:flex;align-items:center;justify-content:center;color:#666;font-size:12px">ছবি নেই</div>
                    <?php endif; ?>
                </div>
            </div>
        </section>

        <section class="subjects">
            <?php
                $subjects = [];
                $fourth = null;
                $noFourthClass = in_array((int)$s['class_id'], [6,7,8]);
                try {
                    $stmt_student_subjects->execute([$s['id']]);
                    $subs = $stmt_student_subjects->fetchAll(PDO::FETCH_ASSOC);
                    foreach($subs as $sub){
                        // Class 6,7,8: all subjects compulsory — no fourth subject separation
                        if (!$noFourthClass && !empty($sub['is_fourth_subject'])) { 
                            $fourth = $sub; 
                        } else { 
                            $subjects[] = $sub; 
                        }
                    }
                } catch (Exception $e) { 
                    $subjects = []; 
                }

                if (empty($subjects) && empty($fourth) && !empty($s['class_id'])) {
                    try {
                        $stmt_class_subjects->execute([$s['class_id']]);
                        $subs = $stmt_class_subjects->fetchAll(PDO::FETCH_ASSOC);
                        foreach($subs as $sub){ 
                            $subjects[] = $sub; 
                        }
                    } catch (Exception $e) { 
                        $subjects = []; 
                    }
                }
            ?>

            <table>
                <thead>
                    <tr><th style="width:6%">ক্রম</th><th>বিষয়</th><th style="width:20%">কোড</th></tr>
                </thead>
                <tbody>
                    <?php if (!empty($subjects)): 
                        foreach ($subjects as $i => $sub): ?>
                            <tr>
                                <td><?= ($i+1) ?></td>
                                <td><?= htmlspecialchars($sub['name'] ?? '') ?></td>
                                <td><?= htmlspecialchars($sub['code'] ?? '') ?></td>
                            </tr>
                        <?php endforeach; 
                    else: ?>
                        <tr><td colspan="3">বিষয় তালিকা পাওয়া যায়নি</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <?php if (!empty($fourth)): ?>
                <table style="margin-top:8px">
                    <tbody>
                        <tr class="fourth-subject"><td style="width:6%">৪</td><td>৪র্থ বিষয়: <?= htmlspecialchars($fourth['name'] ?? '') ?></td><td><?= htmlspecialchars($fourth['code'] ?? '') ?></td></tr>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <div class="footer">
            <div style="flex:1;line-height:1.6;font-size:clamp(10px, 1.8vw, 12px)">
                <strong>পরীক্ষার নির্দেশনা:</strong><br>
                • সময়মতো পরীক্ষার হলে আসবেন<br>
                • প্রশ্নপত্র পড়ুন এবং সাবধানে উত্তর লিখুন<br>
                • নকল করা কঠোরভাবে নিষিদ্ধ
            </div>
            <div style="flex:1;text-align:center;padding-top:20px">
                <div style="font-size:clamp(10px, 1.8vw, 11px);margin-bottom:30px">পরীক্ষক/অধ্যক্ষের স্বাক্ষর</div>
                <div style="border-top:1px solid #333;width:80%;margin:0 auto;height:40px"></div>
            </div>
        </div>
        </div>
    </div>
    <div class="page-break"></div>
<?php endforeach; ?>

<div style="padding:12px;font-size:12px;color:#444;text-align:center">নোট: প্রিন্ট করার সময় পেজ সাইজ A4 এবং মার্জিন 15mm সেট করুন।</div>

</body>
</html>
