<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<!-- ── TOOLBAR ──────────────────────────────────────────────────────────── -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">

    <div class="d-flex align-items-center gap-2 flex-wrap">
        <!-- Pilih versi jadwal -->
        <div class="input-group input-group-sm" style="width:auto">
            <span class="input-group-text bg-white">
                <i class="bi bi-calendar3 text-primary"></i>
            </span>
            <select class="form-select form-select-sm" id="selectImport"
                onchange="switchImport(this.value)" style="min-width:200px">
                <?php foreach ($imports as $imp): ?>
                <option value="<?= $imp['id'] ?>"
                    <?= $imp['id'] == $import_id ? 'selected' : '' ?>>
                    <?= esc($imp['name']) ?><?= $imp['is_active'] ? ' ✓' : '' ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Pilih kelas -->
        <div class="input-group input-group-sm" style="width:auto">
            <span class="input-group-text bg-white">
                <i class="bi bi-door-open text-success"></i>
            </span>
            <select class="form-select form-select-sm" id="selectClass"
                onchange="switchClass(this.value)" style="min-width:130px">
                <?php
                $lastGrade = null;
                foreach ($classes as $c):
                    if ($c['grade_level'] !== $lastGrade):
                        if ($lastGrade !== null) echo '</optgroup>';
                        echo '<optgroup label="Kelas ' . $c['grade_level'] . '">';
                        $lastGrade = $c['grade_level'];
                    endif;
                ?>
                <option value="<?= esc($c['asc_id']) ?>"
                    <?= $c['asc_id'] === $class_asc_id ? 'selected' : '' ?>>
                    <?= esc($c['name']) ?>
                </option>
                <?php endforeach; ?>
                <?php if ($lastGrade !== null) echo '</optgroup>'; ?>
            </select>
        </div>
    </div>

    <!-- Navigasi & Export -->
    <div class="d-flex gap-2 flex-wrap">
        <a href="/asc-schedule?import_id=<?= $import_id ?>"
            class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-grid me-1"></i>Keseluruhan
        </a>
        <a href="/asc-schedule/teacher?import_id=<?= $import_id ?>"
            class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-person-badge me-1"></i>Per Guru
        </a>
        <?php if ($class_asc_id): ?>
        <div class="dropdown">
            <button class="btn btn-sm btn-success dropdown-toggle" data-bs-toggle="dropdown">
                <i class="bi bi-download me-1"></i>Export
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><h6 class="dropdown-header text-muted" style="font-size:10px">DENGAN WAKTU</h6></li>
                <li>
                    <a class="dropdown-item"
                        href="/asc-schedule/export/class/excel?import_id=<?= $import_id ?>&class_id=<?= urlencode($class_asc_id) ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel — Kelas Ini
                    </a>
                </li>
                <li>
                    <a class="dropdown-item"
                        href="/asc-schedule/export/class/pdf?import_id=<?= $import_id ?>&class_id=<?= urlencode($class_asc_id) ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Kelas Ini
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item"
                        href="/asc-schedule/export/class/pdf-all?import_id=<?= $import_id ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Semua Kelas
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li><h6 class="dropdown-header text-muted" style="font-size:10px">TANPA WAKTU</h6></li>
                <li>
                    <a class="dropdown-item"
                        href="/asc-schedule/export/class/excel-notimes?import_id=<?= $import_id ?>&class_id=<?= urlencode($class_asc_id) ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel — Kelas Ini (No Waktu)
                    </a>
                </li>
                <li>
                    <a class="dropdown-item"
                        href="/asc-schedule/export/class/pdf-notimes?import_id=<?= $import_id ?>&class_id=<?= urlencode($class_asc_id) ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Kelas Ini (No Waktu)
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item"
                        href="/asc-schedule/export/class/pdf-all-notimes?import_id=<?= $import_id ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Semua Kelas (No Waktu)
                    </a>
                </li>
            </ul>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── INFO KELAS ─────────────────────────────────────────────────────── -->
<?php if ($selected_class): ?>
<div class="d-flex align-items-center gap-3 mb-3 p-3 bg-white rounded border">
    <div class="rounded d-flex align-items-center justify-content-center"
        style="width:48px;height:48px;background:#1e3a5f">
        <i class="bi bi-door-open text-white fs-4"></i>
    </div>
    <div>
        <div class="fw-bold fs-5">Kelas <?= esc($selected_class['name']) ?></div>
        <div class="text-muted small">
            Tingkat <?= $selected_class['grade_level'] ?> &nbsp;·&nbsp;
            <?= esc($import['name']) ?> &nbsp;·&nbsp;
            <?= $import['academic_year'] ?> — <?= $import['semester'] ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ── GRID MATRIX JADWAL KELAS (TRANSPOSE: JAM SEBAGAI BARIS, HARI SEBAGAI KOLOM) ── -->
<?php if (!empty($schedule_data)): ?>
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-bordered mb-0 schedule-matrix" id="classGrid">
                <thead>
                    <tr>
                        <th class="text-center align-middle header-period-col">Jam</th>
                        <?php foreach ($days as $day): ?>
                        <th class="text-center align-middle header-day">
                            <?= strtoupper(substr($day['day_name'], 0, 3)) ?>
                            <div class="day-full small fw-normal"><?= $day['day_name'] ?></div>
                        </th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($periods as $period):
                        $pNum = $period['period_number'];
                    ?>
                    <tr>
                        <!-- Kolom Jam -->
                        <td class="text-center align-middle period-label">
                            <div class="period-num"><?= $pNum ?></div>
                            <div class="period-time"><?= substr($period['start_time'],0,5) ?>–<?= substr($period['end_time'],0,5) ?></div>
                        </td>

                        <!-- Kolom per Hari -->
                        <?php foreach ($days as $day):
                            $dayNum = $day['day_number'];
                            $slot = $schedule_data[$dayNum][$pNum] ?? null;
                            $bg   = $slot ? $slot['teacher_color'] : '';
                            $fg   = $slot ? getContrastColor($slot['teacher_color']) : '';
                        ?>
                        <td class="text-center align-middle schedule-cell <?= $slot ? 'has-slot' : 'empty-slot' ?>"
                            <?php if ($slot): ?>
                            style="background:<?= $bg ?>;color:<?= $fg ?>"
                            title="<?= esc($slot['display_name'] ?? $slot['subject_name']) ?> — <?= esc($slot['display_teacher_name'] ?? $slot['teacher_name']) ?>"
                            <?php endif; ?>>
                            <?php if ($slot): ?>
                            <div class="slot-subject"><?= esc($slot['display_code'] ?? $slot['subject_code']) ?></div>
                            <div class="slot-teacher">[<?= esc($slot['display_teacher_code'] ?? $slot['teacher_code']) ?>]</div>
                            <?php endif; ?>
                        </td>
                        <?php endforeach; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Legenda guru -->
<div class="card mt-3">
    <div class="card-header py-2 d-flex align-items-center gap-2">
        <i class="bi bi-info-circle text-primary"></i>
        <span class="fw-semibold small">Keterangan Kode Guru</span>
    </div>
    <div class="card-body py-2">
        <div class="row g-1">
            <?php
            $usedTeachers = [];
            foreach ($schedule_data as $daySlots) {
                foreach ($daySlots as $slot) {
                    $usedTeachers[$slot['display_teacher_code'] ?? $slot['teacher_code']] = $slot;
                }
            }
            ksort($usedTeachers);
            foreach ($teachers as $teacher):
                if (!isset($usedTeachers[$teacher['short_code']])) continue;
                $bg = $teacher['color'];
                $fg = getContrastColor($teacher['color']);
            ?>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="d-flex align-items-center gap-2 py-1">
                    <span class="badge px-2 py-1 flex-shrink-0"
                        style="background:<?= $bg ?>;color:<?= $fg ?>;min-width:36px;font-size:.75rem">
                        <?= esc($teacher['short_code']) ?>
                    </span>
                    <span class="small text-truncate" style="font-size:.78rem"
                        title="<?= esc($teacher['name']) ?>">
                        <?= esc($teacher['name']) ?>
                    </span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php elseif ($class_asc_id): ?>
<div class="alert alert-warning">
    <i class="bi bi-exclamation-triangle me-2"></i>Tidak ada data jadwal untuk kelas ini.
</div>
<?php else: ?>
<div class="alert alert-info">
    <i class="bi bi-arrow-up-circle me-2"></i>Pilih kelas untuk melihat jadwal.
</div>
<?php endif; ?>

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

<?= $this->section('scripts') ?>
<style>
.schedule-matrix {
    table-layout: fixed;
    border-collapse: collapse;
}
.header-period-col {
    background: #1e3a5f;
    color: #fff;
    font-size: .75rem;
    padding: 6px 4px;
    min-width: 80px;
}
.header-day {
    background: #1e3a5f;
    color: #fff;
    padding: 5px 4px;
    min-width: 85px;
    font-size: .8rem;
}
.day-full {
    font-size: .65rem;
    opacity: .8;
    font-weight: normal;
}
.period-label {
    background: #f0f4f8;
    padding: 6px 4px;
}
.period-num {
    font-size: .9rem;
    font-weight: 700;
    line-height: 1.2;
}
.period-time {
    font-size: .65rem;
    color: #666;
    line-height: 1.2;
}
.schedule-cell {
    height: 65px;
    padding: 4px;
    transition: filter .15s;
}
.schedule-cell.has-slot:hover {
    filter: brightness(.88);
    cursor: default;
}
.empty-slot {
    background: #fafafa !important;
}
.slot-subject {
    font-size: .82rem;
    font-weight: 700;
    line-height: 1.2;
}
.slot-teacher {
    font-size: .7rem;
    line-height: 1.2;
    margin-top: 2px;
    opacity: .85;
}
</style>
<script>
function switchImport(importId) {
    window.location.href = `/asc-schedule/class?import_id=${importId}`;
}
function switchClass(classId) {
    const importId = document.getElementById('selectImport').value;
    window.location.href = `/asc-schedule/class?import_id=${importId}&class_id=${classId}`;
}
</script>
<?= $this->endSection() ?>

<?php
function getContrastColor($hex) {
    $hex = ltrim($hex, '#');
    if (strlen($hex) !== 6) return '#000000';
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    $luminance = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
    return $luminance > 0.5 ? '#000000' : '#ffffff';
}
?>