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

<?php
// ── Helper vars ────────────────────────────────────────────────────────────
$dayNames = [1=>'Senin',2=>'Selasa',3=>'Rabu',4=>'Kamis',5=>'Jumat',6=>'Sabtu'];
?>

<!-- ── 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>

        <!-- Filter tingkat -->
        <div class="btn-group btn-group-sm" role="group">
            <a href="/asc-schedule?import_id=<?= $import_id ?>"
                class="btn <?= !$grade_level ? 'btn-primary' : 'btn-outline-primary' ?>">
                Semua
            </a>
            <?php foreach ($grade_levels as $gl): ?>
            <a href="/asc-schedule?import_id=<?= $import_id ?>&grade=<?= $gl ?>"
                class="btn <?= $grade_level == $gl ? 'btn-primary' : 'btn-outline-primary' ?>">
                Kelas <?= $gl ?>
            </a>
            <?php endforeach; ?>
        </div>

    </div>

    <!-- Tombol export & navigasi -->
    <div class="d-flex gap-2 flex-wrap">
        <a href="/asc-schedule/class?import_id=<?= $import_id ?>"
            class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-person-workspace me-1"></i>Per Kelas
        </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>
        <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/excel?import_id=<?= $import_id ?><?= $grade_level ? '&grade='.$grade_level : '' ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel
                        <?= $grade_level ? "(Kelas {$grade_level})" : "(Semua)" ?>
                    </a>
                </li>
                <li>
                    <a class="dropdown-item" href="/asc-schedule/export/pdf?import_id=<?= $import_id ?><?= $grade_level ? '&grade='.$grade_level : '' ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF
                        <?= $grade_level ? "(Kelas {$grade_level})" : "(Semua)" ?>
                    </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/excel-notimes?import_id=<?= $import_id ?><?= $grade_level ? '&grade='.$grade_level : '' ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel (No Waktu)
                        <?= $grade_level ? "(Kelas {$grade_level})" : "(Semua)" ?>
                    </a>
                </li>
                <li>
                    <a class="dropdown-item" href="/asc-schedule/export/pdf-notimes?import_id=<?= $import_id ?><?= $grade_level ? '&grade='.$grade_level : '' ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF (No Waktu)
                        <?= $grade_level ? "(Kelas {$grade_level})" : "(Semua)" ?>
                    </a>
                </li>
            </ul>
        </div>
    </div>

</div>

<!-- ── SELECTOR HIGHLIGHT GURU (PILLS - LIST NAMA) ────────────────────── -->
<div class="card mb-3">
    <div class="card-body py-2 px-3">
        <div class="d-flex align-items-center gap-2 flex-wrap">
            <span class="text-muted small fw-semibold me-1">
                <i class="bi bi-person-fill me-1"></i>Sorot Guru:
            </span>
            <!-- Tombol reset / Semua -->
            <button class="btn btn-sm btn-secondary active" id="btnAll"
                onclick="highlightTeacher(null)">
                Semua
            </button>
            <!-- Pills per guru (NAMA, bukan kode) -->
            <?php foreach ($teachers as $teacher):
                $bg  = $teacher['color'];
                $fg  = getContrastColor($teacher['color']);
                // Potong nama jadi maksimal 2 kata atau 20 karakter
                $shortName = $teacher['name'];
                $nameParts = explode(' ', $shortName);
                if (count($nameParts) > 2) {
                    $shortName = $nameParts[0] . ' ' . $nameParts[1];
                }
                if (strlen($shortName) > 22) {
                    $shortName = substr($shortName, 0, 20) . '..';
                }
            ?>
            <button class="btn btn-sm teacher-pill"
                id="pill-<?= esc($teacher['short_code']) ?>"
                data-code="<?= esc($teacher['short_code']) ?>"
                data-name="<?= esc($teacher['name']) ?>"
                onclick="highlightTeacher('<?= esc($teacher['short_code']) ?>')"
                style="background-color:<?= $bg ?>;color:<?= $fg ?>;border-color:<?= $bg ?>;border-radius:20px;padding:4px 12px"
                title="<?= esc($teacher['name']) ?> (<?= esc($teacher['short_code']) ?>)">
                <?= esc($shortName) ?>
            </button>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- ── GRID JADWAL ──────────────────────────────────────────────────────── -->
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive" id="scheduleTableWrapper">
            <table class="table table-bordered table-sm mb-0" id="scheduleTable"
                style="min-width: <?= (count($classes) * 72) + 120 ?>px">
                <thead>
                    <tr class="table-dark">
                        <th class="text-center align-middle sticky-col sticky-day"
                            style="min-width:60px">Hari</th>
                        <th class="text-center align-middle sticky-col sticky-period"
                            style="min-width:60px">Jam</th>
                        <?php foreach ($classes as $class): ?>
                        <th class="text-center align-middle"
                            style="min-width:72px; font-size:.8rem">
                            <?= esc($class['name']) ?>
                        </th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($days as $dayIdx => $day):
                        $dayNum   = $day['day_number'];
                        $dayName  = $day['day_name'];
                        $pCount   = count($periods);
                    ?>
                    <?php foreach ($periods as $pIdx => $period):
                        $pNum     = $period['period_number'];
                        $isFirst  = ($pIdx === 0);
                    ?>
                    <tr class="schedule-row" data-day="<?= $dayNum ?>">

                        <!-- Kolom Hari (merge rowspan) -->
                        <?php if ($isFirst): ?>
                        <td class="text-center fw-bold align-middle sticky-col sticky-day day-cell"
                            rowspan="<?= $pCount ?>"
                            style="background:#1e3a5f;color:#fff;font-size:.8rem;
                                   writing-mode:vertical-rl;text-orientation:mixed;
                                   min-width:32px;padding:8px 4px">
                            <?= strtoupper($dayName) ?>
                        </td>
                        <?php endif; ?>

                        <!-- Kolom Jam -->
                        <td class="text-center align-middle sticky-col sticky-period"
                            style="background:#f0f4f8;font-size:.75rem;min-width:60px">
                            <div class="fw-bold"><?= $pNum ?></div>
                            <div class="text-muted" style="font-size:.65rem">
                                <?= $period['start_time'] ?>
                            </div>
                        </td>

                        <!-- Kolom per kelas -->
                        <?php foreach ($classes as $class):
                            $slot = $grid_data[$dayNum][$pNum][$class['asc_id']] ?? null;
                        ?>
                        <td class="text-center align-middle p-0 schedule-cell
                                <?= $slot ? 'has-lesson' : 'empty-cell' ?>"
                            data-teacher="<?= $slot ? esc($slot['display_teacher_code'] ?? $slot['teacher_code']) : '' ?>"
                            data-teacher-name="<?= $slot ? esc($slot['display_teacher_name'] ?? $slot['teacher_name']) : '' ?>"
                            style="<?= $slot ? "background-color:{$slot['teacher_color']}" : '' ?>;
                                   height:44px; font-size:.78rem; transition: opacity .2s, filter .2s">

                            <?php if ($slot): ?>
                            <div class="px-1 py-1 h-100 d-flex flex-column justify-content-center"
                                style="color:<?= getContrastColor($slot['teacher_color']) ?>">
                                <div class="fw-bold lh-1" style="font-size:.78rem">
                                    <?= esc($slot['display_code'] ?? $slot['subject_code']) ?>
                                </div>
                                <div class="lh-1 mt-1" style="font-size:.68rem;opacity:.85">
                                    [<?= esc($slot['display_teacher_code'] ?? $slot['teacher_code']) ?>]
                                </div>
                            </div>
                            <?php endif; ?>
                        </td>
                        <?php endforeach; ?>

                    </tr>
                    <?php endforeach; ?>

                    <!-- Garis pemisah antar hari -->
                    <?php if ($dayIdx < count($days) - 1): ?>
                    <tr class="day-separator">
                        <td colspan="<?= count($classes) + 2 ?>"
                            style="height:4px;background:#1e3a5f;padding:0;border:none"></td>
                    </tr>
                    <?php endif; ?>

                    <?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>
        <button class="btn btn-sm btn-link ms-auto p-0 text-muted"
            data-bs-toggle="collapse" data-bs-target="#legendBody">
            <i class="bi bi-chevron-down"></i>
        </button>
    </div>
    <div class="collapse show" id="legendBody">
        <div class="card-body py-2">
            <div class="row g-1">
                <?php foreach ($teachers as $teacher):
                    $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="text-truncate small" style="font-size:.78rem"
                            title="<?= esc($teacher['name']) ?>">
                            <?= esc($teacher['name']) ?>
                        </span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<style>
/* Sticky columns */
.sticky-col { position: sticky; z-index: 2; }
.sticky-day { left: 0; }
.sticky-period { left: 32px; }

/* Schedule cell transition */
.schedule-cell { transition: opacity .25s, filter .25s; }
.schedule-cell.dimmed {
    opacity: .15 !important;
    filter: grayscale(100%) !important;
}
.schedule-cell.highlighted {
    outline: 2px solid #fff;
    outline-offset: -2px;
    z-index: 1;
}

/* Empty cell */
.empty-cell { background: #fafafa !important; }
[data-bs-theme="dark"] .empty-cell { background: #1a2233 !important; }

/* Active pill style */
.teacher-pill.active {
    outline: 2px solid #fff;
    outline-offset: 1px;
    box-shadow: 0 0 0 2px #0d6efd;
}

/* Table hover */
#scheduleTable tbody tr:hover td:not(.day-cell) {
    filter: brightness(0.95);
}
</style>

<script>
// ── Highlight guru ───────────────────────────────────────────────────────
let activeTeacher = null;

function highlightTeacher(code) {
    activeTeacher = code;

    const cells   = document.querySelectorAll('.schedule-cell.has-lesson');
    const pills   = document.querySelectorAll('.teacher-pill');
    const btnAll  = document.getElementById('btnAll');

    if (!code) {
        // Reset semua
        cells.forEach(c => {
            c.classList.remove('dimmed', 'highlighted');
        });
        pills.forEach(p => p.classList.remove('active'));
        btnAll.classList.add('active');
        return;
    }

    btnAll.classList.remove('active');

    cells.forEach(cell => {
        const teacherCode = cell.dataset.teacher;
        if (teacherCode === code) {
            cell.classList.remove('dimmed');
            cell.classList.add('highlighted');
        } else {
            cell.classList.add('dimmed');
            cell.classList.remove('highlighted');
        }
    });

    // Update pill aktif
    pills.forEach(p => {
        if (p.dataset.code === code) {
            p.classList.add('active');
        } else {
            p.classList.remove('active');
        }
    });
}

// ── Ganti versi jadwal ───────────────────────────────────────────────────
function switchImport(importId) {
    const url = new URL(window.location.href);
    url.searchParams.set('import_id', importId);
    url.searchParams.delete('grade');
    window.location.href = url.toString();
}

// ── Tooltip singkat saat hover cell ─────────────────────────────────────
document.querySelectorAll('.schedule-cell.has-lesson').forEach(cell => {
    cell.style.cursor = 'pointer';
    const teacherName = cell.dataset.teacherName || '';
    const subjectCode = cell.querySelector('.fw-bold')?.textContent?.trim() || '';
    cell.title = `${subjectCode} — ${teacherName}`;
});
</script>
<?= $this->endSection() ?>

<?php
// ── PHP helper: warna kontras (hitam/putih) ────────────────────────────
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';
}
?>