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

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

$req = ($_SERVER['REQUEST_METHOD']==='POST') ? $_POST : $_GET;

$exam_id = isset($req['exam_id']) ? trim($req['exam_id']) : '';
$cards_per_page = isset($req['cards_per_page']) ? (int)$req['cards_per_page'] : 12;
$custom_heading = isset($req['custom_heading']) ? trim($req['custom_heading']) : '';
$subtitle = isset($req['subtitle']) ? trim($req['subtitle']) : '';
$address = isset($req['address']) ? trim($req['address']) : '';

$font_family = isset($req['font_family']) ? trim($req['font_family']) : '';
$heading_size = isset($req['heading_size']) ? (int)$req['heading_size'] : 14;
$name_size = isset($req['name_size']) ? (int)$req['name_size'] : 14;
$roll_size = isset($req['roll_size']) ? (int)$req['roll_size'] : 24;
$footer_size = isset($req['footer_size']) ? (int)$req['footer_size'] : 11;
$line_height = isset($req['line_height']) ? (float)$req['line_height'] : 1.2;

// Additional filters (from subject tools)
$session_name = isset($req['session']) ? trim($req['session']) : '';
$class_id = isset($req['class_id']) ? trim($req['class_id']) : '';
$group_name = isset($req['group_name']) ? trim($req['group_name']) : '';
$subject_id = isset($req['subject_id']) ? trim($req['subject_id']) : '';

$placeholder_mode = isset($req['placeholder_mode']) ? $req['placeholder_mode'] : 'text';
$logo_mode    = isset($req['logo_mode'])    ? $req['logo_mode']                           : 'none';
$logo_size    = isset($req['logo_size'])    ? max(10, min(200, (int)$req['logo_size']))    : 40;
$logo_opacity = isset($req['logo_opacity']) ? max(5,  min(100, (int)$req['logo_opacity'])) : 20;
$logo_url     = isset($_SESSION['seat_logo_url']) ? $_SESSION['seat_logo_url'] : '';
$show_photo   = isset($req['show_photo'])   ? (int)$req['show_photo']                     : 1;   // 1=show, 0=hide
$photo_size   = isset($req['photo_size'])   ? max(20, min(100, (int)$req['photo_size']))  : 45;  // px

// Default to 'centered' when logo exists but no mode was explicitly sent (fresh page load or AJAX upload)
if (!empty($logo_url) && $logo_mode === 'none' && !isset($req['logo_mode'])) {
    $logo_mode = 'centered';
}

// Handle logo upload/remove
$upload_error = '';
$upload_success = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Upload
    if (isset($_POST['upload_logo'])) {
        if (!isset($_FILES['logo_file']) || $_FILES['logo_file']['error'] !== UPLOAD_ERR_OK) {
            $fe = isset($_FILES['logo_file']) ? $_FILES['logo_file']['error'] : -1;
            $upload_error = 'ফাইল আপলোড এরর: কোড '.$fe.'. অনুগ্রহ করে একটি ছবি সিলেক্ট করুন।';
        } else {
            $tmp  = $_FILES['logo_file']['tmp_name'];
            $name = $_FILES['logo_file']['name'];
            $size = $_FILES['logo_file']['size'];
            $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));

            // Detect type by extension AND mime (mime_content_type can misread SVG)
            $extAllowed  = ['png','jpg','jpeg','svg','webp'];
            $mimeAllowed = ['image/png','image/jpeg','image/jpg','image/svg+xml','image/webp','text/plain','text/html','application/octet-stream'];
            $mimeType    = function_exists('mime_content_type') ? mime_content_type($tmp) : 'application/octet-stream';

            if ($size > 2*1024*1024) {
                $upload_error = 'ফাইল সাইজ ২MB-এর বেশি।';
            } elseif (!in_array($ext, $extAllowed, true)) {
                $upload_error = 'শুধু PNG, JPG, SVG, WebP ফাইল সমর্থিত। আপলোড করা ফাইলের এক্সটেনশন: .'.$ext;
            } else {
                // For SVG, mime may report text/plain or text/html — allow by extension
                $diskDir = realpath(__DIR__.'/..').'/uploads/temp/seat_cards';
                if (!is_dir($diskDir)) { @mkdir($diskDir, 0777, true); }
                $safe = 'logo_'.date('Ymd_His').'_'.bin2hex(random_bytes(4)).'.'.$ext;
                $dest = $diskDir.'/'.$safe;
                if (@move_uploaded_file($tmp, $dest)) {
                    // Delete old logo file if exists
                    if (!empty($_SESSION['seat_logo_url'])) {
                        $oldFile = realpath(__DIR__.'/..').'/' . ltrim(str_replace('../', '', $_SESSION['seat_logo_url']), '/');
                        if (file_exists($oldFile)) { @unlink($oldFile); }
                    }
                    $webPath = '../uploads/temp/seat_cards/'.$safe;
                    $_SESSION['seat_logo_url'] = $webPath;
                    $logo_url = $webPath;
                    $upload_success = true;
                    // Auto-switch logo_mode to centered if currently none
                    if ($logo_mode === 'none') { $logo_mode = 'centered'; }
                } else {
                    $upload_error = 'ফাইল সেভ করা যায়নি। uploads/temp/seat_cards/ ডিরেক্টরি write-able কিনা চেক করুন।';
                }
            }
        }
    }
    // Remove
    if (isset($_POST['remove_logo'])) {
        if (!empty($_SESSION['seat_logo_url'])) {
            $oldFile = realpath(__DIR__.'/..').'/' . ltrim(str_replace('../', '', $_SESSION['seat_logo_url']), '/');
            if (file_exists($oldFile)) { @unlink($oldFile); }
        }
        unset($_SESSION['seat_logo_url']);
        $logo_url = '';
    }
}
// Prefer uploaded logo from session
if (isset($_SESSION['seat_logo_url']) && $_SESSION['seat_logo_url']) {
    $logo_url = $_SESSION['seat_logo_url'];
}

$gap_mm = isset($req['gap_mm']) ? (int)$req['gap_mm'] : 8;
$margin_mm = isset($req['margin_mm']) ? (int)$req['margin_mm'] : 10;

// Allow flexible counts and auto-fit to A4
$allowed_counts = range(1, 24);
if ($cards_per_page < 1) { $cards_per_page = 12; }

// Auto-calc grid (portrait A4 ~ 210x297mm)
$aspect = 210/297; // width/height
$cols = max(2, min(5, (int)round(sqrt($cards_per_page * $aspect))));
if ($cols < 1) { $cols = 1; }
$rows = (int)ceil($cards_per_page / $cols);
if ($rows > 6) { $rows = 6; $cols = (int)ceil($cards_per_page / $rows); }

// Load dropdown data for filters
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();

// Load class subjects if class selected
$class_subjects = [];
if (!empty($class_id)) {
    $stmt = $pdo->prepare("SELECT s.id, s.name, s.code
                           FROM class_subjects cs
                           JOIN subjects s ON cs.subject_id = s.id
                           WHERE cs.class_id = ? AND s.status='active'
                           ORDER BY s.name");
    $stmt->execute([$class_id]);
    $class_subjects = $stmt->fetchAll();
}

// Fetch exams for dropdown (filtered by optional session/class/group)
$examSql = "SELECT e.id, e.name, c.name AS class_name, c.section, e.session, e.group_name, e.created_at
            FROM exams e
            JOIN classes c ON e.class_id = c.id
            WHERE 1=1";
$examParams = [];
if (!empty($session_name)) { $examSql .= " AND e.session = ?"; $examParams[] = $session_name; }
if (!empty($class_id)) { $examSql .= " AND e.class_id = ?"; $examParams[] = $class_id; }
if ($group_name !== '') { $examSql .= " AND COALESCE(e.group_name,'') = ?"; $examParams[] = $group_name; }
$examSql .= " ORDER BY e.created_at DESC";
$stmt = $pdo->prepare($examSql);
$stmt->execute($examParams);
$all_exams = $stmt->fetchAll();

$exam_details = null;
$students = [];
if ($exam_id) {
    // Mode 1: Use exam
    $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) {
        // Students of the class/session (respect group when present); optionally filter by subject
        $sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.group_name, s.photo
                FROM students s ".
                (!empty($subject_id) ? "JOIN student_subjects ss ON ss.student_id = s.id AND ss.subject_id = ? " : "").
                "WHERE s.class_id = ? AND s.session = ? AND s.status = 'active' ".
                ($exam_details['group_name'] ? "AND s.group_name = ?" : "AND (s.group_name IS NULL OR s.group_name = '')").
                " ORDER BY CAST(s.roll_number AS UNSIGNED), s.first_name";
        $params = [];
        if (!empty($subject_id)) { $params[] = $subject_id; }
        $params[] = $exam_details['class_id'];
        $params[] = $exam_details['session'];
        if ($exam_details['group_name']) { $params[] = $exam_details['group_name']; }
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $students = $stmt->fetchAll();
    }
} elseif (!empty($class_id) && !empty($session_name)) {
    // Mode 2/3: Use filters (session + class + optional group + optional subject)
    $exam_details = [
        'name' => $custom_heading ?: 'Seat Cards',
        'session' => $session_name,
        'class_id' => $class_id,
        'group_name' => ($group_name !== '' ? $group_name : ''),
        // For header display: fetch class info
        'class_name' => '',
        'section' => ''
    ];
    // Fetch class info for header
    $stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
    $stmt->execute([$class_id]);
    if ($cinfo = $stmt->fetch()) { $exam_details['class_name'] = $cinfo['name']; $exam_details['section'] = $cinfo['section']; }

    $sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.group_name, s.photo
            FROM students s ".
            (!empty($subject_id) ? "JOIN student_subjects ss ON ss.student_id = s.id AND ss.subject_id = ? " : "").
            "WHERE s.class_id = ? AND s.session = ? AND s.status = 'active' ".
            ($group_name !== '' ? "AND COALESCE(s.group_name,'') = ?" : "").
            " ORDER BY CAST(s.roll_number AS UNSIGNED), s.first_name";
    $params = [];
    if (!empty($subject_id)) { $params[] = $subject_id; }
    $params[] = $class_id;
    $params[] = $session_name;
    if ($group_name !== '') { $params[] = $group_name; }
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

?>
<!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>
        :root{--gap:<?php echo (int)$gap_mm; ?>mm;--margin-mm:<?php echo (int)$margin_mm; ?>mm}
        @page{size:A4;margin:var(--margin-mm)}
        @media print{
            .no-print{display:none!important}
            .mini-card{background:#fff!important;border-color:#000!important;box-shadow:none!important}
            .mini-card::before{display:none!important}
            .exam-title{color:#000!important}.subtitle,.address,.meta{color:#000!important}
            .student-name{color:#000!important}.roll-box{color:#000!important;background:transparent!important;border:2px solid #000!important}
            .mini-footer{color:#000!important}.placeholder{color:#aaa!important;border-color:#bbb!important}
            .stu-photo{border-color:#999!important}
            .stu-photo-placeholder{border-color:#ccc!important;color:#aaa!important}
        }
        body{font-family:'Hind Siliguri',system-ui,-apple-system,sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0;font-size:.85rem}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 20px rgba(0,0,0,.4)}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none;display:flex;align-items:center;gap:8px}
        .top-bar .brand i{font-size:1.2rem}
        .top-bar .nav-links{display:flex;gap:12px}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.75rem;font-weight:500;padding:4px 10px;border-radius:6px;transition:.2s}
        .top-bar .nav-links a:hover{color:#fff;background:rgba(255,255,255,.08)}
        .filter-card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:10px 14px;margin-bottom:12px}
        .filter-card .form-label{font-size:.72rem;font-weight:600;color:#90caf9;margin-bottom:1px}
        .filter-card .form-select,.filter-card .form-control{font-size:.78rem;padding:3px 7px;border-radius:5px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0;height:auto}
        .filter-card .form-select:focus,.filter-card .form-control:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .filter-card .btn{font-size:.78rem;padding:3px 14px;border-radius:6px}
        .btn-primary-custom{background:linear-gradient(135deg,#1565c0,#1e88e5);border:none;color:#fff;font-weight:600}
        .btn-primary-custom:hover{background:linear-gradient(135deg,#1976d2,#2196f3);color:#fff}
        .btn-success-custom{background:linear-gradient(135deg,#2e7d32,#43a047);border:none;color:#fff;font-weight:600}
        .btn-success-custom:hover{background:linear-gradient(135deg,#388e3c,#4caf50);color:#fff}

        .page-grid{display:grid;grid-template-columns:repeat(var(--cols),1fr);gap:var(--gap);page-break-after:always;align-items:stretch}
        .page-grid{--cols:<?php echo (int)$cols; ?>}
        .mini-card{height:calc((297mm - 2*var(--margin-mm) - (<?php echo (int)$rows; ?> - 1)*var(--gap)) / <?php echo (int)$rows; ?>)}
        .page-grid:last-of-type{page-break-after:auto}

        .mini-card{
            position:relative;border:1.6px solid #263238;border-radius:8px;background:linear-gradient(135deg,#fafafa,#f0f0f0);padding:5mm 4mm;height:100%;
            display:flex;flex-direction:column;justify-content:space-between;overflow:hidden;
            page-break-inside:avoid;break-inside:avoid;box-shadow:0 1px 4px rgba(0,0,0,.05)
        }
        .mini-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;background:linear-gradient(90deg,#4fc3f7,#2196f3,#1565c0);border-radius:8px 8px 0 0}
        .mini-top{text-align:center}
        .exam-title{font-weight:700;font-size:<?php echo (int)$heading_size; ?>px;margin-bottom:1.5mm;line-height:<?php echo $line_height; ?>;color:#1565c0}
        .subtitle{font-size:<?php echo max(10,(int)($heading_size-2)); ?>px;color:#546e7a;line-height:<?php echo $line_height; ?>;margin-bottom:1mm}
        .address{font-size:<?php echo max(9,(int)($heading_size-3)); ?>px;color:#78909c;line-height:<?php echo $line_height; ?>;margin-bottom:1mm}
        .meta{font-size:<?php echo (int)$footer_size; ?>px;color:#607d8b;line-height:<?php echo $line_height; ?>}
        .student-name{text-align:center;font-weight:700;font-size:<?php echo (int)$name_size; ?>px;margin:2mm 0;line-height:<?php echo $line_height; ?>;color:#1a237e}
        .roll-box{text-align:center;padding:1.5mm 0;margin:0 auto;border:2px solid #1565c0;border-radius:6px;background:rgba(21,101,192,.06);font-size:<?php echo (int)$roll_size; ?>px;font-weight:900;letter-spacing:.5px;color:#1565c0;min-width:60%;max-width:90%}
        .mini-footer{font-size:<?php echo (int)$footer_size; ?>px;color:#455a64;text-align:left;margin-top:2mm;line-height:<?php echo $line_height; ?>}
        .placeholder{display:flex;align-items:center;justify-content:center;color:#bbb;border:1.6px dashed #ccc;background:rgba(200,200,200,.05)}
        .placeholder.outline{border-style:solid}
        .placeholder.hide{border:none;color:transparent}
        .mini-card .watermark{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none;opacity:<?php echo round($logo_opacity/100, 2); ?>}
        .mini-card .watermark img{width:<?php echo (int)$logo_size; ?>px;height:<?php echo (int)$logo_size; ?>px;max-width:90%;object-fit:contain}
        .mini-top .logo{margin-bottom:1.5mm;text-align:center}
        .mini-top .logo img{height:<?php echo (int)$logo_size; ?>px;max-width:100%;object-fit:contain;display:block;margin:0 auto}
        .stu-photo{position:absolute;top:4mm;right:3mm;width:<?php echo (int)$photo_size; ?>px;height:<?php echo (int)$photo_size; ?>px;border-radius:4px;border:1.5px solid #90caf9;object-fit:cover;background:#e3f2fd}
        .stu-photo-placeholder{position:absolute;top:4mm;right:3mm;width:<?php echo (int)$photo_size; ?>px;height:<?php echo (int)$photo_size; ?>px;border-radius:4px;border:1.5px dashed #90caf9;display:flex;align-items:center;justify-content:center;font-size:9px;color:#90caf9;background:#f0f7ff;text-align:center;line-height:1.2}
    </style>
</head>
<body class="bengali-text">
    <div class="top-bar no-print">
        <a class="brand" href="../index.php"><i class="fas fa-graduation-cap"></i> সীট কার্ড গ্রিড</a>
        <div class="nav-links">
            <a href="routine.php"><i class="fas fa-calendar me-1"></i>রুটিন</a>
            <a href="admit_card.php"><i class="fas fa-address-card me-1"></i>এডমিট কার্ড</a>
            <a href="attendance.php"><i class="fas fa-clipboard-check me-1"></i>হাজিরা</a>
            <a href="manage_exams.php"><i class="fas fa-list me-1"></i>পরীক্ষা</a>
        </div>
    </div>

    <div class="container-fluid" style="padding:10px 16px">
        <?php if ($upload_error): ?>
        <div class="alert alert-danger py-1 px-2 no-print" style="font-size:.8rem"><i class="fas fa-exclamation-circle me-1"></i><?php echo h($upload_error); ?></div>
        <?php endif; ?>
        <?php if ($upload_success): ?>
        <div class="alert alert-success py-1 px-2 no-print" style="font-size:.8rem"><i class="fas fa-check-circle me-1"></i>লোগো সফলভাবে আপলোড হয়েছে।</div>
        <?php endif; ?>
        <form method="POST" enctype="multipart/form-data" class="filter-card no-print">
            <div class="row g-1 align-items-end">
                <div class="col-lg-2 col-6"><label class="form-label">সেশন</label><select class="form-select" name="session"><option value="">সব</option><?php foreach($sessions as $s):?><option value="<?php echo h($s['session_name']);?>" <?php echo $session_name===$s['session_name']?'selected':'';?>><?php echo h($s['session_name']);?></option><?php endforeach;?></select></div>
                <div class="col-lg-2 col-6"><label class="form-label">ক্লাস</label><select class="form-select" name="class_id"><option value="">সব</option><?php foreach($classes as $c):?><option value="<?php echo h($c['id']);?>" <?php echo $class_id==$c['id']?'selected':'';?>><?php echo h($c['name'].'-'.$c['section']);?></option><?php endforeach;?></select></div>
                <div class="col-lg-2 col-6"><label class="form-label">গ্রুপ</label><select class="form-select" name="group_name"><option value="">সব</option><?php foreach($groups as $g):?><option value="<?php echo h($g['group_name']);?>" <?php echo $group_name===$g['group_name']?'selected':'';?>><?php echo h($g['group_name']);?></option><?php endforeach;?></select></div>
                <div class="col-lg-2 col-6"><label class="form-label">বিষয়</label><select class="form-select" name="subject_id"><option value="">-</option><?php foreach($class_subjects as $sub):?><option value="<?php echo h($sub['id']);?>" <?php echo $subject_id==$sub['id']?'selected':'';?>><?php echo h($sub['name']);?></option><?php endforeach;?></select></div>
                <div class="col-lg-2 col-6"><label class="form-label">পরীক্ষা</label><select class="form-select" name="exam_id"><option value="">নির্বাচন করুন</option><?php foreach($all_exams as $exam):?><option value="<?php echo h($exam['id']);?>" <?php echo $exam_id==$exam['id']?'selected':'';?>><?php echo h($exam['name']);?></option><?php endforeach;?></select></div>
                <div class="col-lg-1 col-6"><label class="form-label">প্রতি পৃষ্ঠা</label><select class="form-select" name="cards_per_page"><?php foreach($allowed_counts as $n):?><option value="<?php echo $n;?>" <?php echo $cards_per_page==$n?'selected':'';?>><?php echo $n;?></option><?php endforeach;?></select></div>
                <div class="col-lg-1 col-6"><label class="form-label">&nbsp;</label><button type="submit" class="btn btn-primary-custom w-100"><i class="fas fa-search"></i></button></div>
            </div>
            <div class="row g-1 align-items-end mt-1">
                <div class="col-lg-2 col-6"><label class="form-label">শিরোনাম</label><input type="text" class="form-control" name="custom_heading" value="<?php echo h($custom_heading);?>" placeholder="Exam-2025"></div>
                <div class="col-lg-2 col-6"><label class="form-label">উপশিরোনাম</label><input type="text" class="form-control" name="subtitle" value="<?php echo h($subtitle);?>" placeholder="Center-2"></div>
                <div class="col-lg-2 col-6"><label class="form-label">ঠিকানা</label><input type="text" class="form-control" name="address" value="<?php echo h($address);?>" placeholder="School, address"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Heading</label><input type="number" class="form-control" name="heading_size" value="<?php echo h($heading_size);?>"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Name</label><input type="number" class="form-control" name="name_size" value="<?php echo h($name_size);?>"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Roll</label><input type="number" class="form-control" name="roll_size" value="<?php echo h($roll_size);?>"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Footer</label><input type="number" class="form-control" name="footer_size" value="<?php echo h($footer_size);?>"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Line H</label><input type="number" step="0.1" class="form-control" name="line_height" value="<?php echo h($line_height);?>"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Gap</label><input type="number" class="form-control" name="gap_mm" value="<?php echo h($gap_mm);?>" min="2" max="20"></div>
                <div class="col-lg-1 col-4"><label class="form-label">Margin</label><input type="number" class="form-control" name="margin_mm" value="<?php echo h($margin_mm);?>" min="5" max="20"></div>
            </div>
            <div class="row g-1 align-items-end mt-1">
                <div class="col-lg-2 col-6"><label class="form-label">Placeholder</label><select class="form-select" name="placeholder_mode"><option value="text" <?php echo $placeholder_mode==='text'?'selected':'';?>>Text</option><option value="outline" <?php echo $placeholder_mode==='outline'?'selected':'';?>>Outline</option><option value="hide" <?php echo $placeholder_mode==='hide'?'selected':'';?>>Hide</option></select></div>
                <div class="col-lg-2 col-6"><label class="form-label">Logo</label><select class="form-select" name="logo_mode"><option value="centered" <?php echo $logo_mode==='centered'?'selected':'';?>>Centered</option><option value="watermark" <?php echo $logo_mode==='watermark'?'selected':'';?>>Watermark</option><option value="none" <?php echo $logo_mode==='none'?'selected':'';?>>No Logo</option></select></div>

                <!-- Logo Size -->
                <div class="col-lg-1 col-4">
                    <label class="form-label" title="Centered মোডে লোগোর উচ্চতা (px)">Logo Size</label>
                    <div class="d-flex align-items-center gap-1">
                        <input type="range" class="form-range" id="logo_size_range" name="logo_size"
                               min="10" max="200" step="2" value="<?php echo (int)$logo_size; ?>"
                               style="flex:1;accent-color:#4fc3f7"
                               oninput="document.getElementById('logo_size_num').value=this.value;updateLogoPreviewStyle()">
                        <input type="number" id="logo_size_num" min="10" max="200" step="2"
                               value="<?php echo (int)$logo_size; ?>"
                               style="width:46px;font-size:.72rem;padding:2px 4px;border-radius:4px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0;text-align:center"
                               oninput="document.getElementById('logo_size_range').value=this.value;updateLogoPreviewStyle()">
                    </div>
                </div>

                <!-- Logo Opacity -->
                <div class="col-lg-2 col-4">
                    <label class="form-label" title="Watermark মোডে অপাসিটি (%)">Logo Opacity %</label>
                    <div class="d-flex align-items-center gap-1">
                        <input type="range" class="form-range" id="logo_opacity_range" name="logo_opacity"
                               min="5" max="100" step="5" value="<?php echo (int)$logo_opacity; ?>"
                               style="flex:1;accent-color:#4fc3f7"
                               oninput="document.getElementById('logo_opacity_num').value=this.value;updateLogoPreviewStyle()">
                        <input type="number" id="logo_opacity_num" min="5" max="100" step="5"
                               value="<?php echo (int)$logo_opacity; ?>"
                               style="width:46px;font-size:.72rem;padding:2px 4px;border-radius:4px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0;text-align:center"
                               oninput="document.getElementById('logo_opacity_range').value=this.value;updateLogoPreviewStyle()">
                    </div>
                </div>

                <div class="col-lg-3 col-12"><label class="form-label">লোগো আপলোড (PNG/JPG/SVG/WebP, 2MB)</label>
                    <div class="d-flex gap-1 align-items-center">
                        <input type="file" class="form-control" id="logo_file_input" name="logo_file" accept=".png,.jpg,.jpeg,.svg,.webp">
                        <button type="button" id="btn_upload_logo" class="btn btn-sm btn-outline-light" style="font-size:.72rem;padding:2px 10px;white-space:nowrap" title="আপলোড করুন"><i class="fas fa-upload"></i></button>
                        <?php if($logo_url):?>
                        <img id="logo_preview" src="<?php echo h($logo_url);?>" alt="logo" style="max-height:28px;border-radius:4px;border:1px solid rgba(255,255,255,.2)">
                        <button type="button" id="btn_remove_logo" class="btn btn-sm btn-outline-danger" style="font-size:.72rem;padding:2px 10px" title="সরান"><i class="fas fa-trash"></i></button>
                        <?php else:?>
                        <img id="logo_preview" src="" alt="" style="max-height:28px;border-radius:4px;border:1px solid rgba(255,255,255,.2);display:none">
                        <button type="button" id="btn_remove_logo" class="btn btn-sm btn-outline-danger" style="font-size:.72rem;padding:2px 10px;display:none" title="সরান"><i class="fas fa-trash"></i></button>
                        <?php endif;?>
                        <span id="logo_upload_status" style="font-size:.72rem"></span>
                    </div>
                </div>
                <div class="col-lg-2 col-6 d-flex gap-1 align-items-end">
                    <!-- Photo toggle & size -->
                    <div style="flex:1">
                        <label class="form-label">শিক্ষার্থীর ছবি</label>
                        <div class="d-flex gap-1 align-items-center">
                            <select class="form-select" name="show_photo" style="width:auto">
                                <option value="1" <?php echo $show_photo?'selected':'';?>>দেখাও</option>
                                <option value="0" <?php echo !$show_photo?'selected':'';?>>লুকাও</option>
                            </select>
                            <input type="number" class="form-control" name="photo_size" value="<?php echo (int)$photo_size; ?>" min="20" max="100" style="width:56px" title="ছবির সাইজ (px)">
                            <span style="font-size:.68rem;color:rgba(255,255,255,.4)">px</span>
                        </div>
                    </div>
                </div>
                <div class="col-lg-1 col-6 d-flex align-items-end">
                    <?php if($exam_details && !empty($students)):?><button type="button" class="btn btn-success-custom w-100" onclick="window.print()"><i class="fas fa-print me-1"></i>প্রিন্ট</button><?php endif;?>
                </div>
            </div>
        </form>
        <!-- DEBUG STRIP -->
        <div class="no-print" style="font-size:.7rem;color:rgba(255,255,255,.4);padding:2px 4px;margin-bottom:4px">
            Logo mode: <b style="color:#4fc3f7"><?php echo h($logo_mode); ?></b> &nbsp;|&nbsp;
            Logo URL: <b style="color:#4fc3f7"><?php echo $logo_url ? h($logo_url) : '<span style="color:#ef9a9a">NOT SET</span>'; ?></b>
            <?php if($logo_url): ?>
            &nbsp;| <a href="<?php echo h($logo_url);?>" target="_blank" style="color:#81c784;font-size:.68rem">ফাইল দেখুন ↗</a>
            <?php endif; ?>
        </div>

        <?php if ($exam_details && !empty($students)): ?>
            <div class="d-flex align-items-center gap-2 mb-2 no-print">
                <span class="badge" style="background:rgba(79,195,247,.15);color:#4fc3f7;font-weight:600;font-size:.75rem"><?php echo count($students); ?> জন শিক্ষার্থী</span>
                <span class="badge" style="background:rgba(255,255,255,.06);color:rgba(255,255,255,.5);font-weight:400;font-size:.7rem"><?php echo $cards_per_page; ?> টি/পৃষ্ঠা</span>
            </div>
            <?php
                $chunks = array_chunk($students, $cards_per_page);
                $page_index = 0;
            ?>
            <?php foreach ($chunks as $chunk): $page_index++; ?>
                <div class="page-grid" style="--cols: <?php echo (int)$cols; ?>;">
                    <?php foreach ($chunk as $stu): ?>
                        <div class="mini-card">
                            <?php if ($logo_mode==='watermark' && $logo_url): ?>
                                <div class="watermark" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none;opacity:<?php echo round($logo_opacity/100,2); ?>">
                                    <img src="<?php echo h($logo_url); ?>" alt="wm" style="max-width:80%;max-height:80%">
                                </div>
                            <?php endif; ?>
                            <?php if ($show_photo): ?>
                                <?php
                                    $purl = '';
                                    if (!empty($stu['photo'])) {
                                        // photo column may be relative like uploads/student_photos/xxx.jpg
                                        $pfile = realpath(__DIR__.'/../'.$stu['photo']);
                                        if ($pfile && file_exists($pfile)) {
                                            $purl = '../'.$stu['photo'];
                                        } elseif (file_exists(realpath(__DIR__.'/../').'/'.$stu['photo'])) {
                                            $purl = '../'.$stu['photo'];
                                        }
                                    }
                                ?>
                                <?php if ($purl): ?>
                                    <img class="stu-photo" src="<?php echo h($purl); ?>" alt="photo">
                                <?php else: ?>
                                    <div class="stu-photo-placeholder">ছবি<br>নেই</div>
                                <?php endif; ?>
                            <?php endif; ?>
                            <div class="mini-top">
                                <?php if ($logo_mode==='centered' && $logo_url): ?>
                                    <div class="logo"><img src="<?php echo h($logo_url); ?>" alt="logo" style="height:<?php echo (int)$logo_size; ?>px;max-width:100%;object-fit:contain;display:block;margin:0 auto"></div>
                                <?php endif; ?>
                                <div class="exam-title"><?php echo h($custom_heading ?: $exam_details['name']); ?></div>
                                <?php if ($subtitle): ?><div class="subtitle"><?php echo h($subtitle); ?></div><?php endif; ?>
                                <?php if ($address): ?><div class="address"><?php echo h($address); ?></div><?php endif; ?>
                                <div class="meta">
                                    <?php if (!empty($exam_details['group_name'])): ?>গ্রুপ/Group: <?php echo h($exam_details['group_name']); ?><br><?php endif; ?>
                                    ক্লাস/Class: <?php echo h($exam_details['class_name'].' - '.$exam_details['section']); ?>
                                </div>
                            </div>
                            <div class="student-name"><?php echo h(trim($stu['first_name'].' '.$stu['last_name'])); ?></div>
                            <div class="roll-box"><?php echo h($stu['roll_number']); ?></div>
                            <div class="mini-footer">
                                Reg/রেজিঃ <?php echo h($stu['student_id']); ?><br>
                                <?php if (!empty($stu['group_name'])): ?>বিভাগ/Group: <?php echo h($stu['group_name']); ?><br><?php endif; ?>
                                Session/সেশন: <?php echo h($exam_details['session']); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <?php // Fill placeholders if last page not full
                        $remaining = $cards_per_page - count($chunk);
                        for ($i=0; $i<$remaining; $i++): ?>
                        <?php if ($placeholder_mode !== 'hide'): ?>
                        <div class="mini-card placeholder <?php echo $placeholder_mode==='outline' ? 'outline' : ''; ?>">
                            <?php echo $placeholder_mode==='text' ? 'Empty' : '&nbsp;'; ?>
                        </div>
                        <?php else: ?>
                        <div class="mini-card" style="visibility:hidden"></div>
                        <?php endif; ?>
                    <?php endfor; ?>
                </div>
            <?php endforeach; ?>
        <?php elseif ($exam_id): ?>
            <div class="alert alert-warning mt-3"><i class="fas fa-info-circle"></i> কোন শিক্ষার্থী পাওয়া যায়নি।</div>
        <?php endif; ?>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Live update logo size & opacity on cards without page reload
    function updateLogoPreviewStyle(){
        var sizeEl    = document.getElementById('logo_size_range');
        var opacityEl = document.getElementById('logo_opacity_range');
        var size    = sizeEl    ? (parseInt(sizeEl.value)    || <?php echo (int)$logo_size; ?>)    : <?php echo (int)$logo_size; ?>;
        var opacity = opacityEl ? (parseInt(opacityEl.value) || <?php echo (int)$logo_opacity; ?>) : <?php echo (int)$logo_opacity; ?>;

        // Direct inline style on each img — most reliable
        document.querySelectorAll('.mini-top .logo img').forEach(function(img){
            img.style.height   = size + 'px';
            img.style.maxWidth = '100%';
            img.style.display  = 'block';
            img.style.margin   = '0 auto';
        });
        // Watermark: size slider controls width/height as % of card
        document.querySelectorAll('.mini-card .watermark img').forEach(function(img){
            img.style.width    = size + 'px';
            img.style.height   = size + 'px';
            img.style.maxWidth = '90%';
            img.style.objectFit = 'contain';
        });
        // Watermark opacity
        document.querySelectorAll('.mini-card .watermark').forEach(function(wm){
            wm.style.opacity = (opacity / 100).toFixed(2);
        });
    }
    document.addEventListener('DOMContentLoaded', updateLogoPreviewStyle);

    (function(){
        var btnUpload  = document.getElementById('btn_upload_logo');
        var btnRemove  = document.getElementById('btn_remove_logo');
        var fileInput  = document.getElementById('logo_file_input');
        var preview    = document.getElementById('logo_preview');
        var statusEl   = document.getElementById('logo_upload_status');
        var logoModeEl = document.querySelector('select[name="logo_mode"]');

        function setStatus(msg, ok){
            if(!statusEl) return;
            statusEl.textContent = msg;
            statusEl.style.color = ok ? '#81c784' : '#ef9a9a';
        }

        if(btnUpload){
            btnUpload.addEventListener('click', function(){
                if(!fileInput || !fileInput.files || !fileInput.files.length){
                    setStatus('অনুগ্রহ করে একটি ফাইল সিলেক্ট করুন।', false);
                    return;
                }
                var fd = new FormData();
                fd.append('action', 'upload');
                fd.append('logo_file', fileInput.files[0]);
                btnUpload.disabled = true;
                setStatus('আপলোড হচ্ছে…', true);
                fetch('seat_logo_ajax.php', {method:'POST', body: fd})
                    .then(function(r){ return r.json(); })
                    .then(function(data){
                        btnUpload.disabled = false;
                        setStatus(data.msg, data.ok);
                        if(data.ok && data.url){
                            if(preview){ preview.src = data.url; preview.style.display=''; }
                            if(btnRemove){ btnRemove.style.display=''; }
                            // Set logo_mode to centered and auto-submit the main form
                            if(logoModeEl && logoModeEl.value === 'none'){
                                logoModeEl.value = 'centered';
                            }
                            // Auto-submit so cards reload with logo
                            setStatus('আপলোড সফল। পেজ রিলোড হচ্ছে…', true);
                            setTimeout(function(){
                                document.querySelector('form.filter-card').submit();
                            }, 600);
                        }
                    })
                    .catch(function(e){
                        btnUpload.disabled = false;
                        setStatus('নেটওয়ার্ক এরর: '+e.message, false);
                    });
            });
        }

        if(btnRemove){
            btnRemove.addEventListener('click', function(){
                if(!confirm('লোগো সরিয়ে দেবেন?')) return;
                var fd = new FormData();
                fd.append('action', 'remove');
                fetch('seat_logo_ajax.php', {method:'POST', body: fd})
                    .then(function(r){ return r.json(); })
                    .then(function(data){
                        setStatus(data.msg, data.ok);
                        if(data.ok){
                            if(preview){ preview.src=''; preview.style.display='none'; }
                            if(btnRemove){ btnRemove.style.display='none'; }
                            if(logoModeEl){ logoModeEl.value = 'none'; }
                        }
                    });
            });
        }
    })();
    </script>
</body>
</html>