<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Presensi ASN - Kab. Polewali Mandar</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script>
    <style>
        :root {
            --primary: #155724;
            --secondary: #FFD700;
            --bg: #f8fafc;
        }

        body {
            background-color: var(--bg);
            padding-bottom: 120px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            color: #1e293b;
            user-select: none;
        }

        .header-section {
            background: linear-gradient(135deg, #0b3d17 0%, #155724 100%);
            color: white;
            border-radius: 0 0 35px 35px;
            padding: 40px 24px 80px;
            text-align: center;
        }

        .time-badge {
            display: inline-flex;
            align-items: center;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            padding: 8px 20px;
            border-radius: 20px;
            font-weight: 700;
            color: var(--secondary);
            font-size: 1.2rem;
            margin-bottom: 20px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .absensi-container {
            margin-top: -65px;
            display: flex;
            justify-content: center;
            z-index: 10;
            position: relative;
        }

        .btn-absen-main {
            width: 135px;
            height: 135px;
            border-radius: 50%;
            background: white;
            border: none;
            padding: 10px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            transition: 0.3s;
            position: relative;
        }

        .pulse-animation {
            animation: pulse-yellow 2s infinite;
        }

        @keyframes pulse-yellow {
            0% {
                box-shadow: 0 0 0 0 rgba(255, 215, 0, 0.7);
            }

            70% {
                box-shadow: 0 0 0 15px rgba(255, 215, 0, 0);
            }

            100% {
                box-shadow: 0 0 0 0 rgba(255, 215, 0, 0);
            }
        }

        .btn-absen-inner {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: linear-gradient(135deg, #FFD700 0%, #edc300 100%);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #155724;
            border: 4px solid white;
        }

        .btn-absen-main:active {
            transform: scale(0.95);
        }

        .status-card {
            background: white;
            border-radius: 20px;
            padding: 15px;
            text-align: center;
            flex: 1;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        }

        .status-pill {
            font-size: 0.65rem;
            padding: 4px 12px;
            border-radius: 50px;
            font-weight: 800;
            letter-spacing: 0.5px;
            display: inline-block;
        }

        .holiday-footer {
            background: #fff;
            border-radius: 20px;
            padding: 15px;
            border-left: 5px solid #dc3545;
            margin-top: 20px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
        }

        .bottom-nav {
            position: fixed;
            bottom: 20px;
            left: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(15px);
            display: flex;
            justify-content: space-around;
            padding: 12px;
            border-radius: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            z-index: 1000;
        }

        .nav-item {
            text-align: center;
            color: #94a3b8;
            text-decoration: none;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .nav-item.active {
            color: var(--primary);
        }

        #camera-container {
            display: none;
            position: fixed;
            inset: 0;
            background: #000;
            z-index: 9999;
        }

        #video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>

<body>

    <div class="pwa-wrapper">
        <div id="camera-container">
            <video id="video" autoplay muted playsinline></video>
            <div class="camera-ui text-center position-absolute bottom-0 w-100 mb-5 pb-4">
                <div id="face-status" class="alert alert-light mx-4 shadow-lg border-0 rounded-4 fw-bold">Menyiapkan...</div>
                <button class="btn btn-danger btn-lg rounded-pill px-5 shadow" onclick="location.reload()">Batal</button>
            </div>
        </div>

        <div class="header-section">
            <div class="time-badge"><i class="far fa-clock me-2"></i><span id="live-clock">00:00:00</span></div>
            <div class="fw-bold fs-4"><?= $pegawai['nama_lengkap'] ?></div>
            <div class="opacity-75 small mb-3">NIP. <?= $pegawai['nip'] ?></div>
            <span class="badge bg-warning text-dark px-3 py-2 rounded-pill fw-bold shadow-sm" style="font-size: 0.7rem;">ASN KAB. POLEWALI MANDAR</span>
        </div>

        <div class="absensi-container">
            <?php if ($libur): ?>
                <button class="btn-absen-main" onclick="Swal.fire('Hari Libur','<?= $libur['keterangan'] ?>','info')">
                    <div class="btn-absen-inner" style="background: #ef4444; border-color: #f87171; color: white;">
                        <i class="fas fa-umbrella-beach fa-2x mb-1"></i><span class="small fw-bold">LIBUR</span>
                    </div>
                </button>
            <?php else: ?>
                <button class="btn-absen-main pulse-animation" id="startAbsen">
                    <div class="btn-absen-inner shadow-sm">
                        <i class="fas fa-fingerprint fa-3x mb-1"></i><span class="small fw-bold">ABSEN</span>
                    </div>
                </button>
            <?php endif; ?>
        </div>

        <div class="container px-4 mt-4">
            <div class="d-flex gap-3 mb-4">

                <div class="status-card shadow-sm border-0">
                    <div class="text-muted small fw-bold mb-1">MASUK</div>
                    <?php if ($terakhir && isset($terakhir['jam_masuk_aktual'])): ?>
                        <div class="fs-4 fw-bold text-success mb-1"><?= date('H:i', strtotime($terakhir['jam_masuk_aktual'])) ?></div>

                        <?php
                        $statusM = $terakhir['status_masuk'] ?? 'Hadir';
                        $bgM = ($statusM == 'Terlambat') ? 'bg-danger text-danger' : 'bg-success text-success';
                        ?>
                        <span class="status-pill <?= $bgM ?> bg-opacity-10"><?= $statusM ?></span>

                        <?php if (isset($terakhir['menit_keterlambatan']) && $terakhir['menit_keterlambatan'] > 0): ?>
                            <div class="mt-2 text-danger fw-bold" style="font-size: 0.7rem; background: #fff0f0; padding: 3px 8px; border-radius: 6px; display: inline-block;">
                                <i class="fas fa-exclamation-circle me-1"></i>Telat <?= $terakhir['menit_keterlambatan'] ?> mnt
                            </div>
                        <?php endif; ?>

                    <?php else: ?>
                        <div class="fs-4 fw-bold text-light mb-1">--:--</div>
                        <span class="status-pill bg-secondary bg-opacity-10 text-secondary">-</span>
                    <?php endif; ?>
                </div>

                <div class="status-card shadow-sm border-0">
                    <div class="text-muted small fw-bold mb-1">KELUAR</div>
                    <?php if ($terakhir && isset($terakhir['jam_pulang_aktual'])): ?>
                        <div class="fs-4 fw-bold text-primary mb-1"><?= date('H:i', strtotime($terakhir['jam_pulang_aktual'])) ?></div>

                        <?php
                        $statusP = $terakhir['status_pulang'] ?? 'Selesai';
                        $bgP = ($statusP == 'Cepat Pulang') ? 'bg-warning text-warning' : 'bg-primary text-primary';
                        ?>
                        <span class="status-pill <?= $bgP ?> bg-opacity-10"><?= $statusP ?></span>

                    <?php else: ?>
                        <div class="fs-4 fw-bold text-light mb-1">--:--</div>
                        <span class="status-pill bg-secondary bg-opacity-10 text-secondary">-</span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="row g-3 mb-4 text-center">
                <div class="col-6">
                    <div class="status-card py-3" onclick="openModalIzin('Sakit')">
                        <i class="fas fa-file-signature fa-2x text-success mb-2"></i>
                        <div class="small fw-bold">Sakit / Izin</div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="status-card py-3" onclick="openModalIzin('Tugas Luar')">
                        <i class="fas fa-briefcase fa-2x text-warning mb-2"></i>
                        <div class="small fw-bold">Tugas Luar</div>
                    </div>
                </div>
            </div>

            <?php if (!empty($libur_mendatang)): ?>
                <h6 class="fw-bold small text-muted mb-2 px-1">Informasi Libur Terdekat</h6>
                <?php foreach ($libur_mendatang as $lm): ?>
                    <div class="holiday-footer d-flex align-items-center mb-3">
                        <div class="bg-danger bg-opacity-10 p-2 rounded-circle me-3 text-danger"><i class="fas fa-bullhorn small"></i></div>
                        <div>
                            <div class="fw-bold small"><?= $lm['keterangan'] ?></div>
                            <div class="text-muted" style="font-size: 0.7rem;"><?= date('d F Y', strtotime($lm['tanggal'])) ?></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <nav class="bottom-nav">
            <a href="<?= base_url('pwa') ?>" class="nav-item active"><i class="fas fa-house-user"></i><br>Home</a>
            <a href="#" class="nav-item"><i class="fas fa-clipboard-list"></i><br>Riwayat</a>
            <a href="#" class="nav-item"><i class="fas fa-user-gear"></i><br>Profil</a>
            <a href="<?= base_url('logout') ?>" class="nav-item text-danger"><i class="fas fa-power-off"></i><br>Keluar</a>
        </nav>
    </div>

     <div class="modal fade" id="modalIzin" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg" style="border-radius: 25px;">
                <div class="modal-header border-0 pb-0">
                    <h6 class="fw-bold mb-0" id="titleIzin">Pengajuan</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="formIzin" enctype="multipart/form-data">
                    <div class="modal-body p-4">
                        <input type="hidden" name="kategori" id="inputKategori">

                        <div class="mb-3">
                            <label class="small fw-bold text-muted mb-1">Alasan / Keterangan</label>
                            <textarea name="deskripsi" class="form-control border-light bg-light" rows="3" placeholder="Contoh: Sakit demam, Izin urusan keluarga, atau Lokasi tugas luar..." required></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-muted mb-1">Unggah Bukti (Foto/PDF)</label>
                            <input type="file" name="file_bukti" class="form-control border-light bg-light" accept="image/*,application/pdf" required>
                            <div class="form-text" style="font-size: 0.65rem;">Ambil foto surat dokter atau surat tugas.</div>
                        </div>

                        <div class="alert alert-info py-2" style="font-size: 0.7rem;">
                            <i class="fas fa-info-circle me-1"></i> Pengajuan akan diverifikasi oleh Admin Kominfo.
                        </div>

                        <button type="submit" class="btn btn-success w-100 rounded-pill fw-bold py-2 mt-2" id="btnKirimIzin">Kirim Pengajuan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        setInterval(() => {
            document.getElementById('live-clock').innerText = new Date().toLocaleTimeString('id-ID', {
                hour12: false
            });
        }, 1000);

        let faceMatcher = null;
        let modelsLoaded = false;

        async function initFaceAPI() {
            const MODEL_URL = 'https://justadudewhohacks.github.io/face-api.js/models';
            try {
                await Promise.all([
                    faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL),
                    faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL),
                    faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL),
                    faceapi.nets.faceExpressionNet.loadFromUri(MODEL_URL)
                ]);

                const rawVector = '<?= $face_data ?>';
                if (rawVector && rawVector !== "") {
                    const descriptor = new Float32Array(JSON.parse(rawVector));
                    faceMatcher = new faceapi.FaceMatcher(new faceapi.LabeledFaceDescriptors('ASN', [descriptor]), 0.6);
                    modelsLoaded = true;
                    console.log("AI Liveness Ready");
                } else {
                    Swal.fire('Data Wajah Kosong', 'Hubungi Admin untuk rekam wajah.', 'warning');
                }
            } catch (err) {
                console.error("Error FaceAPI:", err);
            }
        }
        initFaceAPI();

        document.getElementById('startAbsen').onclick = async () => {
            if (!modelsLoaded) return Swal.fire('Tunggu', 'Sedang memuat model AI...', 'info');

            const container = document.getElementById('camera-container');
            const video = document.getElementById('video');
            const status = document.getElementById('face-status');

            container.style.display = 'block';

            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        facingMode: 'user'
                    }
                });
                video.srcObject = stream;

                const interval = setInterval(async () => {
                    const detect = await faceapi.detectSingleFace(video, new faceapi.TinyFaceDetectorOptions())
                        .withFaceLandmarks()
                        .withFaceDescriptor()
                        .withFaceExpressions();

                    if (detect && faceMatcher) {
                        const match = faceMatcher.findBestMatch(detect.descriptor);

                        if (match.label !== 'unknown') {
                            const expressions = detect.expressions;
                            if (expressions.happy > 0.7) {
                                clearInterval(interval);

                                status.className = "alert alert-success mx-4 shadow-lg border-0 rounded-4 fw-bold";
                                status.innerHTML = '<i class="fas fa-smile-beam me-2"></i>Senyum Terkonfirmasi!';

                                setTimeout(() => {
                                    status.className = "alert alert-warning mx-4 shadow-lg border-0 rounded-4 fw-bold";
                                    status.innerHTML = '<i class="fas fa-map-marker-alt fa-bounce me-2"></i>Mengambil Lokasi...';
                                    getGPSLocation(stream);
                                }, 1000);

                            } else {
                                status.className = "alert alert-info mx-4 shadow-lg border-0 rounded-4 fw-bold";
                                status.innerHTML = '<i class="far fa-smile me-2"></i>Silakan Senyum!';
                            }
                        } else {
                            status.className = "alert alert-danger mx-4 shadow-lg border-0 rounded-4 fw-bold";
                            status.innerHTML = '<i class="fas fa-times-circle me-2"></i>Wajah Tidak Dikenal';
                        }
                    } else {
                        status.innerHTML = 'Arahkan wajah ke kamera...';
                    }
                }, 500);
            } catch (err) {
                Swal.fire('Izin Kamera Ditolak', 'Pastikan izin kamera diberikan.', 'error');
                container.style.display = 'none';
            }
        };

        function getGPSLocation(stream) {
            const status = document.getElementById('face-status');
            if (!navigator.geolocation) {
                Swal.fire('Error', 'Browser tidak mendukung Geolocation.', 'error');
                return;
            }
            navigator.geolocation.getCurrentPosition(
                (pos) => {
                    if (pos.coords.accuracy > 100) {
                        status.innerHTML = '<i class="fas fa-exclamation-triangle me-2"></i>GPS Tidak Akurat!';
                        Swal.fire('Sinyal Lemah', 'Akurasi GPS rendah (' + Math.round(pos.coords.accuracy) + 'm). Pindah ke area terbuka.', 'warning')
                            .then(() => location.reload());
                        return;
                    }
                    status.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>Mengirim Data...';
                    stream.getTracks().forEach(t => t.stop());
                    submitToDatabase(pos.coords.latitude, pos.coords.longitude);
                },
                (err) => {
                    let errorMsg = "Gagal mengambil lokasi.";
                    switch (err.code) {
                        case err.PERMISSION_DENIED:
                            errorMsg = "Izin lokasi ditolak.";
                            break;
                        case err.POSITION_UNAVAILABLE:
                            errorMsg = "Sinyal GPS hilang.";
                            break;
                        case err.TIMEOUT:
                            errorMsg = "Waktu habis, cari sinyal yang lebih baik.";
                            break;
                    }
                    stream.getTracks().forEach(t => t.stop());
                    document.getElementById('camera-container').style.display = 'none';
                    Swal.fire('GPS Gagal', errorMsg, 'error').then(() => location.reload());
                }, {
                    enableHighAccuracy: true,
                    timeout: 20000,
                    maximumAge: 0
                }
            );
        }

        function submitToDatabase(lat, lng) {
            const form = new FormData();
            form.append('latitude', lat);
            form.append('longitude', lng);
            form.append('device_info', navigator.userAgent);

            fetch('<?= base_url('pwa/submit_absen') ?>', {
                    method: 'POST',
                    body: form
                })
                .then(res => res.json())
                .then(data => {
                    document.getElementById('camera-container').style.display = 'none';
                    if (data.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: data.message,
                            confirmButtonText: 'Selesai',
                            confirmButtonColor: '#155724',
                            allowOutsideClick: false
                        }).then((result) => {
                            if (result.isConfirmed) location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Ditolak',
                            text: data.message,
                            footer: '<small class="text-danger">Wajah & Senyum ✅ | Lokasi ❌</small>',
                            confirmButtonText: 'Coba Lagi',
                            confirmButtonColor: '#dc3545',
                            allowOutsideClick: false
                        }).then((result) => {
                            if (result.isConfirmed) location.reload();
                        });
                    }
                })
                .catch(err => {
                    document.getElementById('camera-container').style.display = 'none';
                    Swal.fire('Error Server', 'Gagal terhubung ke server.', 'error');
                });
        }

        // Fungsi untuk membuka Modal dan set kategori
        function openModalIzin(kat) {
            document.getElementById('inputKategori').value = kat;
            document.getElementById('titleIzin').innerText = 'Form Pengajuan ' + kat;
            new bootstrap.Modal(document.getElementById('modalIzin')).show();
        }

        // Logika Submit Form Izin via AJAX
        document.getElementById('formIzin').onsubmit = async function(e) {
            e.preventDefault();

            const btn = document.getElementById('btnKirimIzin');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Mengirim...';

            const formData = new FormData(this);

            try {
                const response = await fetch('<?= base_url('pwa/submit_izin') ?>', {
                    method: 'POST',
                    body: formData
                });
                const res = await response.json();

                if (res.status === 'success') {
                    Swal.fire('Berhasil', res.message, 'success').then(() => location.reload());
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                    btn.disabled = false;
                    btn.innerText = 'Kirim Pengajuan';
                }
            } catch (err) {
                Swal.fire('Error', 'Gagal terhubung ke server', 'error');
                btn.disabled = false;
                btn.innerText = 'Kirim Pengajuan';
            }
        };
    </script>

   

</body>

</html>