<?php
require_once "auth/auth_check.php";
require_once "auth/config.php";

/* ================= FETCH DATA ================= */

$classes  = $conn->query("SELECT * FROM classes ORDER BY class_name ASC");
$subjects = $conn->query("SELECT * FROM subjects ORDER BY subject_name ASC");

/* ================= KEEP VALUES ================= */

$class_id   = $_GET['class_id'] ?? '';
$subject_id = $_GET['subject_id'] ?? '';

// Term and session are fetched from DB (set via Settings page)
$active_term_row    = $conn->query("SELECT name FROM terms    WHERE is_active = 1 LIMIT 1")->fetch_assoc();
$active_session_row = $conn->query("SELECT name FROM sessions WHERE is_active = 1 LIMIT 1")->fetch_assoc();
$term    = $active_term_row    ? $active_term_row['name']    : '';
$session = $active_session_row ? $active_session_row['name'] : '';

/* ================= LOAD QUESTIONS ================= */

$questions = [];
$class_name = "";
$subject_name = "";

if(isset($_GET['load'])){

    $stmt = $conn->prepare("
    SELECT
        q.*,
        c.class_name,
        s.subject_name,
        qi.image_name
    FROM questions q
    JOIN classes c ON q.class_id = c.id
    JOIN subjects s ON q.subject_id = s.id
    LEFT JOIN question_images qi 
        ON qi.question_id = q.id
        AND qi.id = (
            SELECT MAX(id)
            FROM question_images
            WHERE question_id = q.id
        )
    WHERE q.class_id = ?
    AND q.subject_id = ?
    AND q.term = ?
    AND q.session = ?
");

    $stmt->bind_param("iiss", $class_id, $subject_id, $term, $session);

    $stmt->execute();

    $result = $stmt->get_result();

    while($row = $result->fetch_assoc()){

        $questions[] = $row;
    }

    if(count($questions) > 0){

        $class_name   = $questions[0]['class_name'];
        $subject_name = $questions[0]['subject_name'];
    }
}

/* ================= AUTO SIZE TIER ================= */
/* Based on question count, assign a tier that drives
   font sizes on screen AND on the A4 print output.
   Tier 1 (1-5)   : very large  — few questions, big readable text
   Tier 2 (6-10)  : large       — comfortable reading size
   Tier 3 (11-15) : medium      — default balanced size
   Tier 4 (16-20) : small       — compact to fit A4
   Tier 5 (21+)   : very small  — maximum compression for A4
*/
$qCount = count($questions);
if     ($qCount <= 5)  { $sizeTier = 'tier1'; }
elseif ($qCount <= 10) { $sizeTier = 'tier2'; }
elseif ($qCount <= 15) { $sizeTier = 'tier3'; }
elseif ($qCount <= 20) { $sizeTier = 'tier4'; }
else                   { $sizeTier = 'tier5'; }
?>

<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>View Questions</title>

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

<style>

/* ================= LOAD BUTTON SPIN ================= */

@keyframes btn-spin{
    0%  { transform:rotate(0deg);   }
    100%{ transform:rotate(360deg); }
}

#load-btn.loading{
    pointer-events:none;
    opacity:.8;
    position:relative;
    color:transparent !important;
}

#load-btn.loading::after{
    content:"";
    position:absolute;
    top:50%;
    left:50%;
    width:18px;
    height:18px;
    margin:-9px 0 0 -9px;
    border:3px solid rgba(255,255,255,.35);
    border-top-color:#fff;
    border-radius:50%;
    animation:btn-spin .7s linear infinite;
}

/* ================= BASE ================= */

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{
    font-family:Arial,sans-serif;
    background:#f2f2f2;
    padding:10px;
}

/* ================= FILTER FORM ================= */

.form-box{
    background:#fff;
    max-width:900px;
    margin:auto;
    padding:20px;
    border-radius:10px;
    box-shadow:0 3px 10px rgba(0,0,0,.08);
}

.form-box h2{
    margin-bottom:15px;
    color:#333;
    text-align:center;
}

select,
button{
    width:100%;
    padding:12px;
    margin-top:10px;
    border:1px solid #ccc;
    font-size:14px;
}

button{
    background:#007bff;
    color:#fff;
    border:none;
    cursor:pointer;
    font-weight:bold;
}

button:hover{
    opacity:.9;
}

/* ================= PAPER (screen view) ================= */

.paper{
    background:#fff;
    width:99%;
    max-width:99%;
    margin:20px auto;
    padding:25px;
    position:relative;
    border:2px solid #6a1b9a;
    border-radius:15px;
    box-shadow:0 3px 12px rgba(0,0,0,.08);
}

.paper::before{
    content:"";
    position:absolute;
    top:8px;
    left:8px;
    right:8px;
    bottom:8px;
    border:1px dashed #b39ddb;
    border-radius:10px;
    pointer-events:none;
}

/* ================= HEADER ================= */

.header{
    text-align:center;
    padding-bottom:12px;
    margin-bottom:15px;
    border-bottom:3px solid #6a1b9a;
    position:relative;
}

.header img{
    width:65px;
    margin-bottom:3px;
}

.header h2{
    font-size:22px;
    color:#222;
}

.address{
    font-size:13px;
    color:#666;
    text-align:center;
}

/* FLOWER DESIGN */

.flower{
    position:absolute;
    top:10px;
    font-size:15px;
    color:purple;
}

.flower.left{
    left:10px;
}

.flower.right{
    right:10px;
}

.school-header{
    display:flex;
    align-items:center;
    justify-content:center;
    gap:15px;
    flex-wrap:wrap;
}

.school-header img{
    width:70px;
}

.school-header h2{
    margin:0;
    font-size:24px;
}

.school-header .address{
    margin-top:5px;
}

/* ================= INFO BAR ================= */

.info-bar{
    margin-top:15px;
    background:#ece8ff;
    padding:8px 10px;
    display:flex;
    flex-direction:row;
    flex-wrap:wrap;          /* wrap on mobile */
    justify-content:space-between;
    align-items:center;
    gap:6px;
    font-size:12px;
    font-weight:bold;
}

.info-bar > div{
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    flex:1 1 auto;
    min-width:0;
}

/* ================= TITLE ================= */

.title-line{
    text-align:center;
    margin-top:12px;
    margin-bottom:15px;
    font-weight:bold;
    font-size:15px;
    color:#333;
    background:#ece8ff;
    padding:6px;
    border-radius:5px;
}

/* ================= QUESTIONS ================= */

.q{
    margin-top:14px; /* 5. slightly tighter for A4 single page */
}

.question-instruction{
    background:#fff8dc;
    border-left:4px solid #ff9800;
    padding:8px 10px;
    margin-bottom:8px;
    border-radius:8px;
    /* 4. increased question/instruction font size */
    font-size:15px;
    color:#444;
    line-height:1.4;
}

/* ================= SAMPLE ANSWER ================= */

/* 4. Consistent alignment even with DB line breaks:
   - display:block + width:100% fills the box
   - word-break keeps long words from misaligning
   - padding-left anchors every line at the same indent
   No pre-wrap / pre that would mirror raw \n indentation from DB */
.sample-answer{
    background:#fafafa;
    border:2px dashed #bbb;
    border-radius:5px;
    padding:6px 10px 6px 10px;
    margin:6px 0;
    font-size:15px;
    font-weight:bold;
    line-height:1.5;
    color:#222;
    display:block;
    width:100%;
    word-break:break-word;
    /* Reset any inherited whitespace handling */
    white-space:normal;
}

/* ================= QUESTION TEXT ================= */

.question-text{
    font-weight:bold;
    color:#222;
    line-height:1.6;
    /* 4. increased question text size */
    font-size:15px;
}

/* ================= OPTIONS ================= */

.options-line{
    display:flex;
    flex-direction:row;
    flex-wrap:wrap;          /* wrap to next line on mobile if needed */
    gap:12px 20px;
    margin-top:8px;
    margin-left:15px;
    align-items:center;
}

.option-item{
    display:flex;
    flex-direction:row;
    align-items:center;
    gap:6px;
    font-size:14px;
    white-space:nowrap;
    flex-shrink:0;
}

/* OPTION BOX */

.box{
    width:14px;
    height:14px;
    border:1.5px solid #000;
    flex-shrink:0;
}

/* ================= AUTO SIZE TIERS (screen) ================= */
/* Tier 1: 1-5 questions — very large */
body.tier1 .question-text      { font-size:22px; line-height:1.8; }
body.tier1 .option-item        { font-size:20px; }
body.tier1 .sample-answer      { font-size:20px; }
body.tier1 .question-instruction{ font-size:19px; }
body.tier1 .box                { width:20px; height:20px; }
body.tier1 .q                  { margin-top:22px; }

/* Tier 2: 6-10 questions — large */
body.tier2 .question-text      { font-size:18px; line-height:1.7; }
body.tier2 .option-item        { font-size:16px; }
body.tier2 .sample-answer      { font-size:16px; }
body.tier2 .question-instruction{ font-size:15px; }
body.tier2 .box                { width:17px; height:17px; }
body.tier2 .q                  { margin-top:16px; }

/* Tier 3: 11-15 questions — medium (existing default) */
body.tier3 .question-text      { font-size:15px; line-height:1.6; }
body.tier3 .option-item        { font-size:14px; }
body.tier3 .sample-answer      { font-size:15px; }
body.tier3 .question-instruction{ font-size:15px; }
body.tier3 .box                { width:14px; height:14px; }
body.tier3 .q                  { margin-top:14px; }

/* Tier 4: 16-20 questions — small */
body.tier4 .question-text      { font-size:13px; line-height:1.5; }
body.tier4 .option-item        { font-size:12px; }
body.tier4 .sample-answer      { font-size:12px; }
body.tier4 .question-instruction{ font-size:12px; }
body.tier4 .box                { width:12px; height:12px; }
body.tier4 .q                  { margin-top:10px; }

/* Tier 5: 21+ questions — very small */
body.tier5 .question-text      { font-size:11px; line-height:1.4; }
body.tier5 .option-item        { font-size:10px; }
body.tier5 .sample-answer      { font-size:10px; }
body.tier5 .question-instruction{ font-size:10px; }
body.tier5 .box                { width:10px; height:10px; }
body.tier5 .q                  { margin-top:7px; }

/* ================= PRINT BUTTON ================= */

.print-area{
    text-align:center;
    margin:15px;
}

.print-btn{
    background:#007bff;
    color:#fff;
    padding:12px 20px;
    border:none;
    cursor:pointer;
    font-size:15px;
    font-weight:bold;
}

/* ================= QUESTION IMAGE ================= */

.question-image{
    display:block;
    width:100%;
    max-width:300px;
    margin:10px auto;
    border-radius:10px;
    border:1px solid #ddd;
    padding:4px;
    background:#fff;
}

/* ================= ESSAY ANSWER BOX ================= */

/* 3. essay box height fits content / shows 3 lines only; reduced */
.essay-answer{
    width:95%;
    margin:8px auto;
    border:1.5px dashed #999;
    border-radius:7px;
    position:relative;
    overflow:hidden;
    background:#fff;
}

.essay-watermark{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    font-size:18px;
    font-weight:bold;
    color:rgba(0,0,0,0.05);
    white-space:nowrap;
    pointer-events:none;
    user-select:none;
}

.essay-lines{
    position:relative;
    z-index:2;
    padding:8px 12px;
}

/* 3. reduced line height so essay box is compact */
.essay-line{
    border-bottom:1px solid #ddd;
    height:24px;
}

/* ================= FOOTER IDENTITY (inside paper) ================= */

.paper-footer{
    margin-top:18px;
    padding-top:10px;
    border-top:2px solid #6a1b9a;
    text-align:center;
    font-size:12px;
    color:#6a1b9a;
    letter-spacing:1px;
}

@media(max-width:768px){

    .header h2{
        font-size:18px;
    }

    /* Info bar: stack into 2-column grid on mobile */
    .info-bar{
        flex-wrap:wrap;
        gap:5px;
    }

    .info-bar > div{
        flex:1 1 45%;   /* two items per row on mobile */
        font-size:11px;
    }

    /* Options: allow wrapping on mobile so A B C D
       sit 2-per-row rather than scrolling off screen */
    .options-line{
        flex-wrap:wrap;
        gap:8px 16px;
        margin-left:8px;
    }

    .option-item{
        font-size:13px;
    }
}

/* ================= ARABIC / RTL QUESTIONS ================= */

.q.rtl{
    direction:rtl;
    text-align:right;
}

.q.rtl .question-instruction{
    direction:rtl;
    text-align:right;
}

.q.rtl .options-line{
    direction:rtl;
    justify-content:flex-end;
    margin-left:0;
    margin-right:15px;
}

.q.rtl .sample-answer{
    direction:rtl;
    text-align:right;
}

/* Arabic question: number on RIGHT, Arabic text flows left from it */
.question-arabic{
    display:flex;
    flex-direction:row-reverse;
    align-items:flex-start;
    gap:8px;
}

.arabic-num{
    flex-shrink:0;
    font-weight:bold;
    color:#222;
    direction:ltr;
    min-width:22px;
    text-align:right;
}

.arabic-body{
    flex:1;
    direction:rtl;
    text-align:right;
    display:block;
}

/* ================= PRINT ================= */

@media print{

    /* Hide ALL screen-only UI */
    .form-box,
    .print-area,
    .no-print,
    .site-header,
    .site-footer{
        display:none !important;
    }

    /* Force A4 single page */
    @page{
        size:A4 portrait;
        margin:8mm 10mm 20mm 10mm; /* bottom margin leaves room for fixed footer */
    }

    html, body{
        width:210mm;
        margin:0;
        padding:0;
        background:#fff !important;
        /* prevent browser adding its own header/footer text */
        -webkit-print-color-adjust:exact !important;
        print-color-adjust:exact !important;
    }

    /* Paper: full width, no overflow so content stays on one page */
    .paper{
        width:99% !important;
        max-width:99% !important;
        margin:0 auto !important;
        padding:5px 10px 30px 10px !important; /* bottom pad keeps content above fixed footer */

        border-left:none !important;
        border-right:none !important;
        border-bottom:none !important;
        border-top:12px solid purple !important;
        border-top-left-radius:35px !important;
        border-top-right-radius:35px !important;
        border-radius:35px 35px 0 0 !important;

        box-shadow:none !important;
        overflow:hidden !important;       /* clip anything that overflows — forces 1 page */
        page-break-after:avoid !important;
        break-after:avoid !important;
    }

    /* Inner dashed border: top only */
    .paper::before{
        border-left:none !important;
        border-right:none !important;
        border-bottom:none !important;
        border-top:1px dashed #b39ddb !important;
        left:0 !important;
        right:0 !important;
        bottom:auto !important;
        border-radius:35px 35px 0 0 !important;
    }

    /* Keep colour printing exact */
    *{
        -webkit-print-color-adjust:exact !important;
        print-color-adjust:exact !important;
    }

    .header h2{
        font-size:13pt !important;
    }

    .school-header img{
        width:50px !important;
    }

    .address{
        font-size:9pt !important;
    }

    .info-bar{
        font-size:9pt !important;
        padding:5px 8px !important;
        flex-direction:row !important;
        flex-wrap:nowrap !important;
        gap:6px !important;
        white-space:nowrap !important;
        overflow:hidden !important;
    }

    .info-bar > div{
        flex:1 1 0 !important;
        min-width:0 !important;
        white-space:nowrap !important;
        overflow:hidden !important;
        text-overflow:ellipsis !important;
        font-size:8.5pt !important;
    }

    .title-line{
        font-size:10pt !important;
        padding:4px !important;
        margin:4px 0 !important;
    }

    .question-text{
        line-height:1.4 !important;
    }

    .question-instruction{
        padding:4px 8px !important;
        margin-bottom:4px !important;
    }

    .sample-answer{
        line-height:1.4 !important;
        padding:4px 8px !important;
        margin:3px 0 !important;
        white-space:normal !important;
        word-break:break-word !important;
        display:block !important;
        width:100% !important;
        text-indent:0 !important;
    }

    .sample-answer br{
        display:block !important;
        margin:0 !important;
        padding:0 !important;
    }

    .option-item{
        white-space:nowrap !important;
    }

    .options-line{
        flex-direction:row !important;
        flex-wrap:nowrap !important;
        margin-top:4px !important;
        overflow:hidden !important;
    }

    .q{
        margin-top:6px !important;
        page-break-inside:avoid !important;
        break-inside:avoid !important;
    }

    .essay-answer{
        width:98% !important;
        margin:4px auto !important;
    }

    .essay-line{
        height:16px !important;
    }

    .essay-lines{
        padding:3px 10px !important;
    }

    .question-image{
        max-width:200px !important;
        margin:5px auto !important;
    }

    /* ===== FOOTER PINNED TO BOTTOM OF PRINT PAGE ===== */
    .paper-footer{
        position:fixed !important;
        bottom:0 !important;
        left:0 !important;
        right:0 !important;
        width:100% !important;
        margin:0 !important;
        padding:5px 10px !important;
        border-top:1.5px solid purple !important;
        font-size:8pt !important;
        color:purple !important;
        text-align:center !important;
        letter-spacing:1px !important;
        background:#fff !important;
    }

    /* ===== PRINT SIZE TIERS ===== */

    /* Tier 1: 1-5 questions — very large print */
    body.tier1 .question-text       { font-size:18pt !important; line-height:1.8 !important; }
    body.tier1 .option-item         { font-size:16pt !important; }
    body.tier1 .sample-answer       { font-size:16pt !important; }
    body.tier1 .question-instruction{ font-size:15pt !important; }
    body.tier1 .box                 { width:22px !important; height:22px !important; }
    body.tier1 .q                   { margin-top:20px !important; }
    body.tier1 .options-line        { gap:25px !important; }

    /* Tier 2: 6-10 questions — large print */
    body.tier2 .question-text       { font-size:11pt !important; line-height:1.5 !important; }
    body.tier2 .option-item         { font-size:10pt !important; }
    body.tier2 .sample-answer       { font-size:10pt !important; }
    body.tier2 .question-instruction{ font-size:9.5pt !important; }
    body.tier2 .box                 { width:14px !important; height:14px !important; }
    body.tier2 .q                   { margin-top:7px !important; }
    body.tier2 .options-line        { gap:16px !important; }

    /* Tier 3: 11-15 questions — medium print */
    body.tier3 .question-text       { font-size:10pt !important; line-height:1.4 !important; }
    body.tier3 .option-item         { font-size:9.5pt !important; }
    body.tier3 .sample-answer       { font-size:10pt !important; }
    body.tier3 .question-instruction{ font-size:9pt !important; }
    body.tier3 .box                 { width:13px !important; height:13px !important; }
    body.tier3 .q                   { margin-top:6px !important; }
    body.tier3 .options-line        { gap:12px !important; }

    /* Tier 4: 16-20 questions — small print */
    body.tier4 .question-text       { font-size:8pt !important; line-height:1.3 !important; }
    body.tier4 .option-item         { font-size:7.5pt !important; }
    body.tier4 .sample-answer       { font-size:8pt !important; }
    body.tier4 .question-instruction{ font-size:7.5pt !important; }
    body.tier4 .box                 { width:10px !important; height:10px !important; }
    body.tier4 .q                   { margin-top:4px !important; }
    body.tier4 .options-line        { gap:10px !important; }
    body.tier4 .essay-line          { height:13px !important; }

    /* Tier 5: 21+ questions — very small print */
    body.tier5 .question-text       { font-size:7pt !important; line-height:1.3 !important; }
    body.tier5 .option-item         { font-size:6.5pt !important; }
    body.tier5 .sample-answer       { font-size:7pt !important; }
    body.tier5 .question-instruction{ font-size:6.5pt !important; }
    body.tier5 .box                 { width:9px !important; height:9px !important; }
    body.tier5 .q                   { margin-top:4px !important; }
    body.tier5 .options-line        { gap:8px !important; }
    body.tier5 .essay-line          { height:12px !important; }
}

</style>

</head>

<body class="<?= isset($sizeTier) ? htmlspecialchars($sizeTier) : 'tier3' ?>">

<div class="no-print">
<?php include 'header.php'; ?>
</div>

<div style="height:18px;"></div>

<div class="form-box">

<h2>Load Examination Questions</h2>

<form method="GET">

<!-- CLASS -->

<select name="class_id" required>

<option value="">Select Class</option>

<?php while($c = $classes->fetch_assoc()): ?>

<option 
value="<?= $c['id'] ?>"
<?= ($class_id == $c['id']) ? 'selected' : '' ?>
>

<?= htmlspecialchars($c['class_name']) ?>

</option>

<?php endwhile; ?>

</select>

<!-- SUBJECT -->

<select name="subject_id" required>

<option value="">Select Subject</option>

<?php while($s = $subjects->fetch_assoc()): ?>

<option 
value="<?= $s['id'] ?>"
<?= ($subject_id == $s['id']) ? 'selected' : '' ?>
>

<?= htmlspecialchars($s['subject_name']) ?>

</option>

<?php endwhile; ?>

</select>

<!-- TERM & SESSION (auto from DB) -->

<?php if($term && $session): ?>
<div style="background:#ece8ff;border-left:4px solid #6a1b9a;border-radius:6px;padding:9px 14px;margin-top:10px;font-size:13px;color:#333;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
    📅 <strong>Term:</strong> <?= htmlspecialchars($term) ?> &nbsp;&bull;&nbsp; 🗓️ <strong>Session:</strong> <?= htmlspecialchars($session) ?>
</div>
<?php else: ?>
<div style="background:#fff3cd;border-left:4px solid #d97706;border-radius:6px;padding:9px 14px;margin-top:10px;font-size:13px;color:#92400e;">
    ⚠️ No active term or session set. Please update in Settings.
</div>
<?php endif; ?>

<button type="submit" name="load" id="load-btn"
    onclick="if(this.form.checkValidity()){ this.classList.add('loading'); setTimeout(function(){ var el=document.getElementById('questions-anchor'); if(el){ el.scrollIntoView({behavior:'smooth'}); } },500); }"
    <?= (!$term || !$session) ? 'disabled style="opacity:.5;cursor:not-allowed;"' : '' ?>
>
Load Questions
</button>

</form>

</div>

<?php if(count($questions) > 0): ?>

<div id="questions-anchor"></div>

<!-- PRINT BUTTON -->

<div class="print-area">

<button class="print-btn" onclick="if(typeof _printTitle!=='undefined'){document.title=_printTitle;} window.print();">
Print Exam Paper
</button>

</div>

<!-- ================= PAPER ================= -->

<div class="paper">

<!-- HEADER -->

<div class="header">

<div class="flower left">❀ ❀ ❀</div>

<div class="flower right">❀ ❀ ❀</div>

<div class="school-header">

    <img src="logo.png" alt="School Logo">

    <div>

        <h2>ALBAYAN ACADEMY NURSERY & PRIMARY SCHOOL SHENDAM</h2>

        <p class="address">
            Tudun Wada Shendam, Plateau State, Nigeria.
        </p>

    </div>

</div>

</div>

<!-- INFO BAR -->

<div class="info-bar">

<div>Class: <?= htmlspecialchars($class_name) ?></div>

<div>Subject: <?= htmlspecialchars($subject_name) ?></div>

<div>Term: <?= htmlspecialchars($term) ?></div>

<div>Session: <?= htmlspecialchars($session) ?></div>

<div>Adm No: ________________</div>

</div>

<!-- TITLE -->

<div class="title-line">

EXAMINATION QUESTIONS

</div>

<!-- QUESTIONS -->

<?php $i=1; foreach($questions as $q): ?>

<?php
// Detect Arabic: if question text contains Arabic Unicode block characters
$isArabic = preg_match('/[\x{0600}-\x{06FF}]/u', $q['question']);
?>

<div class="q<?= $isArabic ? ' rtl' : '' ?>">

    <!-- QUESTION INSTRUCTION -->

    <?php if(!empty($q['instruction'])): ?>

    <div class="question-instruction">

        <strong>Instruction:</strong>
        <?= nl2br(htmlspecialchars($q['instruction'])) ?>

    </div>

    <?php endif; ?>

    <!-- QUESTION TEXT -->

    <?php if($isArabic): ?>
    <div class="question-text question-arabic">
        <span class="arabic-body"><?= nl2br(htmlspecialchars($q['question'])) ?></span>
        <span class="arabic-num"><?= $i ?>.</span>
    </div>
    <?php else: ?>
    <div class="question-text">
        <?= $i ?>. <?= nl2br(htmlspecialchars($q['question'])) ?>
    </div>
    <?php endif; ?>

    <!-- QUESTION IMAGE -->

    <?php if(!empty($q['image_name'])): ?>

    <img
        src="uploads/questions/<?= htmlspecialchars($q['image_name']) ?>"
        class="question-image"
        alt="Question Image">

    <?php endif; ?>

    <?php
    /* Question is objective if ANY of the 4 option columns has data.
       Each option is then shown/hidden individually based on its own value. */
    $isObjective =
        !empty($q['option_a']) ||
        !empty($q['option_b']) ||
        !empty($q['option_c']) ||
        !empty($q['option_d']);
    ?>

    <!-- OBJECTIVE QUESTION -->

    <?php if($isObjective):
        $lA = $isArabic ? 'أ' : 'A';
        $lB = $isArabic ? 'ب' : 'B';
        $lC = $isArabic ? 'ج' : 'C';
        $lD = $isArabic ? 'د' : 'D';
    ?>

    <div class="options-line">

        <?php if(!empty($q['option_a'])): ?>
        <div class="option-item">
            <span class="box"></span>
            <?= $lA ?>. <?= htmlspecialchars($q['option_a']) ?>
        </div>
        <?php endif; ?>

        <?php if(!empty($q['option_b'])): ?>
        <div class="option-item">
            <span class="box"></span>
            <?= $lB ?>. <?= htmlspecialchars($q['option_b']) ?>
        </div>
        <?php endif; ?>

        <?php if(!empty($q['option_c'])): ?>
        <div class="option-item">
            <span class="box"></span>
            <?= $lC ?>. <?= htmlspecialchars($q['option_c']) ?>
        </div>
        <?php endif; ?>

        <?php if(!empty($q['option_d'])): ?>
        <div class="option-item">
            <span class="box"></span>
            <?= $lD ?>. <?= htmlspecialchars($q['option_d']) ?>
        </div>
        <?php endif; ?>

    </div>

    <!-- ESSAY QUESTION -->

    <?php else: ?>

    <div class="essay-answer">

        <div class="essay-watermark">
           Essay answer space, write here
        </div>

        <?php if(!empty($q['sample_answer'])): ?>

        <!-- 4. Trim each line from DB before nl2br to ensure consistent left-alignment
                regardless of how the text was typed/saved (spaces, tabs, \r\n etc.) -->
        <div class="sample-answer"><?php
            $lines = explode("\n", str_replace("\r\n", "\n", str_replace("\r", "\n", $q['sample_answer'])));
            $trimmed = array_map('trim', $lines);
            echo nl2br(htmlspecialchars(implode("\n", $trimmed)));
        ?></div>

        <?php else: ?>

        <!-- 3. Only 3 compact lines when no sample answer -->
        <div class="essay-lines">

            <?php for($x=1; $x<=3; $x++): ?>

            <div class="essay-line"></div>

            <?php endfor; ?>

        </div>

        <?php endif; ?>

    </div>

    <?php endif; ?>

</div>

<?php $i++; ?>

<?php endforeach; ?>

<!-- FOOTER IDENTITY -->
<div class="paper-footer">
    &#9733; Printed by <strong>Albayan Academy Nur &amp; Pri School ICT Center</strong> &mdash; Shendam &#9733;
</div>

</div> <!-- end paper -->
<?php endif; ?>

<div style="height:18px;"></div>

<div class="no-print">
<?php include 'footer.php'; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
<?php if(isset($_GET['load'])): ?>

<?php if(count($questions) > 0):
    // First 3 alphabetic characters of subject name (uppercase)
    preg_match_all('/[A-Za-z]/', $subject_name, $letters);
    $subjectShort = strtoupper(implode('', array_slice($letters[0], 0, 3)));
    $printTitle   = $subjectShort . ' - ' . $class_name . ' - ' . $session;
?>
var _printTitle = <?= json_encode($printTitle) ?>;
var _origTitle  = document.title;

// Swap title in before print so browser uses it as the save filename
window.addEventListener('beforeprint', function(){ document.title = _printTitle; });
window.addEventListener('afterprint',  function(){ document.title = _origTitle;  });

Swal.fire({
    icon: 'success',
    title: 'Questions Available',
    text: '<?= count($questions) ?> question(s) found for the selected class and subject.',
    confirmButtonColor: '#6a1b9a',
    timer: 3000,
    timerProgressBar: true,
    showConfirmButton: true,
    confirmButtonText: 'OK'
});
<?php else: ?>
Swal.fire({
    icon: 'warning',
    title: 'No Questions Found',
    text: 'No questions available for the selected class and subject.',
    confirmButtonColor: '#6a1b9a',
    confirmButtonText: 'OK'
});
<?php endif; ?>

<?php endif; ?>
</script>

</body>
</html>
