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

<?php
$request = service('request');
$activePeriod = $activePeriod ?? [];
$fKelas   = $request->getGet('kelas');
$fMapel   = $request->getGet('mapel');
$fSearch  = $request->getGet('q');
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="fw-bold mb-0"><i class="bi bi-journal-text me-2 text-primary"></i>Jurnal Mengajar</h5>
        <p class="text-muted small mb-0">
            Semester <?= esc($activePeriod['semester'] ?? '—') ?>
            <span class="mx-1">•</span>
            Catatan pelaksanaan pembelajaran harian.
        </p>
    </div>
    <a href="/guru/journal/create" class="btn btn-primary btn-sm">
        <i class="bi bi-plus-lg me-1"></i>Jurnal Baru
    </a>
</div>

<!-- Filter -->
<div class="card shadow-sm border-0 rounded-3 mb-3">
    <div class="card-body p-3">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label small mb-0">Kelas</label>
                <select name="kelas" class="form-select form-select-sm border-0 bg-light shadow-none">
                    <option value="">Semua</option>
                    <?php foreach ($classrooms as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= $fKelas == $c['id'] ? 'selected' : '' ?>>
                        <?= esc($c['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small mb-0">Mapel</label>
                <select name="mapel" class="form-select form-select-sm border-0 bg-light shadow-none">
                    <option value="">Semua</option>
                    <?php foreach ($subjects as $s): ?>
                    <option value="<?= $s['id'] ?>" <?= $fMapel == $s['id'] ? 'selected' : '' ?>>
                        <?= esc($s['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small mb-0">Cari</label>
                <input type="text" name="q" class="form-control form-control-sm border-0 bg-light shadow-none"
                       placeholder="Materi, kelas, mapel..." value="<?= esc($fSearch) ?>">
            </div>
            <div class="col-md-3 d-flex gap-2 align-items-end">
                <button class="btn btn-sm btn-outline-primary flex-fill"><i class="bi bi-funnel me-1"></i>Filter</button>
                <a href="#" id="btnCetakJurnal" class="btn btn-sm btn-outline-secondary flex-fill" target="_blank">
                    <i class="bi bi-printer me-1"></i>Cetak
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Daftar Jurnal -->
<div class="card shadow-sm border-0 rounded-3">
    <div class="card-body p-0">
        <?php if (empty($journals)): ?>
        <div class="text-center py-5 text-muted">
            <i class="bi bi-journal-text" style="font-size:2rem;"></i>
            <p class="mt-2 mb-0">Belum ada jurnal mengajar.</p>
            <a href="/guru/journal/create" class="btn btn-primary btn-sm mt-2">Buat Jurnal Baru</a>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Tgl</th>
                        <th>Jam</th>
                        <th>Kelas</th>
                        <th>Mapel</th>
                        <th>Pert</th>
                        <th>Materi</th>
                        <th>Presensi</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($journals as $j): ?>
                    <tr>
                        <td style="white-space:nowrap;"><?= date('d/m/Y', strtotime($j['meeting_date'])) ?></td>
                        <td><?= $j['start_period'] ?>-<?= $j['end_period'] ?></td>
                        <td><?= esc($j['classroom_name']) ?></td>
                        <td><?= esc($j['subject_name']) ?></td>
                        <td><?= $j['meeting_number'] ?></td>
                        <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= esc($j['topic']) ?></td>
                        <td style="white-space:nowrap;">
                            <?php if ($j['total_present'] > 0 || $j['total_sick'] > 0 || $j['total_permit'] > 0 || $j['total_absent'] > 0): ?>
                            <span class="small">H:<?= $j['total_present'] ?>
                                <?php if ($j['total_sick']): ?><span class="text-warning ms-1">S:<?= $j['total_sick'] ?></span><?php endif; ?>
                                <?php if ($j['total_permit']): ?><span class="text-info ms-1">I:<?= $j['total_permit'] ?></span><?php endif; ?>
                                <?php if ($j['total_absent']): ?><span class="text-danger ms-1">A:<?= $j['total_absent'] ?></span><?php endif; ?>
                            </span>
                            <?php else: ?>
                            <span class="text-muted small">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <div class="d-flex gap-1 justify-content-center">
                                <a href="/guru/journal/detail/<?= $j['id'] ?>" class="btn btn-sm btn-outline-primary"
                                   title="Detail" data-bs-toggle="tooltip">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <?php if (!$j['is_final']): ?>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteJournal(<?= $j['id'] ?>)"
                                        title="Hapus" data-bs-toggle="tooltip">
                                    <i class="bi bi-trash"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.getElementById('btnCetakJurnal').addEventListener('click', function(e) {
    e.preventDefault();
    var kelas = document.querySelector('select[name="kelas"]').value;
    var mapel = document.querySelector('select[name="mapel"]').value;
    var url;
    if (kelas && mapel) {
        url = '/guru/journal/print/' + kelas + '/' + mapel;
    } else {
        url = '/guru/journal/print-all';
    }
    window.open(url, '_blank');
});
function deleteJournal(id) {
    Swal.fire({
        title: 'Hapus Jurnal?',
        text: 'Data jurnal dan presensi akan dihapus. Tindakan ini tidak bisa dibatalkan.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonText: 'Batal',
        confirmButtonText: 'Ya, Hapus'
    }).then(result => {
        if (!result.isConfirmed) return;

        fetch('/guru/journal/delete/' + id, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                Swal.fire('Berhasil', data.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Gagal', data.message, 'error');
            }
        })
        .catch(() => Swal.fire('Error', 'Terjadi kesalahan koneksi.', 'error'));
    });
}
</script>

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