<?= $this->extend('layout/main') ?>

<?= $this->section('content') ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h5 class="fw-bold mb-0">Manajemen Pegawai</h5>
        <p class="text-muted small mb-0">Kelola data personil dan registrasi wajah biometrik</p>
    </div>
    <button class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalPegawai">
        <i class="fas fa-user-plus me-1"></i> Tambah Pegawai
    </button>
</div>

<?php if (session()->getFlashdata('success')) : ?>
    <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
        <i class="fas fa-check-circle me-2"></i> <?= session()->getFlashdata('success') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <div class="row align-items-center">
            <div class="col-md-4">
                <label class="small fw-bold text-muted mb-1">Filter Unit Kerja (OPD)</label>
                <select id="filter_opd" class="form-select form-select-sm border-light bg-light">
                    <?php if (session()->get('level') == 'kabupaten'): ?>
                        <option value="">-- Tampilkan Semua OPD --</option>
                    <?php endif; ?>
                    <?php foreach ($opd_list as $o): ?>
                        <option value="<?= $o['id_opd'] ?>"><?= $o['nama_opd'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-8 text-end mt-3 mt-md-0">
                <span class="badge bg-info-subtle text-info px-3">Total Kapasitas: Ribuan Pegawai</span>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <div class="table-responsive">
            <table id="tabelPegawai" class="table table-hover align-middle mb-0" style="width:100%">
                <thead class="bg-light text-muted small">
                    <tr>
                        <th width="5%">NO</th>
                        <th width="30%">NAMA PEGAWAI</th>
                        <th width="25%">JABATAN / LEVEL</th>
                        <th width="20%" class="text-center">STATUS WAJAH</th>
                        <th width="20%" class="text-center">AKSI</th>
                    </tr>
                </thead>
                <tbody>
                    </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPegawai" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold">Tambah Pegawai Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="<?= base_url('pegawai/simpan') ?>" method="POST">
                <?= csrf_field() ?>
                <div class="modal-body px-4">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Unit Kerja (OPD)</label>
                        <select name="id_opd" class="form-select border-light bg-light" required>
                            <?php foreach ($opd_list as $o): ?>
                                <option value="<?= $o['id_opd'] ?>"><?= $o['nama_opd'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label small fw-bold">NIP</label>
                            <input type="text" name="nip" class="form-control border-light bg-light" placeholder="Masukkan NIP" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small fw-bold">Nama Lengkap</label>
                            <input type="text" name="nama_lengkap" class="form-control border-light bg-light" placeholder="Nama Tanpa Gelar" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Jabatan Spesifik</label>
                        <input type="text" name="jabatan" class="form-control border-light bg-light" placeholder="Contoh: Analis IT" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Jabatan Spesifik</label>
                        <input type="text" name="jabatan" class="form-control border-light bg-light" placeholder="Contoh: Analis IT" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Level Jabatan</label>
                        <select name="level_jabatan" class="form-select border-light bg-light" required>
                            <option value="Kepala Dinas">Kepala Dinas</option>
                            <option value="Sekretaris">Sekretaris</option>
                            <option value="Kepala Bidang">Kepala Bidang</option>
                            <option value="Pejabat Fungsional">Pejabat Fungsional</option>
                            <option value="Staf" selected>Staf / Pelaksana</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Password Login</label>
                        <input type="password" name="password" class="form-control border-light bg-light" placeholder="Min. 6 Karakter" required>
                    </div>
                </div>
                <div class="modal-footer border-0 px-4">
                    <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary rounded-pill px-4">Simpan Pegawai</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditPegawai" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold">Edit Data Pegawai</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="<?= base_url('pegawai/update') ?>" method="POST">
                <?= csrf_field() ?>
                <input type="hidden" name="id_pegawai" id="edit_id_pegawai">
                <div class="modal-body px-4">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Unit Kerja (OPD)</label>
                        <select name="id_opd" id="edit_id_opd" class="form-select border-light bg-light" required>
                            <?php foreach ($opd_list as $o): ?>
                                <option value="<?= $o['id_opd'] ?>"><?= $o['nama_opd'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label small fw-bold">NIP</label>
                            <input type="text" name="nip" id="edit_nip" class="form-control border-light bg-light" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small fw-bold">Nama Lengkap</label>
                            <input type="text" name="nama_lengkap" id="edit_nama_lengkap" class="form-control border-light bg-light" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Jabatan Spesifik</label>
                        <input type="text" name="jabatan" id="edit_jabatan" class="form-control border-light bg-light" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Level Jabatan</label>
                        <select name="level_jabatan" id="edit_level_jabatan" class="form-select border-light bg-light" required>
                            <option value="Kepala Dinas">Kepala Dinas</option>
                            <option value="Sekretaris">Sekretaris</option>
                            <option value="Kepala Bidang">Kepala Bidang</option>
                            <option value="Pejabat Fungsional">Pejabat Fungsional</option>
                            <option value="Staf">Staf / Pelaksana</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold text-danger">Ganti Password (Kosongkan jika tidak diubah)</label>
                        <input type="password" name="password" class="form-control border-light bg-light" placeholder="Masukkan password baru">
                    </div>
                </div>
                <div class="modal-footer border-0 px-4">
                    <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning rounded-pill px-4">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEnroll" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white border-0">
                <h5 class="modal-title small"><i class="fas fa-id-card-alt me-2"></i>Registrasi Wajah: <span id="enroll_name"></span></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" onclick="stopCamera()"></button>
            </div>
            <div class="modal-body text-center bg-light p-4">
                <div class="position-relative d-inline-block border border-5 border-white shadow-lg rounded-circle overflow-hidden" style="width: 280px; height: 280px;">
                    <video id="video" width="400" height="300" autoplay muted style="margin-left: -60px;"></video>
                </div>
                <div id="status_enroll" class="mt-3 fw-bold text-secondary small">Menyiapkan AI & Kamera...</div>
                <input type="hidden" id="enroll_id_pegawai">
            </div>
            <div class="modal-footer border-0">
                <button type="button" id="btnCapture" class="btn btn-primary w-100 rounded-pill py-2 shadow" disabled onclick="captureFace()">
                    <i class="fas fa-fingerprint me-2"></i> Pindai & Daftarkan Wajah
                </button>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script>



<script>
    var table;
    $(document).ready(function() {
        // INISIALISASI DATATABLES SERVER-SIDE
        table = $('#tabelPegawai').DataTable({
            "processing": true,
            "serverSide": true,
            "responsive": true,
            "ajax": {
                "url": "<?= base_url('pegawai/ajax_list') ?>",
                "type": "POST",
                "data": function(d) {
                    d.filter_opd = $('#filter_opd').val();
                    d.<?= csrf_token() ?> = "<?= csrf_hash() ?>";
                }
            },
            "columnDefs": [
                { "targets": [0, 3, 4], "orderable": false },
                { "targets": [3, 4], "className": "text-center" }
            ],
            "language": {
                "search": "Cari Nama/NIP:",
                "lengthMenu": "Tampil _MENU_",
                "info": "Data _START_ - _END_ dari _TOTAL_",
                "paginate": { "previous": "<", "next": ">" }
            }
        });

        // Event filter OPD
        $('#filter_opd').change(function() {
            table.ajax.reload();
        });
    });

    // --- LOGIKA FACE API ---
    const video = document.getElementById('video');
    const statusText = document.getElementById('status_enroll');
    const btnCapture = document.getElementById('btnCapture');
    let modelsLoaded = false;

    async function loadModels() {
        if (modelsLoaded) return true;
        statusText.innerText = "Memuat Modul AI...";
        try {
            const MODEL_URL = '<?= base_url('models') ?>';
            await faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL);
            await faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL);
            await faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL);
            modelsLoaded = true;
            return true;
        } catch (e) {
            statusText.innerText = "Modul AI Gagal! Cek folder /models";
            return false;
        }
    }

    async function startCamera() {
        const ready = await loadModels();
        if (!ready) return;

        navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } })
            .then(stream => {
                video.srcObject = stream;
                statusText.innerText = "Dekatkan wajah ke tengah lingkaran";
                btnCapture.disabled = false;
            })
            .catch(err => {
                statusText.innerText = "Kamera diblokir! Gunakan HTTPS.";
            });
    }

    async function captureFace() {
        btnCapture.disabled = true;
        statusText.innerText = "Menganalisis wajah... Tahan posisi";

        const detections = await faceapi.detectSingleFace(video, new faceapi.TinyFaceDetectorOptions({ inputSize: 224 }))
            .withFaceLandmarks().withFaceDescriptor();

        if (detections) {
            statusText.innerText = "Wajah Terverifikasi! Menyimpan...";
            const faceVector = JSON.stringify(Array.from(detections.descriptor));
            
            const formData = new FormData();
            formData.append('id_pegawai', $('#enroll_id_pegawai').val());
            formData.append('face_vector', faceVector);
            formData.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

            fetch('<?= base_url('pegawai/simpan_face_vector') ?>', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(res => res.json())
            .then(res => {
                if(res.status === 'success') {
                    alert("Sukses meregistrasi wajah!");
                    location.reload();
                } else {
                    alert("Gagal: " + res.msg);
                    btnCapture.disabled = false;
                }
            });
        } else {
            statusText.innerText = "Wajah tidak jelas. Coba lagi.";
            btnCapture.disabled = false;
        }
    }

    function openEnroll(id, name) {
        $('#enroll_id_pegawai').val(id);
        $('#enroll_name').text(name);
        const modal = new bootstrap.Modal(document.getElementById('modalEnroll'));
        modal.show();
        document.getElementById('modalEnroll').addEventListener('shown.bs.modal', startCamera, { once: true });
    }

    function stopCamera() {
        if (video.srcObject) video.srcObject.getTracks().forEach(t => t.stop());
    }

    async function openEdit(id) {
        fetch('<?= base_url('pegawai/edit_data') ?>/' + id)
            .then(res => res.json())
            .then(data => {
                $('#edit_id_pegawai').val(data.id_pegawai);
                $('#edit_id_opd').val(data.id_opd);
                $('#edit_nip').val(data.nip);
                $('#edit_nama_lengkap').val(data.nama_lengkap);
                $('#edit_jabatan').val(data.jabatan);
                $('#edit_level_jabatan').val(data.level_jabatan);
                new bootstrap.Modal(document.getElementById('modalEditPegawai')).show();
            });
    }
</script>
<?= $this->endSection() ?>