<?php
if (!function_exists('getContrastColor')) {
    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';
    }
}
?>
<?= $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="selectSchedule"
                onchange="switchSchedule(this.value)" style="min-width:200px">
                <?php foreach ($schedules as $s): ?>
                <option value="<?= $s['id'] ?>"
                    <?= $s['id'] == $schedule['id'] ? 'selected' : '' ?>>
                    <?= esc($s['name']) ?><?= $s['status'] === 'published' ? ' (Aktif)' : '' ?>
                </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_name'] !== $lastGrade):
                        if ($lastGrade !== null) echo '</optgroup>';
                        echo '<optgroup label="Kelas ' . esc($c['grade_name']) . '">';
                        $lastGrade = $c['grade_name'];
                    endif;
                ?>
                <option value="<?= esc($c['id']) ?>"
                    <?= $c['id'] == $classroom_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="/manual-schedule/edit/<?= $schedule['id'] ?>"
            class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-pencil-square me-1"></i>Workspace
        </a>
        <a href="/manual-schedule/by-teacher/<?= $schedule['id'] ?>?teacher_id=<?= !empty($teachers) ? $teachers[0]['id'] : '' ?>"
            class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-person-badge me-1"></i>Per Guru
        </a>
        <?php if ($classroom_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="/manual-schedule/export/class/excel/<?= $schedule['id'] ?>?classroom_id=<?= $classroom_id ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel — Kelas Ini
                    </a>
                </li>
                <li>
                    <a class="dropdown-item"
                        href="/manual-schedule/export/class/pdf/<?= $schedule['id'] ?>?classroom_id=<?= $classroom_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="/manual-schedule/export/class/pdf-all/<?= $schedule['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="/manual-schedule/export/class/excel-notimes/<?= $schedule['id'] ?>?classroom_id=<?= $classroom_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="/manual-schedule/export/class/pdf-notimes/<?= $schedule['id'] ?>?classroom_id=<?= $classroom_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="/manual-schedule/export/class/pdf-all-notimes/<?= $schedule['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_classroom): ?>
<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_classroom['name']) ?></div>
        <div class="text-muted small">
            Tingkat <?= esc($selected_classroom['grade_name']) ?> &nbsp;·&nbsp;
            <?= esc($schedule['name']) ?> &nbsp;·&nbsp;
            <?= esc($schedule['year_name']) ?> — <?= esc($schedule['period_name']) ?>
        </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"><?= esc($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 = isset($schedule_data[$dayNum][$pNum]) ? $schedule_data[$dayNum][$pNum][0] : null;
                            $rawColor = $slot['teacher_color'] ?? '#17a2b8';
                            $bg   = $slot ? $rawColor : '';
                            $fg   = $slot ? getContrastColor($rawColor) : '';
                        ?>
                        <td class="text-center align-middle schedule-cell <?= $slot ? 'has-slot' : 'empty-slot' ?>"
                            <?php if ($slot): ?>
                            style="background:<?= $bg ?>;color:<?= $fg ?>"
                            title="<?= esc($slot['subject_name']) ?> — <?= esc($slot['teacher_name']) ?>"
                            <?php endif; ?>>
                            <?php if ($slot): ?>
                            <div class="slot-subject"><?= esc($slot['subject_code'] ?: $slot['subject_name']) ?></div>
                            <div class="slot-teacher">[<?= esc($slot['teacher_short_code'] ?: $slot['teacher_name']) ?>]</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
            // Kumpulkan semua mapel unik per guru dari schedule_data
            $usedTeachers = [];
            foreach ($schedule_data as $daySlots) {
                foreach ($daySlots as $slotRows) {
                    foreach ($slotRows as $slot) {
                        $code = $slot['teacher_short_code'] ?: $slot['teacher_name'];
                        if (!isset($usedTeachers[$code])) {
                            $usedTeachers[$code] = [
                                'name'     => $slot['teacher_name'],
                                'subjects' => [],
                                'slot'     => $slot,
                            ];
                        }
                        $usedTeachers[$code]['subjects'][$slot['subject_name']] = true;
                    }
                }
            }
            ksort($usedTeachers);
            foreach ($teachers as $teacher):
                $code = $teacher['short_code'] ?: $teacher['name'];
                if (!isset($usedTeachers[$code])) continue;
                // Gunakan warna dari slot (sudah di-generate HSL merata oleh model)
                $bg       = $usedTeachers[$code]['slot']['teacher_color'] ?? ($teacher['color'] ?? '#17a2b8');
                $fg       = getContrastColor($bg);
                $subjects = implode(', ', array_keys($usedTeachers[$code]['subjects']));
            ?>
            <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($code) ?>
                    </span>
                    <div class="small overflow-hidden" style="font-size:.78rem;line-height:1.3"
                        title="<?= esc($teacher['name']) ?> — <?= esc($subjects) ?>">
                        <div class="fw-semibold text-truncate"><?= esc($teacher['name']) ?></div>
                        <div class="text-muted text-truncate" style="font-size:.7rem"><?= esc($subjects) ?></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php elseif ($classroom_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 switchSchedule(scheduleId) {
    window.location.href = `/manual-schedule/by-class/${scheduleId}`;
}
function switchClass(classId) {
    const scheduleId = '<?= $schedule['id'] ?>';
    window.location.href = `/manual-schedule/by-class/${scheduleId}?classroom_id=${classId}`;
}
</script>
<?= $this->endSection() ?>
