<?= $this->extend('layout/email_layout') ?>
<?= $this->section('content') ?>

<?php
/**
 * Expected:
 * - $parent: ['firstname','lastname']
 * - $items:  array of [
 *      'class_section_name' => string,
 *      'invite_link'        => string,
 *      'qr_src'             => string (data-URI or public URL)
 *   ]
 * Optional legacy:
 * - $sections, $links, $qrImageUrl
 * Optional:
 * - $teacherNames (array)
 * - $title
 */
$displayName   = trim(($parent['firstname'] ?? '') . ' ' . ($parent['lastname'] ?? ''));
$items         = $items ?? [];
$teacherNames  = $teacherNames ?? [];
$sections      = $sections ?? [];
$links         = $links ?? [];
$sectionNames  = array_map(fn($s) => $s['class_section_name'] ?? '', $sections);
$linkFallback  = $links[0] ?? ($sections[0]['invite_link'] ?? '#');
$introSections = !empty($items)
    ? array_map(fn($i) => $i['class_section_name'] ?? 'Class', $items)
    : $sectionNames;

/**
 * Closures instead of named functions (avoids redeclare):
 * - $formatSectionName: normalizes labels to "Grade X[-Y]" except KG/Youth or already "Grade ..."
 * - $joinWithAnd: joins items with "and" (no Oxford comma)
 */
$formatSectionName = function (string $section): string {
    $raw = trim($section);
    if ($raw === '') return 'Class';

    // If already starts with "Grade", keep it (normalize spacing/casing lightly)
    if (preg_match('/^\s*grade\s+/i', $raw)) {
        // Capitalize "Grade" word only
        return 'Grade ' . trim(preg_replace('/^\s*grade\s+/i', '', $raw));
    }

    // Normalize special groups
    $up = strtoupper($raw);
    if ($up === 'KG')    return 'KG';
    if ($up === 'YOUTH') return 'Youth';

    // Common forms: "2-A", "5-B", "6", "3 a" -> make "Grade 3-A" or "Grade 6"
    // Keep hyphen part as uppercase if present.
    if (preg_match('/^\s*(\d{1,2})(?:\s*-\s*([A-Za-z]))?\s*$/', $raw, $m)) {
        $grade = (int)$m[1];
        $sec   = isset($m[2]) ? strtoupper($m[2]) : '';
        return 'Grade ' . $grade . ($sec ? '-' . $sec : '');
    }

    // Fallback: Title-case but prefix as Grade
    return 'Grade ' . ucfirst($raw);
};

$joinWithAnd = function (array $arr): string {
    $arr = array_values(array_filter($arr, fn($v) => $v !== null && $v !== ''));
    $n = count($arr);
    if ($n === 0) return '';
    if ($n === 1) return $arr[0];
    if ($n === 2) return $arr[0] . ' and ' . $arr[1];
    return implode(', ', array_slice($arr, 0, -1)) . ' and ' . $arr[$n - 1];
};
?>

<div style="background-color:#fff;border-radius:8px;padding:30px;max-width:720px;margin:auto;
            box-shadow:0 2px 8px rgba(0,0,0,0.12);font-family:'Segoe UI',Arial,sans-serif;color:#333;line-height:1.8;">
    <p style="font-size:18px;">Assalamu Alaikum <?= esc($displayName) ?>,</p>

    <p style="font-size:18px;">
        We are excited to welcome you to this school year at
        <strong>Al Rahma Sunday School</strong>. As we approach our fourth week of learning,
        we ask Allah (SWT) to make this year successful and beneficial for all our children.
    </p>

    <?php
    // Prepare section display for intro using closure
    $formattedSections = array_map($formatSectionName, $introSections);
    $sectionList = $joinWithAnd(array_filter($formattedSections));
    ?>

    <p style="font-size:18px;">
        You have been identified as a parent or guardian of at least one child in
        <strong><?= esc($sectionList ?: 'your class') ?></strong> this year.
        We are inviting you to join the WhatsApp group(s) that include other parents and your child’s instructors.
        The WhatsApp group(s) will be used to share important information about curriculum assignments and school events.
    </p>

    <p style="font-size:18px;">
        Additionally, by joining these groups, you automatically become part of the
        <strong>Al Rahma Sunday School Community</strong>, which hosts all grade groups within the school.
        Through this community, you will receive important alerts and messages from the school administration.
    </p>

    <h2 style="font-size:22px;color:#1c5f2c;font-weight:600;margin-top:22px;">
        Your WhatsApp Group(s)<?= !empty($items) ? ' (' . count($items) . ')' : '' ?>
    </h2>

    <?php if (!empty($items)): ?>
        <?php foreach ($items as $i => $it):
            $sectionLabel = $formatSectionName($it['class_section_name'] ?? 'Class');
            $inviteLink   = (string)($it['invite_link'] ?? '#');
            $qrSrc        = (string)($it['qr_src'] ?? '');
        ?>
            <div style="border:1px solid #e8e8e8;border-radius:10px;padding:16px;margin:16px 0;background:#fff;">
                <div style="font-weight:700;margin-bottom:10px;font-size:22px;">
                    <?= $i + 1 ?>) <?= esc($sectionLabel) ?>
                </div>

                <div style="text-align:center; margin-top:10px; margin-bottom:20px;">
                    <a href="<?= esc($inviteLink) ?>" target="_blank" rel="noopener"
                       style="display:inline-block; background-color:#25D366; color:#fff; padding:14px 28px; border-radius:8px; text-decoration:none; font-weight:600; font-size:20px;">
                        Join WhatsApp Group
                    </a>
                    <div style="margin-top:15px;">
                        <?php if ($qrSrc !== ''): ?>
                            <img src="<?= esc($qrSrc) ?>"
                                 alt="QR for <?= esc($sectionLabel) ?>"
                                 width="260" height="260"
                                 style="display:block; margin:auto;">
                        <?php else: ?>
                            <div style="color:#777; font-size:20px;"><em>QR unavailable</em></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <!-- Legacy single-class fallback -->
        <?php
        $fallbackFormatted = array_map($formatSectionName, $sectionNames);
        $fallbackLabel     = $joinWithAnd(array_filter($fallbackFormatted)) ?: 'Class';
        ?>
        <div style="border:1px solid #e8e8e8;border-radius:10px;padding:16px;margin:16px 0;background:#fff;">
            <div style="font-weight:700;margin-bottom:10px;font-size:22px;">
                <?= esc($fallbackLabel) ?>
            </div>
            <div style="display:flex;flex-wrap:wrap;align-items:center;gap:16px;">
                <div style="flex:1 1 280px;min-width:260px;">
                    <a href="<?= esc($linkFallback) ?>" target="_blank" rel="noopener"
                       style="display:inline-block;background-color:#25D366;color:#fff;padding:14px 24px;
                              border-radius:8px;text-decoration:none;font-weight:600;font-size:20px;">
                        Join WhatsApp Group
                    </a>
                    <div style="margin-top:10px;">
                        <a href="<?= esc($linkFallback) ?>" target="_blank" rel="noopener"
                           style="font-size:18px;color:#0b6ef6;word-break:break-all;">
                            <?= esc($linkFallback) ?>
                        </a>
                    </div>
                </div>
                <div style="flex:0 0 260px;text-align:center;">
                    <?php if (!empty($qrImageUrl)): ?>
                        <img src="<?= esc($qrImageUrl) ?>" alt="WhatsApp QR Code"
                             width="260" height="260" style="display:block;margin:auto;">
                    <?php else: ?>
                        <div style="color:#777;font-size:20px;"><em>QR unavailable</em></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <p style="margin-top:22px;font-size:18px;color:#555;text-align:center;">
        Jazakum Allah Khair,<br>
        <strong>Al Rahma Sunday School Administration</strong>
    </p>
</div>

<?= $this->endSection() ?>
