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

<style>
/* Cegah seluruh wrapper flexbox dan layout melar melebihi lebar layar */
.main-content {
    min-width: 0 !important;
    overflow-x: hidden !important;
}
.content-area {
    min-width: 0 !important;
    max-width: 100% !important;
    overflow-x: hidden !important;
    padding: 1.5rem !important;
}
.row, .col-12, .card {
    min-width: 0 !important;
    max-width: 100% !important;
}
.table-sticky-container {
    overflow: auto;
    max-height: calc(100vh - 440px); /* Batasi tinggi tabel dinamis lebih rendah agar footer langsung terlihat */
    min-height: 250px;
    max-width: 100%;
    width: 100%;
    border: 1px solid #dee2e6;
    border-radius: 8px;
}
.table-sticky-container th,
.table-sticky-container td {
    white-space: nowrap;
    vertical-align: middle;
}
/* Sticky Header (Scroll kebawah tetap diam) */
.table-sticky-container th {
    position: sticky;
    top: 0;
    background-color: #f8f9fa !important;
    z-index: 3;
    box-shadow: 0 2px 3px -1px rgba(0,0,0,0.1);
}
/* Sticky Column 1: No (Scroll ke kanan tetap diam) */
.sticky-col-no {
    position: sticky;
    left: 0;
    background-color: #fff !important;
    z-index: 4;
    width: 50px;
    min-width: 50px;
    max-width: 50px;
    text-align: center;
}
th.sticky-col-no {
    position: sticky;
    top: 0;
    left: 0;
    z-index: 6 !important;
    background-color: #f8f9fa !important;
}
/* Sticky Column 2: Nama Siswa (Scroll ke kanan tetap diam) */
.sticky-student-name {
    position: sticky;
    left: 50px; /* Offset selebar kolom No (50px) */
    background-color: #fff !important;
    z-index: 4;
    box-shadow: 3px 0 6px -2px rgba(0,0,0,0.15);
}
/* Persimpangan: Judul Kolom Nama Siswa */
th.sticky-student-name {
    position: sticky;
    top: 0;
    left: 50px;
    z-index: 6 !important;
    background-color: #f8f9fa !important;
    box-shadow: 3px 2px 6px -2px rgba(0,0,0,0.2) !important;
}
/* Row hover adjustment for sticky columns */
tr:hover td.sticky-student-name,
tr:hover td.sticky-col-no {
    background-color: #f1f5f9 !important;
}
</style>

<div class="row">
    <div class="col-12">
        <div class="card border-0 shadow-sm mb-4" style="border-radius: 12px;">
            <div class="card-body p-4 bg-light bg-gradient" style="border-radius: 12px 12px 0 0;">
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                    <div class="d-flex align-items-center gap-3">
                        <div class="bg-primary bg-opacity-10 p-3 rounded-circle text-primary" style="font-size: 1.8rem; line-height: 1;">
                            <i class="bi bi-card-checklist"></i>
                        </div>
                        <div>
                            <h5 class="fw-bold mb-0 text-dark">Monitoring Kelengkapan Data Siswa</h5>
                            <small class="text-muted">Pantau status pengisian data mandiri KK, NIK, Orang Tua, Alamat, dan Ijazah secara langsung.</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filter Section -->
            <div class="card-body border-bottom bg-white">
                <form action="/student/completeness" method="get" class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label fw-semibold small text-muted">Tahun Pelajaran</label>
                        <select name="academic_period_id" class="form-select border-primary" onchange="this.form.submit()">
                            <?php foreach ($periods as $p): ?>
                                <option value="<?= $p['id'] ?>" <?= (int)$selectedPeriodId === (int)$p['id'] ? 'selected' : '' ?>>
                                    <?= esc($p['year_name']) ?> - Sem. <?= esc($p['semester']) ?> <?= $p['is_active'] ? '(Aktif)' : '' ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-semibold small text-muted">Saring Kelas</label>
                        <select name="classroom_id" class="form-select border-primary" onchange="this.form.submit()">
                            <option value="">-- Semua Kelas --</option>
                            <?php foreach ($classrooms as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= (int)$selectedClassroomId === (int)$c['id'] ? 'selected' : '' ?>>
                                    Kelas <?= esc($c['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex gap-2">
                        <button type="submit" class="btn btn-primary w-100 rounded-pill">
                            <i class="bi bi-filter me-2"></i>Filter Data
                        </button>
                        <a href="/student/completeness" class="btn btn-outline-secondary rounded-pill">
                            <i class="bi bi-arrow-clockwise"></i>
                        </a>
                    </div>
                </form>
            </div>

            <!-- Table Content -->
            <div class="card-body p-4 bg-white" style="border-radius: 0 0 12px 12px;">
                <?php if (empty($students)): ?>
                    <div class="text-center py-5">
                        <div class="text-muted fs-1 mb-3"><i class="bi bi-people"></i></div>
                        <h6 class="fw-bold text-dark">Tidak Ada Data Siswa</h6>
                        <p class="text-muted small">Tidak ada siswa aktif terdaftar pada filter kelas / periode akademik terpilih.</p>
                    </div>
                <?php else: ?>
                    <div class="table-sticky-container">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="sticky-col-no" width="50">No</th>
                                    <th class="sticky-student-name">Nama Siswa</th>
                                    <th class="text-center">Kelas</th>
                                    <th class="text-center">% Lengkap</th>
                                    <th class="text-center">Foto</th>
                                    <th class="text-center">NIK Siswa</th>
                                    <th class="text-center">KIP</th>
                                    <th class="text-center">No. KK</th>
                                    <th class="text-center">Kepala Keluarga</th>
                                    <th class="text-center">Nama Ayah</th>
                                    <th class="text-center">NIK Ayah</th>
                                    <th class="text-center">HP Ayah</th>
                                    <th class="text-center">Nama Ibu</th>
                                    <th class="text-center">NIK Ibu</th>
                                    <th class="text-center">HP Ibu</th>
                                    <th class="text-center">Alamat / Jalan</th>
                                    <th class="text-center">RT</th>
                                    <th class="text-center">RW</th>
                                    <th class="text-center">Desa / Kelurahan</th>
                                    <th class="text-center">Kecamatan</th>
                                    <th class="text-center">Kota / Kabupaten</th>
                                    <th class="text-center">Provinsi</th>
                                    <th class="text-center">Kode Pos</th>
                                    <th class="text-center">Sekolah Asal</th>
                                    <th class="text-center">Seri Ijazah</th>
                                    <th class="text-center">HP Siswa</th>
                                    <th class="text-center" width="100">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $no = 1;

                                // Helper function untuk render status ceklis/silang/warning
                                function renderCellData($val, $type = 'text', $isRequired = true) {
                                    $val = trim($val ?? '');
                                    if ($val === '') {
                                        if ($isRequired) {
                                            return '<span class="text-danger" style="font-size: 1.1rem;" title="Kosong / Belum Diisi"><i class="bi bi-x-circle-fill"></i></span>';
                                        } else {
                                            return '<span class="text-muted" style="font-size: 1.1rem;" title="Kosong (Opsional)"><i class="bi bi-dash-circle"></i></span>';
                                        }
                                    }
                                    
                                    // Validasi NIK/KK
                                    if ($type === 'nik' || $type === 'kk') {
                                        if (strlen($val) !== 16 || !ctype_digit($val)) {
                                            return '<span class="text-warning" style="font-size: 1.1rem;" title="Format tidak valid! Harus tepat 16 digit angka. Terdeteksi: ' . esc($val) . ' (' . strlen($val) . ' digit)"><i class="bi bi-exclamation-triangle-fill"></i></span>';
                                        }
                                        return '<span class="text-success" style="font-size: 1.1rem;" title="Terisi: ' . esc($val) . '"><i class="bi bi-check-circle-fill"></i></span>';
                                    }
                                    
                                    // Validasi HP
                                    if ($type === 'phone') {
                                        if (!str_starts_with($val, '628') || strlen($val) < 10 || strlen($val) > 15 || !ctype_digit($val)) {
                                            return '<span class="text-warning" style="font-size: 1.1rem;" title="Format tidak valid! Harus diawali 628 dan 10-15 digit. Terdeteksi: ' . esc($val) . '"><i class="bi bi-exclamation-triangle-fill"></i></span>';
                                        }
                                        return '<span class="text-success" style="font-size: 1.1rem;" title="Terisi: ' . esc($val) . '"><i class="bi bi-check-circle-fill"></i></span>';
                                    }
                                    
                                    return '<span class="text-success" style="font-size: 1.1rem;" title="Terisi: ' . esc($val) . '"><i class="bi bi-check-circle-fill"></i></span>';
                                }
                                ?>
                                <?php foreach ($students as $s): ?>
                                    <?php
                                    // Hitung Skor Kelengkapan (Total 14 field kunci)
                                    $score = 0;
                                    
                                    $hasPhoto = !empty($s['photo']);
                                    $hasNik = (!empty($s['nik']) && strlen(trim($s['nik'])) === 16 && ctype_digit($s['nik']));
                                    $hasKip = !empty($s['kip_no']);
                                    $hasKk = (!empty($s['family_card_no']) && strlen(trim($s['family_card_no'])) === 16 && ctype_digit($s['family_card_no']));
                                    $hasKkHead = !empty($s['family_head_name']);
                                    $hasFatherName = !empty($s['father_name']);
                                    $hasFatherNik = (!empty($s['father_nik']) && strlen(trim($s['father_nik'])) === 16 && ctype_digit($s['father_nik']));
                                    $hasFatherPhone = !empty($s['father_phone']);
                                    $hasMotherName = !empty($s['mother_name']);
                                    $hasMotherNik = (!empty($s['mother_nik']) && strlen(trim($s['mother_nik'])) === 16 && ctype_digit($s['mother_nik']));
                                    $hasMotherPhone = !empty($s['mother_phone']);
                                    $hasAddress = !empty($s['address']);
                                    $hasOriginSchool = !empty($s['origin_school']);
                                    $hasIjazah = !empty($s['graduation_certificate_no']);
                                    $hasStudentPhone = !empty($s['phone']);

                                    if ($hasPhoto) $score++;
                                    if ($hasNik) $score++;
                                    if ($hasKk) $score++;
                                    if ($hasKkHead) $score++;
                                    if ($hasFatherName) $score++;
                                    if ($hasFatherNik) $score++;
                                    if ($hasFatherPhone) $score++;
                                    if ($hasMotherName) $score++;
                                    if ($hasMotherNik) $score++;
                                    if ($hasMotherPhone) $score++;
                                    if ($hasAddress) $score++;
                                    if ($hasOriginSchool) $score++;
                                    if ($hasIjazah) $score++;
                                    if ($hasStudentPhone) $score++;

                                    $percent = round(($score / 14) * 100);

                                    // Color style berdasarkan persentase
                                    if ($percent === 100) {
                                        $barColor = 'bg-success';
                                        $badgeColor = 'badge bg-success-subtle text-success';
                                    } elseif ($percent >= 50) {
                                        $barColor = 'bg-warning';
                                        $badgeColor = 'badge bg-warning-subtle text-warning';
                                    } else {
                                        $barColor = 'bg-danger';
                                        $badgeColor = 'badge bg-danger-subtle text-danger';
                                    }
                                    ?>
                                    <tr>
                                        <td class="sticky-col-no text-muted small"><?= $no++ ?></td>
                                        <td class="sticky-student-name fw-bold text-dark">
                                            <?= esc($s['full_name']) ?>
                                        </td>
                                        <td class="text-center text-secondary small">
                                            <?= esc($s['classroom_name'] ?? '-') ?>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center gap-2" style="min-width: 100px;">
                                                <div class="progress w-100" style="height: 6px; border-radius: 4px;">
                                                    <div class="progress-bar <?= $barColor ?>" style="width: <?= $percent ?>%"></div>
                                                </div>
                                                <span class="<?= $badgeColor ?> font-monospace" style="font-size: 0.75rem; padding: 3px 6px;">
                                                    <?= $percent ?>%
                                                </span>
                                            </div>
                                        </td>
                                        <td class="text-center">
                                            <?php if ($hasPhoto): ?>
                                                <span class="text-success" style="font-size: 1.1rem;" title="Ada Foto"><i class="bi bi-check-circle-fill"></i></span>
                                            <?php else: ?>
                                                <span class="text-danger" style="font-size: 1.1rem;" title="Kosong / Belum Diisi"><i class="bi bi-x-circle-fill"></i></span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center"><?= renderCellData($s['nik'], 'nik') ?></td>
                                        <td class="text-center"><?= renderCellData($s['kip_no'], 'text', false) ?></td>
                                        <td class="text-center"><?= renderCellData($s['family_card_no'], 'kk') ?></td>
                                        <td class="text-center"><?= renderCellData($s['family_head_name']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['father_name']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['father_nik'], 'nik') ?></td>
                                        <td class="text-center"><?= renderCellData($s['father_phone'], 'phone') ?></td>
                                        <td class="text-center"><?= renderCellData($s['mother_name']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['mother_nik'], 'nik') ?></td>
                                        <td class="text-center"><?= renderCellData($s['mother_phone'], 'phone') ?></td>
                                        <td class="text-center"><?= renderCellData($s['address']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['rt']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['rw']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['village']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['district']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['city']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['province']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['postal_code']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['origin_school']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['graduation_certificate_no']) ?></td>
                                        <td class="text-center"><?= renderCellData($s['phone'], 'phone') ?></td>
                                        <td class="text-center">
                                            <a href="/student/edit/<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary rounded-pill px-3" title="Edit Data Siswa">
                                                <i class="bi bi-pencil-square me-1"></i>Edit
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mt-3 small text-muted">
                        <div>
                            Menampilkan <strong><?= count($students) ?></strong> siswa terdaftar.
                        </div>
                        <div class="d-flex gap-3">
                            <span><span class="text-danger fw-semibold"><i class="bi bi-x-circle me-1"></i>Kosong</span> (Wajib Diisi)</span>
                            <span><span class="text-warning fw-bold bg-warning bg-opacity-10 px-2 py-0.5 rounded border border-warning">Data <i class="bi bi-exclamation-triangle-fill"></i></span> (Format Salah / Kurang Digit)</span>
                            <span><span class="text-muted">-</span> (Opsional Kosong)</span>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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