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

<?php
function getInitialsAv(string $name): string {
    $words = explode(' ', trim($name));
    $init  = '';
    foreach (array_slice($words, 0, 2) as $w) $init .= mb_strtoupper(mb_substr($w, 0, 1));
    return $init;
}
$avatarColors = [
    ['bg'=>'#E6F1FB','color'=>'#0C447C'],['bg'=>'#EEEDFE','color'=>'#3C3489'],
    ['bg'=>'#E1F5EE','color'=>'#085041'],['bg'=>'#FAEEDA','color'=>'#633806'],
    ['bg'=>'#FBEAF0','color'=>'#72243E'],['bg'=>'#EAF3DE','color'=>'#27500A'],
    ['bg'=>'#FAECE7','color'=>'#712B13'],
];
?>

<style>
.av-tbl { width:100%; border-collapse:collapse; font-size:13px; }
.av-tbl thead th { padding:9px 12px; font-size:11px; font-weight:600; color:#6b7280; background:#f9fafb; border-bottom:1px solid #e5e7eb; }
.av-tbl tbody tr { border-bottom:1px solid #f3f4f6; transition:background .1s; }
.av-tbl tbody tr:hover { background:#f9fafb; }
.av-tbl td { padding:9px 12px; vertical-align:middle; }
.guru-avatar { width:34px; height:34px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:700; flex-shrink:0; }
.av-badge { font-size:11px; padding:2px 9px; border-radius:20px; font-weight:600; white-space:nowrap; }
.badge-ok      { background:#E1F5EE; color:#085041; }
.badge-blocked { background:#FBEAF0; color:#72243E; }
.badge-custom  { background:#EBF5FF; color:#0C447C; }
.badge-default { background:#f3f4f6; color:#6b7280; border:1px solid #e5e7eb; }

/* Progress bar blokir */
.block-bar { height:4px; border-radius:2px; background:#e5e7eb; width:80px; display:inline-block; vertical-align:middle; }
.block-bar-fill { height:100%; border-radius:2px; background:#f87171; }
</style>

<div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
    <div>
        <h5 class="mb-0 fw-semibold">
            <i class="bi bi-slash-circle me-2 text-primary"></i>Ketersediaan Guru
        </h5>
        <small class="text-muted">
            Atur batas jam mengajar dan slot tidak tersedia per guru.
            Engine generate akan menghormati semua pengaturan ini.
        </small>
    </div>
    <div class="ibox" style="background:#EBF5FF;color:#0C447C;border:1px solid #BFDBFE;border-radius:8px;padding:6px 14px;font-size:12px">
        <i class="bi bi-clock me-1"></i>Default global: <strong><?= $defaultMax ?> jam/hari</strong>
    </div>
</div>

<!-- Filter & search -->
<div class="d-flex gap-2 mb-3 flex-wrap align-items-center">
    <input type="text" id="searchGuru" class="form-control form-control-sm"
           placeholder="Cari nama / NIP / PEG ID..." style="max-width:240px" oninput="doSearch()">
    <select id="filterBlokir" class="form-select form-select-sm" style="max-width:180px" onchange="doSearch()">
        <option value="all">Semua guru</option>
        <option value="blocked">Ada slot diblokir</option>
        <option value="free">Bebas semua</option>
        <option value="custom">Jam custom</option>
    </select>
    <span id="countInfo" class="text-muted small align-self-center"></span>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="av-tbl">
                <thead>
                    <tr>
                        <th style="width:42px"></th>
                        <th>Nama Guru</th>
                        <th>NIP / PEG ID</th>
                        <th class="text-center">Maks Jam/Hari</th>
                        <th class="text-center">Slot Diblokir</th>
                        <th class="text-center" style="width:100px">Aksi</th>
                    </tr>
                </thead>
                <tbody id="tbodyAv">
                <?php
                // Hitung total KBM slot untuk persentase bar
                $db = \Config\Database::connect();
                $totalKbmAll = $db->table('schedule_timeslots')
                    ->where('slot_type', 'kbm')->where('is_active', 1)
                    ->countAllResults();
                $maxPossibleBlocked = max($totalKbmAll, 1);
                ?>
                <?php foreach ($summary as $idx => $row): ?>
                <?php
                    $av       = $avatarColors[$idx % count($avatarColors)];
                    $initials = getInitialsAv($row['name']);
                    $blocked  = (int)$row['total_blocked'];
                    $maxH     = $row['max_hours_per_day'];
                    $isCustom = $maxH !== null;
                    $blockPct = min(100, round($blocked / $maxPossibleBlocked * 100));
                    $hasBlock = $blocked > 0;
                    $isCustomH= $isCustom;
                ?>
                <tr data-name="<?= strtolower(esc($row['name'])) ?>"
                    data-nip="<?= esc($row['nip'] ?? '') ?>"
                    data-pegid="<?= esc($row['peg_id'] ?? '') ?>"
                    data-blocked="<?= $hasBlock ? 'blocked' : 'free' ?>"
                    data-custom="<?= $isCustomH ? 'custom' : 'default' ?>">
                    <td>
                        <div class="guru-avatar" style="background:<?= $av['bg'] ?>;color:<?= $av['color'] ?>">
                            <?= $initials ?>
                        </div>
                    </td>
                    <td class="fw-semibold"><?= esc($row['name']) ?></td>
                    <td class="text-muted" style="font-size:12px"><?= esc($row['nip'] ?? '—') ?></td>
                    <td class="text-center">
                        <?php if ($isCustom): ?>
                        <span class="av-badge badge-custom">
                            <i class="bi bi-person-gear me-1"></i><?= $maxH ?> jam
                        </span>
                        <?php else: ?>
                        <span class="av-badge badge-default">
                            <?= $defaultMax ?> jam (default)
                        </span>
                        <?php endif; ?>
                    </td>
                    <td class="text-center">
                        <?php if ($blocked === 0): ?>
                        <span class="av-badge badge-ok">
                            <i class="bi bi-check-circle me-1"></i>Bebas semua
                        </span>
                        <?php else: ?>
                        <div class="d-flex flex-column align-items-center gap-1">
                            <span class="av-badge badge-blocked">
                                <i class="bi bi-x-circle me-1"></i><?= $blocked ?> slot
                            </span>
                            <div class="block-bar">
                                <div class="block-bar-fill" style="width:<?= $blockPct ?>%"></div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td class="text-center">
                        <a href="/schedule-availability/edit/<?= $row['id'] ?>"
                           class="btn btn-outline-primary btn-sm py-0 px-3">
                            <i class="bi bi-grid me-1"></i>Atur
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="emptyState" class="text-center text-muted py-4" style="display:none">
    <i class="bi bi-search fs-2 d-block mb-2 opacity-25"></i>
    Tidak ada guru yang cocok dengan filter.
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const rows = Array.from(document.querySelectorAll('#tbodyAv tr'));

function doSearch() {
    const q  = (document.getElementById('searchGuru').value || '').toLowerCase();
    const f  = document.getElementById('filterBlokir').value;
    let n = 0;
    rows.forEach(r => {
        const nm = r.dataset.name || '';
        const np = r.dataset.nip  || '';
        let show = nm.includes(q) || np.includes(q);
        if (f === 'blocked' && r.dataset.blocked !== 'blocked') show = false;
        if (f === 'free'    && r.dataset.blocked !== 'free')    show = false;
        if (f === 'custom'  && r.dataset.custom  !== 'custom')  show = false;
        r.style.display = show ? '' : 'none';
        if (show) n++;
    });
    document.getElementById('countInfo').textContent = n + ' guru';
    document.getElementById('emptyState').style.display = n === 0 ? '' : 'none';
}
doSearch();
</script>
<?= $this->endSection() ?>