<?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 guru -->
        <div class="input-group input-group-sm" style="width:auto">
            <span class="input-group-text bg-white">
                <i class="bi bi-person-badge text-primary"></i>
            </span>
            <select class="form-select form-select-sm" id="selectTeacher"
                onchange="switchTeacher(this.value)" style="min-width:220px">
                <?php foreach ($teachers as $t): ?>
                <option value="<?= esc($t['id']) ?>"
                    <?= $t['id'] == $teacher_id ? 'selected' : '' ?>>
                    [<?= esc($t['short_code'] ?: 'Guru') ?>] <?= esc($t['name']) ?>
                </option>
                <?php endforeach; ?>
            </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-class/<?= $schedule['id'] ?>?classroom_id=<?= !empty($classes) ? $classes[0]['id'] : '' ?>"
            class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-door-open me-1"></i>Per Kelas
        </a>
        <?php if ($teacher_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/teacher/excel/<?= $schedule['id'] ?>?teacher_id=<?= $teacher_id ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel — Guru Ini
                    </a>
                </li>
                <li>
                    <a class="dropdown-item"
                        href="/manual-schedule/export/teacher/pdf/<?= $schedule['id'] ?>?teacher_id=<?= $teacher_id ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Guru Ini
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item"
                        href="/manual-schedule/export/teacher/pdf-all/<?= $schedule['id'] ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Semua Guru
                    </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/teacher/excel-notimes/<?= $schedule['id'] ?>?teacher_id=<?= $teacher_id ?>">
                        <i class="bi bi-file-earmark-excel text-success me-2"></i>Excel — Guru Ini (No Waktu)
                    </a>
                </li>
                <li>
                    <a class="dropdown-item"
                        href="/manual-schedule/export/teacher/pdf-notimes/<?= $schedule['id'] ?>?teacher_id=<?= $teacher_id ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Guru Ini (No Waktu)
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item"
                        href="/manual-schedule/export/teacher/pdf-all-notimes/<?= $schedule['id'] ?>">
                        <i class="bi bi-file-earmark-pdf text-danger me-2"></i>PDF — Semua Guru (No Waktu)
                    </a>
                </li>
            </ul>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── INFO GURU ──────────────────────────────────────────────────────── -->
<?php if ($selected_teacher):
    $teacherBg = $selected_teacher['color'] ?? '#17a2b8';
    $teacherFg = getContrastColor($teacherBg);
?>
<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 fw-bold fs-5"
        style="width:48px;height:48px;background:<?= $teacherBg ?>;color:<?= $teacherFg ?>;flex-shrink:0">
        <?= esc($selected_teacher['short_code'] ?: 'G') ?>
    </div>
    <div class="flex-grow-1">
        <div class="fw-bold"><?= esc($selected_teacher['name']) ?></div>
        <div class="text-muted small">
            <?= esc(guess_id_label($selected_teacher['nip'] ?? null)) ?>: <?= esc($selected_teacher['nip'] ?: '-') ?>
            &nbsp;·&nbsp; <?= esc($schedule['name']) ?> &nbsp;·&nbsp; <?= esc($schedule['year_name']) ?> — <?= esc($schedule['period_name']) ?>
        </div>
    </div>
    <div class="text-end">
        <div class="fw-bold fs-4 text-primary"><?= $total_hours ?></div>
        <div class="text-muted small">Jam/Minggu</div>
    </div>
</div>
<?php endif; ?>

<!-- ── GRID MATRIX JADWAL GURU (TRANSPOSE: JAM SEBAGAI BARIS, HARI SEBAGAI KOLOM) ── -->
<?php if (!empty($schedule_data) && $selected_teacher):
    $teacherBg = $selected_teacher['color'] ?? '#17a2b8';
    $teacherFg = getContrastColor($teacherBg);
?>
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-bordered mb-0 schedule-matrix" id="teacherGrid">
                <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"
                            style="background:<?= $teacherBg ?>20;color:<?= $teacherFg ?>">
                            <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;
                        ?>
                        <td class="text-center align-middle schedule-cell <?= $slot ? 'has-slot' : 'empty-slot' ?>"
                            <?php if ($slot): ?>
                            style="background:<?= $teacherBg ?>;color:<?= $teacherFg ?>"
                            title="<?= esc($slot['classroom_name']) ?> — <?= esc($slot['subject_name']) ?>"
                            <?php endif; ?>>
                            <?php if ($slot): ?>
                            <div class="slot-class"><?= esc($slot['classroom_name']) ?></div>
                            <div class="slot-subject"><?= esc($slot['subject_code'] ?: $slot['subject_name']) ?></div>
                            <?php endif; ?>
                         </td>
                        <?php endforeach; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Ringkasan mengajar per kelas -->
<div class="card mt-3">
    <div class="card-header py-2 d-flex align-items-center gap-2">
        <i class="bi bi-bar-chart text-primary"></i>
        <span class="fw-semibold small">Ringkasan Mengajar</span>
    </div>
    <div class="card-body py-2">
        <?php
        $classSummary = [];
        foreach ($schedule_data as $daySlots) {
            foreach ($daySlots as $slotRows) {
                foreach ($slotRows as $slot) {
                    $key = $slot['classroom_name'];
                    if (!isset($classSummary[$key])) {
                        $classSummary[$key] = [
                            'class' => $slot['classroom_name'],
                            'subjects_full' => [],
                            'hours' => 0
                        ];
                    }
                    $classSummary[$key]['hours']++;
                    $classSummary[$key]['subjects_full'][$slot['subject_name']] = true;
                }
            }
        }
        ksort($classSummary);
        ?>
        <div class="row g-2">
            <?php foreach ($classSummary as $summary): ?>
            <div class="col-6 col-md-3 col-lg-2">
                <div class="border rounded p-2 text-center h-100">
                    <div class="fw-bold summary-badge"
                        style="color:<?= $teacherFg ?>;background:<?= $teacherBg ?>">
                        <?= esc($summary['class']) ?>
                    </div>
                    <div class="text-muted small mt-1" style="font-size:.75rem">
                        <?= implode(', ', array_keys($summary['subjects_full'])) ?>
                    </div>
                    <div class="fw-semibold text-primary mt-1" style="font-size:.85rem">
                        <?= $summary['hours'] ?> jam
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php elseif ($teacher_id): ?>
<div class="alert alert-warning">
    <i class="bi bi-exclamation-triangle me-2"></i>Tidak ada data jadwal untuk guru ini.
</div>
<?php else: ?>
<div class="alert alert-info">
    <i class="bi bi-arrow-up-circle me-2"></i>Pilih guru untuk melihat jadwal mengajar.
</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-class {
    font-size: .82rem;
    font-weight: 700;
    line-height: 1.2;
}
.slot-subject {
    font-size: .7rem;
    line-height: 1.2;
    margin-top: 2px;
    opacity: .85;
}
.summary-badge {
    padding: 3px 6px;
    font-size: .8rem;
    border-radius: 4px;
    display: inline-block;
}
</style>
<script>
function switchSchedule(scheduleId) {
    window.location.href = `/manual-schedule/by-teacher/${scheduleId}`;
}
function switchTeacher(teacherId) {
    const scheduleId = '<?= $schedule['id'] ?>';
    window.location.href = `/manual-schedule/by-teacher/${scheduleId}?teacher_id=${teacherId}`;
}
</script>
<?= $this->endSection() ?>
