<?php

/**
 * ============================================================================
 * PROYEK     : SISTEM PRESENSI BIOMETRIK PWA (PREMIUM EDITION)
 * INSTANSI   : PEMKAB POLEWALI MANDAR
 * DEVELOPER  : COLLABORATIVE AI FOR PAK FATHUR
 * FILE       : index.php (Main Dashboard)
 * ============================================================================
 */

/**
 * FUNGSI: getStatusAbsen
 * Mengembalikan array CSS Class dan Teks berdasarkan data murni dari database.
 * Perhitungan grading waktu sekarang di-handle oleh Controller saat Absen Masuk.
 */
function getStatusAbsen($jam, $status_db = '')
{
    // 1. Cek Jika Belum Ada Data Jam Sama Sekali
    if (!$jam || $jam == '00:00:00' || $jam == null) {
        // Jika ada status Izin/Sakit yang terisi duluan
        if ($status_db && $status_db !== 'Hadir' && $status_db !== 'Pending') {
            return ['teks' => $status_db, 'class' => 'bg-info text-dark'];
        }
        return [
            'teks'  => '-',
            'class' => 'bg-secondary bg-opacity-10 text-secondary'
        ];
    }

    // 2. TENTUKAN WARNA BERDASARKAN STRING YANG TERSIMPAN DI DATABASE
    if ($status_db == 'Sangat Baik / Istimewa') {
        return ['teks' => 'Sangat Baik', 'class' => 'bg-success text-white'];
    } elseif ($status_db == 'Baik') {
        return ['teks' => 'Baik', 'class' => 'bg-info text-dark'];
    } elseif ($status_db == 'Cukup Baik') {
        return ['teks' => 'Cukup Baik', 'class' => 'bg-warning text-dark'];
    } elseif ($status_db == 'Terlambat') {
        return ['teks' => 'Terlambat', 'class' => 'bg-danger text-white'];
    } elseif ($status_db == 'Pembinaan') {
        return ['teks' => 'Pembinaan', 'class' => 'bg-danger text-white'];
    } elseif ($status_db == 'Teguran') {
        return ['teks' => 'Teguran', 'class' => 'bg-dark text-white'];
    } elseif ($status_db == 'Hadir (Apel)') {
        return ['teks' => 'Hadir (Apel)', 'class' => 'bg-primary text-white shadow-sm fw-bold'];
    } else {
        // Fallback default jika status belum/tidak dikenali (contoh: diisi admin manual)
        return ['teks' => $status_db ?: 'Hadir', 'class' => 'bg-primary text-white'];
    }
}

// Global Time Marker
if($pegawai['waktu']=='Asia/Makassar') // misal: 'Asia/Makassar'
{   ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Sync Jam Digital
            setInterval(() => {
                document.getElementById('pwa-digital-clock').innerText = new Date().toLocaleTimeString('id-ID', {
                    timeZone: 'Asia/Makassar', hour12: false
                });
            }, 1000);
        });

    </script><?php
} elseif($pegawai['waktu']=='Asia/Jayapura') {
    ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Sync Jam Digital
            setInterval(() => {
                document.getElementById('pwa-digital-clock').innerText = new Date().toLocaleTimeString('id-ID', {
                    timeZone: 'Asia/Jayapura', hour12: false
                });
            }, 1000);
        });

    </script><?php
} else {
    ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Sync Jam Digital
            setInterval(() => {
                document.getElementById('pwa-digital-clock').innerText = new Date().toLocaleTimeString('id-ID', {
                    timeZone: 'Asia/Jakarta', hour12: false
                });
            }, 1000);
        });

    </script><?php
}
$userTimezone = $pegawai['waktu'];
date_default_timezone_set($userTimezone);
$jam_sekarang = date('H:i:s');
//echo $jam_sekarang;
?>

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <title>Presensi Pegawai Multimayaka</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@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="manifest" href="<?= base_url('manifest.json') ?>">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="theme-color" content="#155724">

    <link rel="shortcut icon" type="image/x-icon" href="<?= base_url('favicon.ico') ?>">
    <link rel="apple-touch-icon" href="<?= base_url('assets/img/logo_180.png') ?>">

    <script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script>

    <style>
        /* ============================================================
            1. CSS VARIABLES & CORE STYLING
            ============================================================
        */
        :root {
            --polman-green: #155724;
            --polman-yellow: #FFD700;
            --soft-white: #f8fafc;
            --pure-white: #ffffff;
            --main-dark: #1e293b;
            --main-muted: #64748b;
            --shadow-sm: 0 4px 12px rgba(0, 0, 0, 0.03);
            --shadow-md: 0 10px 25px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 15px 40px rgba(0, 0, 0, 0.15);
            --glass: rgba(255, 255, 255, 0.1);
        }

        * {
            box-sizing: border-box;
            outline: none !important;
            font-size: 0.95rem;
        }

        body {
            background-color: var(--soft-white);
            padding-bottom: 120px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            color: var(--main-dark);
            overflow-x: hidden;
            -webkit-font-smoothing: antialiased;
        }

        /* ============================================================
            2. HEADER & PROFILE SECTION
            ============================================================
        */
        .header-section {
            background: linear-gradient(135deg, #0b3d17 0%, #155724 100%);
            color: var(--pure-white);
            border-radius: 0 0 50px 50px;
            padding: 60px 24px 110px;
            text-align: center;
            position: relative;
            z-index: 1;
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
        }

        .refresh-trigger {
            position: absolute;
            top: 20px;
            right: 20px;
        }

        .digital-clock-container {
            display: inline-flex;
            align-items: center;
            background: var(--glass);
            backdrop-filter: blur(12px);
            padding: 12px 35px;
            border-radius: 40px;
            font-weight: 800;
            color: var(--polman-yellow);
            font-size: 1.6rem;
            margin-bottom: 25px;
            border: 1px solid rgba(255, 255, 255, 0.25);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .user-profile-header .name {
            font-weight: 800;
            font-size: 1.5rem;
            margin-bottom: 8px;
            letter-spacing: -0.5px;
        }

        .user-profile-header .nip {
            opacity: 0.85;
            font-size: 0.9rem;
            font-weight: 500;
            display: block;
            margin-bottom: 8px;
        }

        .user-profile-header .waktu {
            opacity: 0.85;
            font-size: 0.9rem;
            font-weight: 500;
            display: block;
            margin-bottom: 25px;
        }

        .badge-asn {
            background: rgba(255, 255, 255, 0.15);
            padding: 10px 22px;
            border-radius: 30px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* ============================================================
            3. MAIN CONTENT WRAPPER (CARDS)
            ============================================================
        */
        .content-main-wrapper {
            margin-top: -85px;
            position: relative;
            z-index: 10;
            padding: 0 24px;
            display: flex;
            flex-direction: column;
            gap: 25px;
        }

        .card-notif-apel {
            background: var(--pure-white);
            border-radius: 28px;
            padding: 24px;
            box-shadow: var(--shadow-md);
            border: 1px solid rgba(21, 87, 36, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            overflow: hidden;
        }

        .card-notif-apel::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 8px;
            background: var(--polman-green);
        }

        .card-notif-apel .text-content .title {
            font-weight: 800;
            color: var(--main-dark);
            font-size: 1rem;
            margin-bottom: 6px;
        }

        .card-notif-apel .text-content .meta {
            font-size: 0.8rem;
            color: var(--main-muted);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* ============================================================
            4. BIOMETRIC BUTTON (THE HUB)
            ============================================================
        */
        .absensi-btn-area {
            display: flex;
            justify-content: center;
            position: relative;
            padding: 15px 0;
        }

        .btn-absen-circular {
            width: 165px;
            height: 165px;
            border-radius: 50%;
            background: var(--pure-white);
            border: none;
            padding: 15px;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.18);
            position: relative;
            z-index: 50;
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            cursor: pointer;
        }

        .btn-absen-circular:active {
            transform: scale(0.92);
        }

        .btn-inner-gold {
            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: 7px solid var(--pure-white);
        }

        .btn-inner-green {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: linear-gradient(135deg, #28a745 0%, #155724 100%);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: var(--pure-white);
            border: 7px solid var(--pure-white);
        }

        .pulse-layer {
            animation: pulse-border 2.5s infinite;
        }

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

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

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

        /* ============================================================
            5. DASHBOARD STATS GRID
            ============================================================
        */
        .stats-grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
        }

        .stat-card-item {
            background: var(--pure-white);
            border-radius: 24px;
            padding: 20px 10px;
            text-align: center;
            box-shadow: var(--shadow-sm);
            border: 1px solid #edf2f7;
        }

        .stat-card-item .label {
            font-size: 0.6rem;
            font-weight: 800;
            color: var(--main-muted);
            text-transform: uppercase;
            letter-spacing: 1.2px;
            margin-bottom: 10px;
            display: block;
        }

        .stat-card-item .value {
            font-size: 1.2rem;
            font-weight: 800;
            color: var(--main-dark);
            margin-bottom: 10px;
            display: block;
        }

        .pill-status {
            font-size: 0.55rem;
            padding: 6px 14px;
            border-radius: 50px;
            font-weight: 800;
            display: inline-block;
            line-height: 1;
        }

        /* ============================================================
            6. MENU ROW & PERMIT ACTIONS
            ============================================================
        */
        .menu-item {
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .menu-item:active {
            transform: translateY(4px);
        }

        .menu-item i {
            font-size: 1.8rem;
        }

        .menu-item span {
            font-size: 0.65rem;
            font-weight: 800;
            margin-top: 8px;
        }

        /* ============================================================
            7. RIWAYAT & AGENDA LISTING
            ============================================================
        */
        .riwayat-item-card {
            background: var(--pure-white);
            border-radius: 18px;
            padding: 16px;
            margin-bottom: 12px;
            box-shadow: var(--shadow-sm);
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-left: 5px solid #CBD5E0;
        }

        .history-container {
            max-height: 400px;
            overflow-y: auto;
            padding-right: 5px;
        }

        /* ============================================================
            8. CAMERA & AI OVERLAY UI
            ============================================================
        */
        #camera-verification-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: #000;
            z-index: 99999;
        }

        #camera-stream {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transform: scaleX(-1);
        }

        .camera-mask-circle {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 310px;
            height: 310px;
            border: 5px solid var(--polman-yellow);
            border-radius: 50%;
            box-shadow: 0 0 0 2000px rgba(0, 0, 0, 0.6);
            pointer-events: none;
        }

        .camera-ui-panel {
            position: absolute;
            bottom: 120px;
            left: 20px;
            right: 20px;
            text-align: center;
        }

        /* ============================================================
            9. BOTTOM NAVIGATION BAR
            ============================================================
        */
        .nav-pwa-bottom {
            position: fixed;
            bottom: 25px;
            left: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.96);
            backdrop-filter: blur(20px);
            display: flex;
            justify-content: space-around;
            padding: 16px 12px;
            border-radius: 35px;
            box-shadow: 0 15px 50px rgba(0, 0, 0, 0.18);
            z-index: 1000;
            border: 1px solid rgba(255, 255, 255, 0.4);
        }

        .nav-pwa-link {
            text-align: center;
            text-decoration: none;
            color: #94a3b8;
            font-size: 0.75rem;
            font-weight: 800;
            flex: 1;
            transition: all 0.3s ease;
        }

        .nav-pwa-link.active {
            color: var(--polman-green);
        }

        .nav-pwa-link i {
            font-size: 1.4rem;
            margin-bottom: 6px;
            display: block;
        }

        .card-notif-pengajuan {
            background: var(--pure-white);
            border-radius: 28px;
            padding: 24px;
            box-shadow: var(--shadow-md);
            border: 1px solid rgba(245, 158, 11, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            overflow: hidden;
        }

        .card-notif-pengajuan::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 8px;
            background: #f59e0b;
        }

        .card-notif-pengajuan .text-content .title {
            font-weight: 800;
            color: var(--main-dark);
            font-size: 1rem;
            margin-bottom: 6px;
        }
    </style>

</head>

<body>

    <div id="camera-verification-overlay">
        <video id="camera-stream" autoplay muted playsinline></video>
        <div class="camera-mask-circle"></div>

        <div class="camera-ui-panel">
            <div id="ai-status-label" class="alert alert-light rounded-4 shadow-lg fw-bold py-3 px-4 border-0">
                <i class="fas fa-circle-notch fa-spin me-2 text-success"></i> Menyiapkan Kamera...
            </div>

            <button class="btn btn-danger btn-lg rounded-pill px-5 shadow-lg mt-4 fw-800" onclick="window.location.reload();">
                <i class="fas fa-times-circle me-2"></i> BATALKAN
            </button>
        </div>
    </div>

    <div class="pwa-main-container">

        <header class="header-section">
            <div class="refresh-trigger">
                <button onclick="handleUIRefresh(this)" class="btn btn-sm btn-light rounded-circle shadow border-0" style="width: 48px; height: 48px;">
                    <i class="fas fa-sync-alt text-success fs-5"></i>
                </button>
            </div>

            <div class="digital-clock-container">
                <i class="far fa-clock me-2"></i>
                <span id="pwa-digital-clock">00:00:00</span>
            </div>

            <div class="user-profile-header">
                <span class="small text-uppercase fw-bold text-warning mb-2 d-block" style="letter-spacing: 2px;">
                    <?php
                    $hari_indo = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
                    $bulan_indo = ['', 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
                    echo $hari_indo[date('w')] . ', ' . date('d') . ' ' . $bulan_indo[date('n')] . ' ' . date('Y');
                    ?>
                </span>

                <h1 class="name"><?= $pegawai['nama_lengkap'] ?></h1>
                <span class="nip">NIP. <?= $pegawai['nip'] ?></span>
                <span class="waktu">Waktu. <?= $pegawai['waktu'] ?></span>

                <div class="mt-4">
                    <span class="badge-asn">
                        <i class="fas fa-building me-1 text-warning"></i> PT Multimayaka
                    </span>
                </div>
            </div>
        </header>

        <main class="content-main-wrapper">

            <?php
            $jam_limit_target = $tugas_apel['jam_akhir'] ?? '08:00:00';
            $is_apel_currently_valid = ($tugas_apel && $jam_sekarang <= $jam_limit_target);
            ?>

            <?php
            if ($tugas_apel && $is_apel_currently_valid):
            ?>
                <div class="card-notif-apel shadow-lg">
                    <div class="text-content">
                        <span class="fw-800 text-muted mb-1 d-block" style="font-size: 0.65rem; text-transform: uppercase; letter-spacing: 1.5px;">Penugasan Apel</span>
                        <div class="title"><?= $tugas_apel['nama_apel'] ?></div>
                        <div class="meta">
                            <i class="fas fa-map-marker-alt text-danger"></i> Lokasi: Lapangan Upacara
                            <span class="mx-1">•</span>
                            <i class="far fa-clock text-primary"></i> Batas: <?= date('H:i', strtotime($jam_limit_target)) ?>
                        </div>
                    </div>

                    <div class="status-indicator">
                        <?php if ($tugas_apel['sudah_absen_apel']): ?>
                            <i class="fas fa-check-circle text-success fs-2"></i>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($pengajuan_aktif): ?>
                <div class="card-notif-pengajuan shadow-lg">
                    <div class="text-content">
                        <span class="fw-800 text-muted mb-1 d-block" style="font-size: 0.65rem; text-transform: uppercase; letter-spacing: 1.5px;">Status Pengajuan</span>

                        <div class="title"><?= $pengajuan_aktif['kategori'] ?> (<?= $pengajuan_aktif['sub_kategori'] ?>)</div>

                        <div class="meta" style="font-size: 0.75rem; color: var(--main-muted); display: flex; align-items: center; gap: 6px;">
                            <i class="far fa-calendar-alt text-primary"></i>
                            <?= date('d M', strtotime($pengajuan_aktif['tanggal_mulai'])) ?>
                            <?= ($pengajuan_aktif['tanggal_mulai'] != $pengajuan_aktif['tanggal_selesai']) ? '- ' . date('d M', strtotime($pengajuan_aktif['tanggal_selesai'])) : '' ?>

                            <?php if ($pengajuan_aktif['sub_kategori'] == 'Setengah Hari' || $pengajuan_aktif['sub_kategori'] == 'Dalam Daerah'): ?>
                                <span class="mx-1">•</span>
                                <i class="far fa-clock text-warning"></i> Sesi <?= $pengajuan_aktif['slot_waktu'] ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="status-indicator">
                        <?php if ($pengajuan_aktif['status_approval'] == 'Pending'): ?>
                            <span class="badge bg-warning text-dark rounded-pill px-3 py-2 fw-bold" style="font-size: 0.65rem;">
                                <i class="fas fa-hourglass-half me-1"></i> PENDING
                            </span>
                        <?php elseif ($pengajuan_aktif['status_approval'] == 'Disetujui'): ?>
                            <span class="badge bg-success text-white rounded-pill px-3 py-2 fw-bold" style="font-size: 0.65rem;">
                                <i class="fas fa-check-circle me-1"></i> DISETUJUI
                            </span>
                        <?php else: ?>
                            <span class="badge bg-danger text-white rounded-pill px-3 py-2 fw-bold" style="font-size: 0.65rem;">
                                <i class="fas fa-times-circle me-1"></i> DITOLAK
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div class="absensi-btn-area">
                <?php
                // Logic Night Lock (Presensi hanya boleh jam 07:00 ke atas)
                $is_night_lock = ($jam_sekarang >= '00:00:00' && $jam_sekarang < '07:00:00');
                ?>

                <?php if ($libur): ?>
                    <button class="btn-absen-circular" onclick="Swal.fire('Hari Libur Nasional','<?= $libur['keterangan'] ?>','info')">
                        <div class="btn-inner-gold" style="background: #ef4444; color: white; border-color: #fee2e2;">
                            <i class="fas fa-calendar-times fa-3x mb-2"></i>
                            <span class="small fw-bold">LIBUR</span>
                        </div>
                    </button>

                <?php elseif ($is_night_lock): ?>
                    <button class="btn-absen-circular" onclick="Swal.fire('Sistem Tertutup','Presensi dimulai pukul 07:00 WITA.','warning')">
                        <div class="btn-inner-gold" style="background: #1e293b; color: #94a3b8; border-color: #334155;">
                            <i class="fas fa-moon fa-3x mb-2 text-warning"></i>
                            <span class="small fw-bold">CLOSED</span>
                        </div>
                    </button>

                <?php elseif ($is_apel_currently_valid && !$tugas_apel['sudah_absen_apel']): ?>
                    <button class="btn-absen-circular pulse-layer" onclick="handleStartVerification('apel', <?= $tugas_apel['id_apel'] ?>)">
                        <div class="btn-inner-green shadow-lg">
                            <i class="fas fa-user-check fa-4x mb-2"></i>
                            <span class="small fw-bold text-uppercase" style="font-size: 0.7rem;">Absen Apel</span>
                        </div>
                    </button>

                <?php else: ?>
                    <button class="btn-absen-circular pulse-layer" id="btn-trigger-attendance">
                        <div class="btn-inner-gold shadow-lg">
                            <i class="fas fa-fingerprint fa-4x mb-2"></i>
                            <span class="small fw-bold">PRESENSI</span>
                        </div>
                    </button>
                <?php endif; ?>
            </div>

            <div class="stats-grid-container">
                <div class="stat-card-item">
                    <span class="label">Masuk</span>
                    <?php if ($terakhir && isset($terakhir['jam_masuk_aktual'])): ?>
                        <span class="value"><?= date('H:i', strtotime($terakhir['jam_masuk_aktual'])) ?></span>
                        <?php $stat_m = getStatusAbsen($terakhir['jam_masuk_aktual'], $terakhir['status_masuk']); ?>
                        <span class="pill-status <?= $stat_m['class'] ?>"><?= $stat_m['teks'] ?></span>
                    <?php else: ?>
                        <span class="value text-light opacity-50">--:--</span>
                        <span class="pill-status bg-light text-muted">Belum</span>
                    <?php endif; ?>
                </div>

                <div class="stat-card-item">
                    <span class="label">Siang</span>
                    <?php if ($terakhir && isset($terakhir['jam_siang']) && $terakhir['jam_siang'] != null): ?>
                        <span class="value text-warning fw-bold"><?= date('H:i', strtotime($terakhir['jam_siang'])) ?></span>
                        <span class="pill-status bg-warning bg-opacity-10 text-warning">Ishoma</span>
                    <?php else: ?>
                        <span class="value text-light opacity-50">--:--</span>
                        <span class="pill-status bg-light text-muted">Belum</span>
                    <?php endif; ?>
                </div>

                <div class="stat-card-item">
                    <span class="label">Keluar</span>
                    <?php if ($terakhir && isset($terakhir['jam_pulang_aktual']) && $terakhir['jam_pulang_aktual'] != null): ?>
                        <span class="value text-primary fw-bold"><?= date('H:i', strtotime($terakhir['jam_pulang_aktual'])) ?></span>
                        <span class="pill-status bg-primary text-white">Selesai</span>
                    <?php else: ?>
                        <span class="value text-light opacity-50">--:--</span>
                        <span class="pill-status bg-light text-muted">Belum</span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="menu-row d-flex gap-2">
                <div class="menu-item flex-fill shadow-sm d-flex flex-column align-items-center bg-white rounded-4 py-4 px-2" onclick="handleFormSpecial('Sakit')">
                    <i class="fas fa-notes-medical text-danger fs-1"></i>
                    <span class="fw-800">SAKIT</span>
                </div>
                <div class="menu-item flex-fill shadow-sm d-flex flex-column align-items-center bg-white rounded-4 py-4 px-2" onclick="handleFormSpecial('Izin')">
                    <i class="fas fa-envelope-open-text text-primary fs-1"></i>
                    <span class="fw-800">IZIN</span>
                </div>
                <div class="menu-item flex-fill shadow-sm d-flex flex-column align-items-center bg-white rounded-4 py-4 px-2" onclick="handleFormSpecial('Tugas Luar')">
                    <i class="fas fa-plane-departure text-warning fs-1"></i>
                    <span class="fw-800">TUGAS LUAR</span>
                </div>
            </div>

            <div id="pwa-riwayat-list-section" class="mt-2">
                <div class="d-flex justify-content-between align-items-center mb-3 px-1">
                    <h6 class="fw-800 text-dark mb-0">Riwayat 7 Hari Terakhir</h6>
                    <a href="javascript:void(0)" onclick="handleOpenFilterModal()" class="small text-primary fw-800 text-decoration-none">
                        Filter <i class="fas fa-filter ms-1"></i>
                    </a>
                </div>

                <div class="history-container">
                    <?php if (empty($riwayat)): ?>
                        <div class="bg-white rounded-4 p-5 text-center border border-dashed shadow-sm">
                            <i class="fas fa-folder-open fa-3x text-light mb-3"></i>
                            <p class="small text-muted mb-0 fw-600">Belum ada riwayat presensi.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($riwayat as $row): ?>
                            <?php
                            $status_res = ($row['kategori'] == 'Hadir')
                                ? getStatusAbsen($row['jam_masuk_aktual'], $row['status_masuk'])
                                : ['teks' => $row['kategori'], 'class' => 'bg-info text-dark'];
                            ?>
                            <div class="riwayat-item-card shadow-sm">
                                <div class="date-group">
                                    <div class="fw-800 text-dark" style="font-size: 0.95rem;"><?= date('d F Y', strtotime($row['tanggal'])) ?></div>
                                    <div class="text-muted small mt-1">
                                        <i class="far fa-clock me-1 text-primary"></i>
                                        <?= ($row['jam_masuk_aktual']) ? date('H:i', strtotime($row['jam_masuk_aktual'])) : '--:--' ?> -
                                        <?= ($row['jam_pulang_aktual']) ? date('H:i', strtotime($row['jam_pulang_aktual'])) : '--:--' ?>
                                    </div>
                                </div>
                                <span class="badge <?= $status_res['class'] ?> rounded-pill px-3 py-2" style="font-size: 0.6rem;"><?= $status_res['teks'] ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

        </main>

        <nav class="nav-pwa-bottom">
            <a href="<?= base_url('pwa') ?>" class="nav-pwa-link active">
                <i class="fas fa-house-chimney-user"></i> Home
            </a>
            <?php
            if($pegawai['golongan']=='Sales')
            {
                echo '<a href="'.base_url('visit').'" class="nav-pwa-link">
                <i class="fas fa-arrows-to-eye"></i> Visit</a>';
            }
            ?>
            <a href="javascript:void(0)" onclick="handleOpenFilterModal()" class="nav-pwa-link">
                <i class="fas fa-list-check"></i> Riwayat
            </a>
            <a href="javascript:void(0)" onclick="handleOpenPassModal()" class="nav-pwa-link">
                <i class="fas fa-shield-halved"></i> Profil
            </a>
            <a href="<?= base_url('logoutpwa') ?>" class="nav-pwa-link text-danger">
                <i class="fas fa-power-off"></i> Out
            </a>
        </nav>

    </div>

    <div class="modal fade" id="modal-special-permit" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered mx-3">
            <div class="modal-content shadow-lg border-0" style="border-radius: 28px;">
                <div class="modal-header border-0 p-4">
                    <h5 class="fw-800 mb-0" id="permit-label-header">Form Pengajuan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="form-submit-special-permit" enctype="multipart/form-data">
                    <div class="modal-body px-4 pb-4 pt-0">
                        <input type="hidden" name="kategori" id="permit-hidden-kategori">

                        <div class="mb-3">
                            <label class="small fw-800 text-muted mb-2">Pilih Jenis Spesifik</label>
                            <select name="sub_kategori" id="permit-sub-kategori" class="form-select border-0 bg-light py-3 rounded-4 fw-600 shadow-sm" onchange="togglePermitLogic()" required>
                            </select>
                        </div>

                        <div class="mb-3" id="permit-wrapper-slot" style="display: none;">
                            <label class="small fw-800 text-muted mb-2">Waktu Yang Diajukan</label>
                            <select name="slot_waktu" class="form-select border-0 bg-light py-3 rounded-4 shadow-sm">
                                <option value="Penuh">Satu Hari Penuh</option>
                                <option value="Pagi">Sesi Pagi (Absen Masuk)</option>
                                <option value="Siang">Sesi Siang (Absen Ishoma)</option>
                                <option value="Sore">Sesi Sore (Absen Pulang)</option>
                            </select>
                        </div>

                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="small fw-800 text-muted mb-2">Dari Tanggal</label>
                                <input type="date" name="tgl_mulai" class="form-control border-0 bg-light py-3 rounded-4 shadow-sm" value="<?= date('Y-m-d') ?>" required>
                            </div>
                            <div class="col-6" id="permit-wrapper-tgl-selesai">
                                <label class="small fw-800 text-muted mb-2">Sampai Tanggal</label>
                                <input type="date" name="tgl_selesai" class="form-control border-0 bg-light py-3 rounded-4 shadow-sm" value="<?= date('Y-m-d') ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-800 text-muted mb-2">Alasan / Keterangan</label>
                            <textarea name="keterangan" class="form-control border-0 bg-light rounded-4 shadow-sm" rows="3" placeholder="Tulis alasan lengkap Anda..." required></textarea>
                        </div>

                        <div class="mb-4">
                            <label class="small fw-800 text-muted mb-2">Unggah Bukti (JPG/PDF)</label>
                            <input type="file" name="file_bukti" class="form-control border-0 bg-light py-2 rounded-4 shadow-sm" accept="image/*,application/pdf" required>
                        </div>

                        <button type="submit" class="btn btn-success w-100 rounded-pill fw-800 py-3 shadow-lg fs-6">KIRIM PENGAJUAN</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modal-pwa-password" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered mx-3">
            <div class="modal-content shadow-lg border-0" style="border-radius: 28px;">
                <div class="modal-header border-0 p-4">
                    <h6 class="fw-800 mb-0">UBAH KATA SANDI</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="form-pwa-update-pass">
                    <div class="modal-body px-4 pb-4 pt-0">
                        <div class="mb-3">
                            <input type="password" name="lama" class="form-control border-0 bg-light py-3 rounded-4 shadow-sm" placeholder="Kata Sandi Lama" required>
                        </div>
                        <div class="mb-3">
                            <input type="password" name="baru" class="form-control border-0 bg-light py-3 rounded-4 shadow-sm" placeholder="Kata Sandi Baru" required minlength="6">
                        </div>
                        <div class="mb-4">
                            <input type="password" name="konfirmasi" class="form-control border-0 bg-light py-3 rounded-4 shadow-sm" placeholder="Ulangi Sandi Baru" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 rounded-pill fw-800 py-3 shadow-lg">SIMPAN PERUBAHAN</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modal-pwa-filter" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered mx-3">
            <div class="modal-content shadow-lg border-0" style="border-radius: 28px;">
                <div class="modal-header border-0 p-4">
                    <h6 class="fw-800 mb-0">FILTER RIWAYAT</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="<?= base_url('pwa') ?>" method="GET">
                    <div class="modal-body px-4 pb-4 pt-0">
                        <div class="mb-3">
                            <select name="bulan" class="form-select border-0 bg-light py-3 rounded-4 shadow-sm" required>
                                <?php foreach ($bulan_indo as $num => $txt): if ($num == 0) continue; ?>
                                    <option value="<?= $num ?>" <?= (date('n') == $num) ? 'selected' : '' ?>><?= $txt ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-4">
                            <select name="tahun" class="form-select border-0 bg-light py-3 rounded-4 shadow-sm" required>
                                <option value="<?= date('Y') ?>"><?= date('Y') ?></option>
                                <option value="<?= date('Y') - 1 ?>"><?= date('Y') - 1 ?></option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 rounded-pill fw-800 py-3 shadow-lg">TAMPILKAN DATA</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        /**
         * 1. GLOBAL STATE TRACKING & PENGUNCI DOUBLE SUBMIT (LOCKS)
         */
        let pwaFaceDetectorReady = false;
        let pwaFaceMatcherObject = null;
        let pwaActiveAbsenMode = 'reguler';
        let pwaActiveApelId = null;

        // Kunci proses untuk mencegah spam eksekusi ganda
        let isBiometricProcessing = false;
        let isSendingToServer = false;

        // Tantangan Liveness
        const livenessChallenges = [{
            id: 'SMILE',
            label: 'Silakan TERSENYUM Lebar'
        }];
        let currentChallenge = null;

        /**
         * 2. INITIALIZATION
         
        document.addEventListener('DOMContentLoaded', function() {
            // Sync Jam Digital
            setInterval(() => {
                document.getElementById('pwa-digital-clock').innerText = new Date().toLocaleTimeString('id-ID', {
                    timeZone: 'Asia/Makassar', hour12: false
                });
            }, 1000);
        });
*/
        /**
         * 3. AI CORE
         */
        async function loadBiometricModels() {
            const URL_MODELS = 'https://justadudewhohacks.github.io/face-api.js/models';
            try {
                await Promise.all([
                    faceapi.nets.tinyFaceDetector.loadFromUri(URL_MODELS),
                    faceapi.nets.faceLandmark68Net.loadFromUri(URL_MODELS),
                    faceapi.nets.faceRecognitionNet.loadFromUri(URL_MODELS),
                    faceapi.nets.faceExpressionNet.loadFromUri(URL_MODELS)
                ]);

                const rawVector = '<?= $face_data ?>';
                if (rawVector) {
                    const parsed = new Float32Array(JSON.parse(rawVector));
                    // [PERBAIKAN 1]: Mengubah batas threshold dari 0.55 menjadi 0.58 agar sedikit lebih toleran terhadap cahaya
                    pwaFaceMatcherObject = new faceapi.FaceMatcher(new faceapi.LabeledFaceDescriptors('ASN_USER', [parsed]), 0.45);
                }
                pwaFaceDetectorReady = true;
            } catch (err) {
                console.error("AI Error:", err);
            }
        }
        loadBiometricModels();

        /**
         * 4. MAIN FLOW DETEKSI (AUTO ENROLLMENT)
         */
        const btnMain = document.getElementById('btn-trigger-attendance');
        if (btnMain) {
            btnMain.onclick = () => {
                pwaActiveAbsenMode = 'reguler';
                startBiometricFlow();
            };
        }

        function handleStartVerification(mode, id) {
            pwaActiveAbsenMode = mode;
            pwaActiveApelId = id;
            startBiometricFlow();
        }

        async function startBiometricFlow() {
            if (!pwaFaceDetectorReady) return Swal.fire('Wait', 'Sensor sedang inisialisasi...', 'info');

            // Buka kunci keamanan di awal sesi
            isBiometricProcessing = false;
            isSendingToServer = false;

            const overlay = document.getElementById('camera-verification-overlay');
            const video = document.getElementById('camera-stream');
            const statusLabel = document.getElementById('ai-status-label');

            let isEnrollmentMode = false;

            if (!pwaFaceMatcherObject) {
                // JIKA BELUM PUNYA WAJAH -> JALUR PENDAFTARAN (ENROLLMENT)
                isEnrollmentMode = true;
                Swal.fire({
                    title: 'Wajah Belum Terdaftar!',
                    // [PERBAIKAN 2]: Menambahkan instruksi wajib senyum di Alert
                    text: 'Sistem mendeteksi Anda belum mendaftarkan wajah. Posisikan wajah ke kamera lalu TERSENYUM LEBAR, kami akan menyimpannya otomatis.',
                    icon: 'info',
                    confirmButtonText: 'Mulai Rekam Wajah',
                    confirmButtonColor: '#155724'
                }).then((result) => {
                    if (result.isConfirmed) {
                        statusLabel.innerHTML = '<i class="fas fa-smile me-2 text-primary"></i> Posisikan Wajah ke Tengah & TERSENYUM...';
                        statusLabel.className = "alert alert-primary rounded-4 shadow-lg border-0 fw-bold py-3";
                        overlay.style.display = 'block';
                        mulaiKamera(video, statusLabel, isEnrollmentMode);
                    }
                });
            } else {
                // JIKA SUDAH PUNYA WAJAH -> JALUR ABSENSI
                currentChallenge = livenessChallenges[0]; // Tantangan Senyum
                statusLabel.innerHTML = '<i class="fas fa-circle-notch fa-spin me-2 text-success"></i> Menyiapkan Kamera...';
                statusLabel.className = "alert alert-light rounded-4 shadow-lg fw-bold py-3 px-4 border-0";
                overlay.style.display = 'block';
                mulaiKamera(video, statusLabel, isEnrollmentMode);
            }
        }

        async function mulaiKamera(video, statusLabel, isEnrollmentMode) {
            try {
                // Kamera Resolusi Ringan
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        facingMode: 'user',
                        width: {
                            ideal: 640
                        },
                        height: {
                            ideal: 480
                        }
                    }
                });
                video.srcObject = stream;

                video.onloadedmetadata = () => {
                    video.play();
                };

                // Interval Scanner 600ms (Sangat Ringan)
                const detectionInterval = setInterval(async () => {
                    if (isBiometricProcessing) return;

                    try {
                        const result = await faceapi.detectSingleFace(video, new faceapi.TinyFaceDetectorOptions({
                                inputSize: 160
                            }))
                            .withFaceLandmarks().withFaceDescriptor().withFaceExpressions();

                        if (result) {

                            // ==============================================================
                            // JALUR 1: MODE PENDAFTARAN WAJAH (ENROLLMENT)
                            // ==============================================================
                            if (isEnrollmentMode) {
                                // [PERBAIKAN 3]: WAJIB SENYUM saat pendaftaran agar vektor sejajar saat absen nanti
                                if (result.detection.score > 0.80 && result.expressions.happy > 0.80) {
                                    isBiometricProcessing = true;
                                    clearInterval(detectionInterval);

                                    statusLabel.innerHTML = '<i class="fas fa-spinner fa-spin me-2 text-warning"></i> Menyimpan Wajah Anda...';
                                    statusLabel.className = "alert alert-warning rounded-4 shadow-lg border-0 fw-bold py-3";

                                    const descriptorArray = Array.from(result.descriptor);
                                    const faceDataJSON = JSON.stringify(descriptorArray);

                                    stream.getTracks().forEach(t => t.stop());

                                    const fd = new FormData();
                                    fd.append('face_vector', faceDataJSON);

                                    fetch('<?= base_url('pwa/simpan_wajah_pwa') ?>', {
                                            method: 'POST',
                                            body: fd,
                                            headers: {
                                                'X-Requested-With': 'XMLHttpRequest'
                                            }
                                        })
                                        .then(r => r.json()).then(res => {
                                            document.getElementById('camera-verification-overlay').style.display = 'none';
                                            if (res.status === 'success') {
                                                Swal.fire('Berhasil!', 'Wajah Anda telah terdaftar. Silakan tekan tombol PRESENSI kembali untuk melakukan absen.', 'success')
                                                    .then(() => location.reload());
                                            } else {
                                                Swal.fire('Gagal', res.message, 'error');
                                            }
                                        }).catch(() => {
                                            document.getElementById('camera-verification-overlay').style.display = 'none';
                                            Swal.fire('Error', 'Gagal menghubungi server.', 'error');
                                        });
                                } else {
                                    // Beri tahu user jika belum senyum
                                    if (!statusLabel.innerText.includes("TERSENYUM")) {
                                        statusLabel.innerHTML = '<i class="fas fa-smile me-2 text-primary"></i> Silakan TERSENYUM LEBAR untuk Daftar...';
                                        statusLabel.className = "alert alert-primary rounded-4 shadow-lg border-0 fw-bold py-3";
                                    }
                                }

                            }
                            // ==============================================================
                            // JALUR 2: MODE ABSENSI NORMAL
                            // ==============================================================
                            else {
                                const match = pwaFaceMatcherObject.findBestMatch(result.descriptor);
                                if (match.label !== 'unknown') {
                                    statusLabel.innerHTML = `<strong>VALIDASI:</strong> ${currentChallenge.label}`;
                                    statusLabel.className = "alert alert-warning rounded-4 shadow-lg border-0 fw-bold py-3";

                                    if (result.expressions.happy > 0.80) {
                                        isBiometricProcessing = true;
                                        clearInterval(detectionInterval);

                                        statusLabel.innerHTML = "BERHASIL! Mencari Lokasi...";
                                        statusLabel.className = "alert alert-success rounded-4 shadow-lg border-0 fw-bold py-3";
                                        setTimeout(() => finalizeAttendance(stream), 1000);
                                    }
                                } else {
                                    statusLabel.innerText = "WAJAH TIDAK DIKENALI!";
                                    statusLabel.className = "alert alert-danger rounded-4 shadow-lg border-0 fw-bold py-3";
                                }
                            }
                        } else {
                            if (!statusLabel.innerText.includes("TIDAK DIKENALI")) {
                                statusLabel.innerHTML = '<i class="fas fa-expand me-2 text-primary"></i> Posisikan Wajah ke Tengah...';
                                statusLabel.className = "alert alert-light rounded-4 shadow-lg border-0 fw-bold py-3";
                            }
                        }
                    } catch (e) {
                        // Abaikan error saat memuat video
                    }
                }, 600);

            } catch (err) {
                document.getElementById('camera-verification-overlay').style.display = 'none';
                Swal.fire('Error', 'Gagal akses kamera. Pastikan izin kamera aktif.', 'error');
            }
        }

        // ==============================================================
        // FOKUS GPS - LOGIKA FALLBACK (HIGH -> STANDARD ACCURACY)
        // ==============================================================
        function finalizeAttendance(stream) {
            let lokasiDitemukan = false;

            const sendDataToServer = (lat, lng) => {
                // Cegah pengiriman data ganda jika salah satu metode GPS tembus bersamaan
                if (isSendingToServer || lokasiDitemukan) return;

                isSendingToServer = true;
                lokasiDitemukan = true;

                stream.getTracks().forEach(t => t.stop()); // Matikan kamera agar HP tidak lag

                const fd = new FormData();
                fd.append('latitude', lat);
                fd.append('longitude', lng);
                fd.append('nip', '<?= $pegawai['nip'] ?>');
                fd.append('jam_masuk', '<?= $jam_sekarang ?>');

                let url = '<?= base_url('pwa/submit_absen') ?>';
                if (pwaActiveAbsenMode === 'apel') {
                    url = '<?= base_url('pwa/submit_absen_apel') ?>';
                    fd.append('id_apel', pwaActiveApelId);
                }

                fetch(url, {
                        method: 'POST',
                        body: fd,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                    .then(r => r.json()).then(data => {
                        document.getElementById('camera-verification-overlay').style.display = 'none';
                        if (data.status === 'success') {
                            Swal.fire('Sukses', data.message, 'success').then(() => {
                                // Jangan pakai reload(), tapi paksa arahkan ulang ke URL bersih PWA
                                window.location.replace('<?= base_url('pwa') ?>');
                            });
                        } else {
                            // Buka kunci lagi jika ditolak server (misal di luar radius), agar bisa mencoba lagi.
                            isSendingToServer = false;
                            lokasiDitemukan = false;
                            Swal.fire('Gagal', data.message, 'error');
                        }
                    }).catch(() => {
                        isSendingToServer = false;
                        lokasiDitemukan = false;
                        Swal.fire('Error', 'Gagal mengirim data ke server.', 'error').then(() => location.reload());
                    });
            };

            const onCompleteFailure = (err) => {
                if (lokasiDitemukan) return; // Jika sudah terkirim oleh metode lain, abaikan error ini.

                stream.getTracks().forEach(t => t.stop());
                let pesanError = 'Gagal mendeteksi lokasi. Pastikan GPS aktif dan perizinan browser diizinkan.';
                if (err.code === 1) pesanError = "Izin lokasi ditolak oleh browser Anda.";
                if (err.code === 2) pesanError = "Sinyal GPS tidak tersedia.";

                Swal.fire('GPS Gagal', pesanError, 'error').then(() => location.reload());
            };

            // Strategi Balapan: Tembak Standard Accuracy (BTS/Wifi) SEKALIGUS High Accuracy (Satelit)
            // Mana yang merespons duluan, itu yang kita eksekusi.

            // 1. Tembak High Accuracy (Satelit - Lebih akurat tapi lambat di dalam gedung)
            navigator.geolocation.getCurrentPosition(
                (pos) => sendDataToServer(pos.coords.latitude, pos.coords.longitude),
                (err) => {
                    console.warn("Satelit GPS lemah.");
                }, // Abaikan error, biarkan metode 2 bekerja
                {
                    enableHighAccuracy: true,
                    timeout: 5000,
                    maximumAge: 0
                }
            );

            // 2. Tembak Standard Accuracy (Tower Seluler/Wifi - Super cepat tapi sedikit kurang presisi)
            // Sengaja diberi jeda 1 detik agar memberi kesempatan High Accuracy menang jika di luar ruangan.
            setTimeout(() => {
                if (!lokasiDitemukan) {
                    navigator.geolocation.getCurrentPosition(
                        (pos) => sendDataToServer(pos.coords.latitude, pos.coords.longitude),
                        onCompleteFailure, {
                            enableHighAccuracy: false,
                            timeout: 5000,
                            maximumAge: 10000
                        }
                    );
                }
            }, 1000);
        }

        /**
         * 5. PERMIT LOGIC 
         */
        function handleFormSpecial(kat) {
            const hidden = document.getElementById('permit-hidden-kategori');
            const label = document.getElementById('permit-label-header');
            const subSelect = document.getElementById('permit-sub-kategori');
            hidden.value = kat;
            label.innerText = "Pengajuan " + kat;

            let options = "";
            if (kat === 'Sakit') options = '<option value="Sakit Penuh">Sakit (Satu Hari Penuh)</option>';
            else if (kat === 'Izin') options = '<option value="Izin Penuh">Izin Penuh</option><option value="Setengah Hari">Izin Setengah Hari</option>';
            else if (kat === 'Tugas Luar') options = '<option value="Luar Daerah">TL Luar Daerah</option><option value="Dalam Daerah">TL Dalam Daerah</option>';

            subSelect.innerHTML = options;
            togglePermitLogic();
            new bootstrap.Modal(document.getElementById('modal-special-permit')).show();
        }

        function togglePermitLogic() {
            const sub = document.getElementById('permit-sub-kategori').value;
            // Jika Setengah Hari ATAU Dalam Daerah, tampilkan pilihan slot waktu
            document.getElementById('permit-wrapper-slot').style.display = (sub === 'Setengah Hari' || sub === 'Dalam Daerah') ? 'block' : 'none';

            // Logika Tanggal Selesai:
            // Biasanya TL Dalam Daerah cuma sehari, tapi kalau dia pilih "Penuh", mungkin butuh range tanggal? 
            // Untuk amannya, kita TAMPILKAN saja tanggal selesai untuk TL Dalam Daerah agar fleksibel (backdate juga bisa lebih enak).
            // Jadi yang di-hidden hanya "Setengah Hari" (karena izin setengah hari pasti di tanggal yang sama).
            document.getElementById('permit-wrapper-tgl-selesai').style.display = (sub === 'Setengah Hari') ? 'none' : 'block';
        }

        document.getElementById('form-submit-special-permit').onsubmit = function(e) {
            e.preventDefault();
            Swal.fire({
                title: 'Mengirim...',
                didOpen: () => Swal.showLoading()
            });
            const formData = new FormData(this);

            const elementNip = document.querySelector('.nip');
            if (elementNip) {
                formData.append('nip_manual', elementNip.innerText.replace('NIP. ', '').trim());
            }

            fetch('<?= base_url('pwa/submit_izin_pwa') ?>', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                .then(async (r) => {
                    // Cek jika balasan dari server bukan 200 OK (contoh: error 500 karena file kebesaran)
                    if (!r.ok) { throw new Error('Terjadi kesalahan di server/file terlalu besar.'); }
                    return r.json();
                })
                .then(res => {
                    if (res.status === 'success') {
                        Swal.fire('Berhasil', res.message, 'success').then(() => window.location.replace('<?= base_url('pwa') ?>'));
                    } else {
                        Swal.fire('Gagal', res.message, 'warning');
                    }
                }).catch((err) => {
                    Swal.fire('Koneksi Gagal', 'Gagal mengirim data. Pastikan internet Anda stabil dan ukuran Foto/PDF tidak lebih dari 2 MB.', 'error');
                });
        };

        function handleUIRefresh(btn) {
            btn.querySelector('i').classList.add('fa-spin');
            setTimeout(() => location.reload(), 600);
        }

        function handleOpenPassModal() {
            new bootstrap.Modal(document.getElementById('modal-pwa-password')).show();
        }

        function handleOpenFilterModal() {
            new bootstrap.Modal(document.getElementById('modal-pwa-filter')).show();
        }
    </script>
</body>

</html>