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

<?= $this->section('email_content') ?>
<?php
// ---------------------------
// Normalization & helpers
// ---------------------------
$year    = $schoolYear ?? date('Y');
$btnUrl  = !empty($portalLink) ? $portalLink : base_url('/login');

// Normalize $students into a clean array of details if present
$studentsArr = [];
if (!empty($students) && is_array($students)) {
    foreach ($students as $st) {
        $studentsArr[] = [
            'name'        => trim((string)($st['name'] ?? '')),
            'studentId'   => trim((string)($st['studentId'] ?? '')),
            'gradeLevel'  => trim((string)($st['gradeLevel'] ?? '')),
            'teacherName' => trim((string)($st['teacherName'] ?? '')),
            'startDate'   => trim((string)($st['startDate'] ?? '')),
        ];
    }
    // Remove empties by name
    $studentsArr = array_values(array_filter($studentsArr, fn($r) => $r['name'] !== ''));
}

// If $studentName is given, it can be string or array
// Use it only when we don't have a useful $students array
$singleFromNameField = null;
if (empty($studentsArr)) {
    if (is_array($studentName ?? null)) {
        $singleFromNameField = trim((string)($studentName[0] ?? ''));
    } else {
        $singleFromNameField = trim((string)($studentName ?? ''));
    }
}

// If students array has exactly one entry, treat as single
$isMulti = count($studentsArr) > 1;

// Date formatter
$fmtDate = function ($d) {
    if (!$d) return null;
    $ts = strtotime($d);
    if ($ts) {
        try {
            $dt = (new DateTime('@' . $ts)); // UTC epoch-based
            return local_date($dt, 'm-d-Y');
        } catch (Throwable $e) {
            // fall back to raw string if conversion fails
        }
    }
    return $d;
};

// Build single-student detail fallbacks (from controller or first student)
$singleDetails = [
    'name'        => $singleFromNameField ?: trim((string)($studentsArr[0]['name']        ?? '')),
    'studentId'   => trim((string)($studentId   ?? ($studentsArr[0]['studentId']   ?? ''))),
    'gradeLevel'  => trim((string)($gradeLevel  ?? ($studentsArr[0]['gradeLevel']  ?? ''))),
    'teacherName' => trim((string)($teacherName ?? ($studentsArr[0]['teacherName'] ?? ''))),
    'startDate'   => trim((string)($startDate   ?? ($studentsArr[0]['startDate']   ?? ''))),
];
?>
<div style="font-size:18px; line-height:1.6;">
    <h2>Enrollment Confirmed</h2>

    <p>Dear <?= esc($parentName ?? 'Parent') ?>,</p>

    <?php if ($isMulti): ?>
        <p>We are pleased to inform you that the following <?= count($studentsArr) ?> students are now officially enrolled for the <?= esc($year) ?> school year:</p>

        <ul style="margin: 0 0 16px 20px;">
            <?php foreach ($studentsArr as $st): ?>
                <?php
                $bits = array_filter([
                    $st['gradeLevel']  ? 'Grade: ' . esc($st['gradeLevel']) : null,
                    $st['teacherName'] ? 'Teacher: ' . esc($st['teacherName']) : null,
                    $fmtDate($st['startDate']) ? 'Start: ' . esc($fmtDate($st['startDate'])) : null,
                ]);
                ?>
                <li>
                    <strong><?= esc($st['name']) ?></strong>
                    <?php if ($bits): ?>
                        <span style="color:#6c757d"> (<?= implode(' • ', $bits) ?>)</span>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>

    <?php else: ?>
        <p>
            We are pleased to inform you that
            <strong><?= esc($singleDetails['name'] ?: 'your student') ?></strong>
            is now officially enrolled for the <?= esc($year) ?> school year.
        </p>

        <?php
        $singleBits = array_filter([
            $singleDetails['gradeLevel']  ? 'Grade: ' . esc($singleDetails['gradeLevel']) : null,
            $singleDetails['teacherName'] ? 'Teacher: ' . esc($singleDetails['teacherName']) : null,
            $fmtDate($singleDetails['startDate']) ? 'Start: ' . esc($fmtDate($singleDetails['startDate'])) : null,
        ]);
        ?>
        <?php if ($singleBits): ?>
            <!--p style="margin-top: -6px; color:#6c757d;"><? //= implode(' • ', $singleBits) 
                                                            ?></p-->
        <?php endif; ?>
    <?php endif; ?>

    <p style="margin:16px 0;">
        <a href="<?= esc($btnUrl) ?>" target="_blank" rel="noopener"
            style="display:inline-block; padding:12px 18px; text-decoration:none; border-radius:6px;
                background:#198754; color:#ffffff; font-weight:600; font-size:18px;">
            Access My Account
        </a>
    </p>

    <p>Welcome to our school community!</p>
    <p>Best regards,<br>Admissions Team</p>
</div>


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