<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';

date_default_timezone_set('Asia/Makassar');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (!function_exists('esc')) {
    function esc($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$act = $_GET['a'] ?? 'list';

if (!in_array($act, ['list', 'detail', 'buat', 'status', 'delete'], true)) {
    $act = 'list';
}

/*
|--------------------------------------------------------------------------
| KONFIGURASI
|--------------------------------------------------------------------------
| Sesuaikan $adminPagePrefix jika URL file admin surat bukan /pages.
| Contoh:
| - Jika URL print: https://adminmambu.sidea.id/pages/surat_usaha_print.php
|   gunakan /pages
| - Jika URL print: https://adminmambu.sidea.id/surat_usaha_print.php
|   gunakan ''
*/
$adminPagePrefix = '/modules';

$daftarSurat = [
    'surat_domisili' => [
        'nama' => 'Surat Keterangan Domisili',
        'ikon' => 'ri-home-4-fill',
        'template' => 'surat_domisili.php',
        'print' => 'surat_domisili_print.php',
        'table' => 'surat_keterangan_domisili',
    ],
    'surat_tidak_mampu' => [
        'nama' => 'Surat Keterangan Tidak Mampu',
        'ikon' => 'ri-hand-heart-fill',
        'template' => 'surat_tidak_mampu.php',
        'print' => 'surat_tidak_mampu_print.php',
        'table' => 'surat_tidak_mampu',
    ],
    'surat_usaha' => [
        'nama' => 'Surat Keterangan Usaha',
        'ikon' => 'ri-store-2-fill',
        'template' => 'surat_usaha.php',
        'print' => 'surat_usaha_print.php',
        'table' => 'surat_usaha',
    ],
    'surat_belum_menikah' => [
        'nama' => 'Surat Keterangan Belum Menikah',
        'ikon' => 'ri-user-heart-fill',
        'template' => 'surat_belum_menikah.php',
        'print' => 'surat_belum_menikah_print.php',
        'table' => 'surat_belum_menikah',
    ],
    'surat_belum_bekerja' => [
        'nama' => 'Surat Keterangan Belum Bekerja',
        'ikon' => 'ri-briefcase-line',
        'template' => 'surat_belum_bekerja.php',
        'print' => 'surat_belum_bekerja_print.php',
        'table' => 'surat_belum_bekerja',
    ],
    'surat_kelakuan_baik' => [
        'nama' => 'Surat Keterangan Kelakuan Baik',
        'ikon' => 'ri-shield-check-fill',
        'template' => 'surat_kelakuan_baik.php',
        'print' => 'surat_kelakuan_baik_print.php',
        'table' => 'surat_kelakuan_baik',
    ],
    'surat_hilang' => [
        'nama' => 'Surat Keterangan Kehilangan',
        'ikon' => 'ri-folder-warning-fill',
        'template' => 'surat_hilang.php',
        'print' => 'surat_hilang_print.php',
        'table' => 'surat_keterangan_hilang',
    ],
    'surat_pindah' => [
        'nama' => 'Surat Pengantar Pindah',
        'ikon' => 'ri-truck-fill',
        'template' => 'surat_pindah.php',
        'print' => 'surat_pindah_print.php',
        'table' => 'surat_pindah',
    ],
    'surat_nikah' => [
        'nama' => 'Surat Pengantar Nikah',
        'ikon' => 'ri-heart-2-fill',
        'template' => 'surat_nikah.php',
        'print' => 'surat_nikah_print.php',
        'table' => 'surat_nikah',
    ],
    'surat_penghasilan_ortu' => [
        'nama' => 'Surat Keterangan Penghasilan Orang Tua',
        'ikon' => 'ri-money-dollar-circle-fill',
        'template' => 'surat_penghasilan_ortu.php',
        'print' => 'surat_penghasilan_ortu_print.php',
        'table' => 'surat_penghasilan_ortu',
    ],
    'surat_merantau' => [
        'nama' => 'Surat Keterangan Merantau',
        'ikon' => 'ri-road-map-fill',
        'template' => 'surat_merantau.php',
        'print' => 'surat_merantau_print.php',
        'table' => 'surat_merantau',
    ],
    'surat_ijin_keramaian' => [
        'nama' => 'Surat Izin Keramaian',
        'ikon' => 'ri-megaphone-fill',
        'template' => 'surat_ijin_keramaian.php',
        'print' => 'surat_ijin_keramaian_print.php',
        'table' => 'surat_ijin_keramaian',
    ],
    'surat_kuasa' => [
        'nama' => 'Surat Kuasa',
        'ikon' => 'ri-file-shield-2-fill',
        'template' => 'surat_kuasa.php',
        'print' => 'surat_kuasa_print.php',
        'table' => 'surat_kuasa',
    ],
    'surat_pengantar_kayu' => [
        'nama' => 'Surat Pengantar Kayu',
        'ikon' => 'ri-plant-fill',
        'template' => 'surat_pengantar_kayu.php',
        'print' => 'surat_pengantar_kayu_print.php',
        'table' => 'surat_pengantar_kayu',
    ],
    'surat_pengantar_hewan' => [
        'nama' => 'Surat Pengantar Hewan',
        'ikon' => 'ri-bear-smile-fill',
        'template' => 'surat_pengantar_hewan.php',
        'print' => 'surat_pengantar_hewan_print.php',
        'table' => 'surat_pengantar_hewan',
    ],
    'surat_ahli_waris' => [
        'nama' => 'Surat Keterangan Ahli Waris',
        'ikon' => 'ri-team-fill',
        'template' => 'surat_ahli_waris.php',
        'print' => 'surat_ahli_waris_print.php',
        'table' => 'surat_ahli_waris',
    ],
    'surat_pembagian_waris' => [
        'nama' => 'Surat Pembagian Waris',
        'ikon' => 'ri-scales-3-fill',
        'template' => 'surat_pembagian_waris.php',
        'print' => 'surat_pembagian_waris_print.php',
        'table' => 'surat_pembagian_waris',
    ],
    'surat_gadai' => [
        'nama' => 'Surat Gadai',
        'ikon' => 'ri-file-lock-fill',
        'template' => 'surat_gadai.php',
        'print' => 'surat_gadai_print.php',
        'table' => 'surat_gadai',
    ],
    'surat_undangan' => [
        'nama' => 'Surat Undangan',
        'ikon' => 'ri-mail-send-fill',
        'template' => 'surat_undangan.php',
        'print' => 'surat_undangan_print.php',
        'table' => 'surat_undangan',
    ],
    'surat_pernyataan_kesanggupan' => [
        'nama' => 'Surat Pernyataan Kesanggupan',
        'ikon' => 'ri-file-check-fill',
        'template' => 'surat_pernyataan_kesanggupan.php',
        'print' => 'surat_pernyataan_kesanggupan_print.php',
        'table' => 'surat_pernyataan_kesanggupan',
    ],
];

if (!isset($_SESSION['csrf_admin_layanan_mandiri'])) {
    $_SESSION['csrf_admin_layanan_mandiri'] = bin2hex(random_bytes(32));
}

$csrfToken = $_SESSION['csrf_admin_layanan_mandiri'];

/* =========================================================
   FUNGSI BANTU
========================================================= */

function layanan_redirect($url)
{
    header('Location: '.$url);
    exit;
}

function layanan_bulan_romawi($bulan)
{
    $romawi = [
        1 => 'I',
        2 => 'II',
        3 => 'III',
        4 => 'IV',
        5 => 'V',
        6 => 'VI',
        7 => 'VII',
        8 => 'VIII',
        9 => 'IX',
        10 => 'X',
        11 => 'XI',
        12 => 'XII',
    ];

    return $romawi[(int)$bulan] ?? '';
}

function layanan_tanggal_indo($tanggal, $denganJam = true)
{
    if (!$tanggal) {
        return '-';
    }

    $waktu = strtotime((string)$tanggal);

    if (!$waktu) {
        return '-';
    }

    $bulanIndonesia = [
        1  => 'Januari',
        2  => 'Februari',
        3  => 'Maret',
        4  => 'April',
        5  => 'Mei',
        6  => 'Juni',
        7  => 'Juli',
        8  => 'Agustus',
        9  => 'September',
        10 => 'Oktober',
        11 => 'November',
        12 => 'Desember',
    ];

    $hasil = date('j', $waktu).' '.$bulanIndonesia[(int)date('n', $waktu)].' '.date('Y', $waktu);

    if ($denganJam) {
        $hasil .= ' '.date('H.i', $waktu).' WITA';
    }

    return $hasil;
}

function layanan_status_label($status)
{
    $map = [
        'diajukan' => 'Diajukan',
        'diproses' => 'Diproses',
        'selesai' => 'Selesai',
        'ditolak' => 'Ditolak',
    ];

    return $map[$status] ?? ucfirst((string)$status);
}

function layanan_status_icon($status)
{
    $map = [
        'diajukan' => 'ri-send-plane-fill',
        'diproses' => 'ri-loader-4-line',
        'selesai' => 'ri-checkbox-circle-fill',
        'ditolak' => 'ri-close-circle-fill',
    ];

    return $map[$status] ?? 'ri-information-fill';
}

function layanan_status_class($status)
{
    $map = [
        'diajukan' => 'layanan-status-diajukan',
        'diproses' => 'layanan-status-diproses',
        'selesai' => 'layanan-status-selesai',
        'ditolak' => 'layanan-status-ditolak',
    ];

    return $map[$status] ?? 'layanan-status-diajukan';
}

function layanan_inisial($nama)
{
    $nama = trim((string)$nama);

    if ($nama === '') {
        return 'W';
    }

    if (function_exists('mb_substr')) {
        return strtoupper(mb_substr($nama, 0, 1, 'UTF-8'));
    }

    return strtoupper(substr($nama, 0, 1));
}

function layanan_decode_json($json)
{
    $data = json_decode((string)$json, true);

    return is_array($data) ? $data : [];
}

function layanan_alamat_warga($warga)
{
    if (!$warga || !is_array($warga)) {
        return '-';
    }

    $bagian = [];

    foreach (['dusun', 'desa', 'kecamatan', 'kabupaten', 'provinsi'] as $key) {
        if (!empty($warga[$key])) {
            $bagian[] = $warga[$key];
        }
    }

    return $bagian ? implode(', ', $bagian) : '-';
}

function layanan_ttl_warga($warga)
{
    if (!$warga || !is_array($warga)) {
        return '-';
    }

    $tempat = trim((string)($warga['tempat_lahir'] ?? ''));
    $tanggal = trim((string)($warga['tanggal_lahir'] ?? ''));

    if ($tanggal !== '') {
        $tanggal = layanan_tanggal_indo($tanggal, false);
    }

    if ($tempat !== '' && $tanggal !== '') {
        return $tempat.', '.$tanggal;
    }

    return $tempat !== '' ? $tempat : ($tanggal !== '' ? $tanggal : '-');
}

function layanan_umur_warga($warga)
{
    $tanggal = trim((string)($warga['tanggal_lahir'] ?? ''));

    if ($tanggal === '') {
        return 0;
    }

    try {
        $lahir = new DateTime($tanggal);
        $sekarang = new DateTime();
        return (int)$lahir->diff($sekarang)->y;
    } catch (Throwable $e) {
        return 0;
    }
}

function layanan_safe_identifier($identifier)
{
    $identifier = (string)$identifier;

    if (!preg_match('/^[a-zA-Z0-9_]+$/', $identifier)) {
        throw new RuntimeException('Nama tabel atau kolom tidak valid.');
    }

    return $identifier;
}

function layanan_table_exists($mysqli, $table)
{
    $table = layanan_safe_identifier($table);

    $result = $mysqli->query("SHOW TABLES LIKE '".$mysqli->real_escape_string($table)."'");

    return $result && $result->num_rows > 0;
}

function layanan_column_exists($mysqli, $table, $column)
{
    $table = layanan_safe_identifier($table);
    $column = layanan_safe_identifier($column);

    $result = $mysqli->query("SHOW COLUMNS FROM `".$table."` LIKE '".$mysqli->real_escape_string($column)."'");

    return $result && $result->num_rows > 0;
}

function layanan_add_column_if_missing($mysqli, $table, $column, $definition)
{
    $table = layanan_safe_identifier($table);
    $column = layanan_safe_identifier($column);

    if (!layanan_column_exists($mysqli, $table, $column)) {
        $mysqli->query("ALTER TABLE `".$table."` ADD COLUMN `".$column."` ".$definition);
    }
}

function layanan_ensure_table($mysqli)
{
    $mysqli->query("
        CREATE TABLE IF NOT EXISTS layanan_surat_pengajuan (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT,
            kode_pengajuan VARCHAR(40) NOT NULL,
            penduduk_id INT UNSIGNED NOT NULL,
            nik VARCHAR(20) NOT NULL,
            nomor_kk VARCHAR(20) NOT NULL,
            nama_lengkap VARCHAR(180) NOT NULL,
            jenis_surat VARCHAR(100) NOT NULL,
            nama_surat VARCHAR(180) NOT NULL,
            keperluan TEXT NOT NULL,
            data_tambahan LONGTEXT NULL,
            status ENUM('diajukan','diproses','selesai','ditolak') NOT NULL DEFAULT 'diajukan',
            catatan_admin TEXT NULL,
            file_surat VARCHAR(255) NULL,
            nomor_surat VARCHAR(120) NULL,
            generated_table VARCHAR(120) NULL,
            generated_id INT UNSIGNED NULL,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY uq_layanan_surat_kode (kode_pengajuan),
            KEY idx_layanan_surat_penduduk (penduduk_id),
            KEY idx_layanan_surat_nik_kk (nik, nomor_kk),
            KEY idx_layanan_surat_status (status, created_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    layanan_add_column_if_missing($mysqli, 'layanan_surat_pengajuan', 'nomor_surat', 'VARCHAR(120) NULL');
    layanan_add_column_if_missing($mysqli, 'layanan_surat_pengajuan', 'generated_table', 'VARCHAR(120) NULL');
    layanan_add_column_if_missing($mysqli, 'layanan_surat_pengajuan', 'generated_id', 'INT UNSIGNED NULL');
}

function layanan_bind_dynamic($stmt, $types, &$values)
{
    $params = [];
    $params[] = &$types;

    foreach ($values as $key => &$value) {
        $params[] = &$value;
    }

    return call_user_func_array([$stmt, 'bind_param'], $params);
}

function layanan_insert_row($mysqli, $table, $data)
{
    if (!$data || !is_array($data)) {
        throw new RuntimeException('Data insert kosong.');
    }

    $table = layanan_safe_identifier($table);

    $columns = [];
    $placeholders = [];
    $values = [];
    $types = '';

    foreach ($data as $column => $value) {
        $column = layanan_safe_identifier($column);

        $columns[] = '`'.$column.'`';
        $placeholders[] = '?';

        if (is_int($value)) {
            $types .= 'i';
            $values[] = $value;
        } elseif (is_float($value)) {
            $types .= 'd';
            $values[] = $value;
        } else {
            $types .= 's';
            $values[] = (string)$value;
        }
    }

    $sql = "INSERT INTO `".$table."` (".implode(', ', $columns).") VALUES (".implode(', ', $placeholders).")";

    $stmt = $mysqli->prepare($sql);

    if (!$stmt) {
        throw new RuntimeException($mysqli->error);
    }

    layanan_bind_dynamic($stmt, $types, $values);

    if (!$stmt->execute()) {
        $error = $stmt->error;
        $stmt->close();
        throw new RuntimeException($error);
    }

    $id = (int)$stmt->insert_id;
    $stmt->close();

    return $id;
}

function layanan_next_id($mysqli, $table)
{
    $table = layanan_safe_identifier($table);

    if (!layanan_table_exists($mysqli, $table)) {
        return 1;
    }

    $result = $mysqli->query("
        SELECT id
        FROM `".$table."`
        ORDER BY id DESC
        LIMIT 1
    ");

    if ($result && $row = $result->fetch_assoc()) {
        return (int)$row['id'] + 1;
    }

    return 1;
}

function layanan_nomor_surat($mysqli, $jenis, $table)
{
    $urut = layanan_next_id($mysqli, $table);
    $romawi = layanan_bulan_romawi((int)date('n'));
    $tahun = date('Y');

    switch ($jenis) {
        case 'surat_domisili':
            return '017/'.$urut.'/Ds.M/'.$romawi.'/'.$tahun;

        case 'surat_tidak_mampu':
            return '400/'.$urut.'/Ds.M/'.$romawi.'/'.$tahun;

        case 'surat_usaha':
            return sprintf('510.1/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_belum_menikah':
            return sprintf('145/%03d/DM/%s/%s', $urut, $romawi, $tahun);

        case 'surat_belum_bekerja':
            return sprintf('145/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_kelakuan_baik':
            return sprintf('145/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_hilang':
            return $urut.'/145/Ds.M/'.$romawi.'/'.$tahun;

        case 'surat_pindah':
            return sprintf('%03d/475/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_nikah':
            return sprintf('474.2/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_penghasilan_ortu':
            return '031/'.$urut.'/Ds.M/'.date('m').'/'.$tahun;

        case 'surat_merantau':
            return sprintf('044/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_ijin_keramaian':
            return sprintf('001/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_kuasa':
            return sprintf('SK/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_pengantar_kayu':
            return '03 / 552 / Ds.M / '.$romawi.' / '.$tahun;

        case 'surat_pengantar_hewan':
            return sprintf('524.2/%02d/DM/%s/%s', $urut, $romawi, $tahun);

        case 'surat_ahli_waris':
            return sprintf('AW/%03d/Ds.M/%s/%s', $urut, $romawi, $tahun);

        case 'surat_undangan':
            return sprintf('%02d/%03d/Ds.M/%s/%s', $urut, $urut, $romawi, $tahun);

        case 'surat_pernyataan_kesanggupan':
            return str_pad((string)$urut, 3, '0', STR_PAD_LEFT).'/SPK/DS.M/'.$tahun;

        default:
            return sprintf('%03d/DS.M/%s/%s', $urut, $romawi, $tahun);
    }
}

function layanan_get_pengajuan($mysqli, $id)
{
    $stmt = $mysqli->prepare("
        SELECT
            p.*,
            i.status_dalam_keluarga AS i_status_dalam_keluarga,
            i.jenis_kelamin AS i_jenis_kelamin,
            i.tempat_lahir AS i_tempat_lahir,
            i.tanggal_lahir AS i_tanggal_lahir,
            i.dusun AS i_dusun,
            i.desa AS i_desa,
            i.kecamatan AS i_kecamatan,
            i.kabupaten AS i_kabupaten,
            i.provinsi AS i_provinsi,
            i.agama AS i_agama,
            i.status_perkawinan AS i_status_perkawinan,
            i.pekerjaan AS i_pekerjaan,
            i.pendidikan_terakhir AS i_pendidikan_terakhir,
            i.kewarganegaraan AS i_kewarganegaraan,
            i.penghasilan_perbulan AS i_penghasilan_perbulan
        FROM layanan_surat_pengajuan p
        LEFT JOIN infografis i ON i.id = p.penduduk_id
        WHERE p.id = ?
        LIMIT 1
    ");

    if (!$stmt) {
        return null;
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;

    $stmt->close();

    return $row ?: null;
}

function layanan_get_warga($mysqli, $id)
{
    $stmt = $mysqli->prepare("
        SELECT *
        FROM infografis
        WHERE id = ?
        LIMIT 1
    ");

    if (!$stmt) {
        return null;
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;

    $stmt->close();

    return $row ?: null;
}

function layanan_get_warga_lain($mysqli, $excludeId)
{
    $stmt = $mysqli->prepare("
        SELECT id
        FROM infografis
        WHERE id <> ?
        ORDER BY id ASC
        LIMIT 1
    ");

    if (!$stmt) {
        return (int)$excludeId;
    }

    $stmt->bind_param('i', $excludeId);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;

    $stmt->close();

    return $row ? (int)$row['id'] : (int)$excludeId;
}

function layanan_file_url_admin($path)
{
    $path = trim((string)$path);

    if ($path === '') {
        return '#';
    }

    if (preg_match('~^https?://~i', $path)) {
        return $path;
    }

    return $path;
}

function layanan_print_path($prefix, $printFile, $id)
{
    $prefix = trim((string)$prefix);

    if ($prefix !== '') {
        $prefix = '/'.trim($prefix, '/');
    }

    return $prefix.'/'.$printFile.'?id='.(int)$id;
}

function layanan_qr_data($jenis, $nomorSurat)
{
    $kode = strtoupper(preg_replace('/[^A-Z0-9]+/i', '-', $jenis)).'-'.time().'-'.random_int(100, 999);
    $hash = hash('sha256', $kode.$nomorSurat);

    return [$kode, $hash];
}

function layanan_build_common_text($pengajuan, $tambahan)
{
    $keperluan = trim((string)($pengajuan['keperluan'] ?? ''));
    $ket = trim((string)($tambahan['keterangan'] ?? ''));

    if ($keperluan !== '' && $ket !== '') {
        return $keperluan."\n".$ket;
    }

    return $keperluan !== '' ? $keperluan : ($ket !== '' ? $ket : '-');
}

function layanan_buat_surat($mysqli, $pengajuan, $daftarSurat, $adminPagePrefix)
{
    $jenis = (string)($pengajuan['jenis_surat'] ?? '');

    if (!isset($daftarSurat[$jenis])) {
        throw new RuntimeException('Jenis surat tidak dikenali.');
    }

    $config = $daftarSurat[$jenis];
    $table = $config['table'];

    if (!layanan_table_exists($mysqli, $table)) {
        throw new RuntimeException('Tabel tujuan surat belum tersedia: '.$table);
    }

    if (!empty($pengajuan['generated_id']) && !empty($pengajuan['file_surat'])) {
        return [
            'surat_id' => (int)$pengajuan['generated_id'],
            'nomor_surat' => (string)($pengajuan['nomor_surat'] ?? ''),
            'table' => (string)($pengajuan['generated_table'] ?? $table),
            'file_surat' => (string)$pengajuan['file_surat'],
        ];
    }

    $warga = layanan_get_warga($mysqli, (int)$pengajuan['penduduk_id']);

    if (!$warga) {
        throw new RuntimeException('Data warga pada tabel infografis tidak ditemukan.');
    }

    $tambahan = layanan_decode_json($pengajuan['data_tambahan'] ?? '{}');

    $tanggal = date('Y-m-d');
    $now = date('Y-m-d H:i:s');
    $nomorSurat = layanan_nomor_surat($mysqli, $jenis, $table);
    [$qrKode, $qrHash] = layanan_qr_data($jenis, $nomorSurat);

    $wargaId = (int)$warga['id'];
    $nama = trim((string)($warga['nama_lengkap'] ?? $pengajuan['nama_lengkap'] ?? '-'));
    $alamat = layanan_alamat_warga($warga);
    $ttl = layanan_ttl_warga($warga);
    $umur = layanan_umur_warga($warga);
    $pekerjaan = trim((string)($warga['pekerjaan'] ?? '-'));
    $agama = trim((string)($warga['agama'] ?? '-'));
    $jenisKelamin = trim((string)($warga['jenis_kelamin'] ?? '-'));
    $kewarganegaraan = trim((string)($warga['kewarganegaraan'] ?? 'Indonesia'));
    $text = layanan_build_common_text($pengajuan, $tambahan);
    $nomorHp = trim((string)($tambahan['nomor_hp'] ?? ''));

    if ($nomorHp === '') {
        $nomorHp = '-';
    }

    $data = [];

    switch ($jenis) {
        case 'surat_domisili':
            $data = [
                'warga_id' => $wargaId,
                'nomor_surat' => $nomorSurat,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_tidak_mampu':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'tanggal_surat' => $tanggal,
                'keterangan' => $text,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_usaha':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'bidang_usaha' => $text,
                'alamat_usaha' => $alamat,
                'tahun_berdiri' => (int)date('Y'),
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_belum_menikah':
        case 'surat_belum_bekerja':
        case 'surat_kelakuan_baik':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_hilang':
            $data = [
                'warga_id' => $wargaId,
                'nomor_surat' => $nomorSurat,
                'tanggal_kehilangan' => $tanggal,
                'keterangan' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_pindah':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'tujuan_dusun' => trim((string)($tambahan['tujuan_dusun'] ?? '-')),
                'tujuan_desa' => trim((string)($tambahan['tujuan_desa'] ?? '-')),
                'tujuan_kecamatan' => trim((string)($tambahan['tujuan_kecamatan'] ?? '-')),
                'tujuan_kabupaten' => trim((string)($tambahan['tujuan_kabupaten'] ?? '-')),
                'tujuan_provinsi' => trim((string)($tambahan['tujuan_provinsi'] ?? '-')),
                'alasan_pindah' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_nikah':
            $isPerempuan = stripos($jenisKelamin, 'perempuan') !== false || stripos($jenisKelamin, 'wanita') !== false;

            $csNama = $isPerempuan ? '-' : $nama;
            $ciNama = $isPerempuan ? $nama : '-';

            $data = [
                'nomor_surat' => $nomorSurat,
                'tanggal_surat' => $tanggal,
                'kantor_desa' => trim((string)($warga['desa'] ?? 'Mambu')),
                'kecamatan' => trim((string)($warga['kecamatan'] ?? 'Luyo')),
                'kabupaten' => trim((string)($warga['kabupaten'] ?? 'Polewali Mandar')),
                'provinsi' => trim((string)($warga['provinsi'] ?? 'Sulawesi Barat')),

                'cs_nama' => $csNama,
                'cs_bin' => '-',
                'cs_nik' => $isPerempuan ? '-' : (string)($warga['nik'] ?? '-'),
                'cs_ttl' => $isPerempuan ? '-' : $ttl,
                'cs_kewarganegaraan' => $kewarganegaraan,
                'cs_agama' => $agama,
                'cs_pekerjaan' => $pekerjaan,
                'cs_alamat' => $isPerempuan ? '-' : $alamat,

                'ci_nama' => $ciNama,
                'ci_binti' => '-',
                'ci_nik' => $isPerempuan ? (string)($warga['nik'] ?? '-') : '-',
                'ci_ttl' => $isPerempuan ? $ttl : '-',
                'ci_kewarganegaraan' => $kewarganegaraan,
                'ci_agama' => $agama,
                'ci_pekerjaan' => $pekerjaan,
                'ci_alamat' => $isPerempuan ? $alamat : '-',

                'ayah_nama' => '-',
                'ayah_nik' => '-',
                'ayah_ttl' => '-',
                'ayah_pekerjaan' => '-',
                'ayah_alamat' => '-',

                'ibu_nama' => '-',
                'ibu_nik' => '-',
                'ibu_ttl' => '-',
                'ibu_pekerjaan' => '-',
                'ibu_alamat' => '-',

                'wali_nama' => '-',
                'wali_nik' => '-',
                'wali_ttl' => '-',
                'wali_pekerjaan' => '-',
                'wali_alamat' => '-',
            ];
            break;

        case 'surat_penghasilan_ortu':
            $penghasilan = preg_replace('/\D/', '', (string)($warga['penghasilan_perbulan'] ?? ''));

            if ($penghasilan === '') {
                $penghasilan = '0';
            }

            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'pekerjaan_ortu' => '-',
                'penghasilan_ortu' => (int)$penghasilan,
                'alasan_surat' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_merantau':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'tujuan_merantau' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_ijin_keramaian':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'umur' => $umur,
                'jenis_kelamin' => $jenisKelamin,
                'pekerjaan' => $pekerjaan,
                'agama' => $agama,
                'alamat' => $alamat,
                'jenis_acara' => $text,
                'hari_tanggal' => layanan_tanggal_indo($tanggal, false),
                'waktu' => '-',
                'tempat_acara' => $alamat,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_kuasa':
            $penerimaId = (int)($tambahan['penerima_id'] ?? 0);

            if ($penerimaId <= 0) {
                $penerimaId = layanan_get_warga_lain($mysqli, $wargaId);
            }

            $data = [
                'nomor_surat' => $nomorSurat,
                'pemberi_id' => $wargaId,
                'penerima_id' => $penerimaId,
                'keperluan' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_pengantar_kayu':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'jenis_kayu' => trim((string)($tambahan['jenis_kayu'] ?? '-')),
                'rincian_kayu' => $text,
                'lokasi_tujuan' => trim((string)($tambahan['lokasi_tujuan'] ?? '-')),
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_pengantar_hewan':
            $jumlahHewan = (int)($tambahan['jumlah_hewan'] ?? 0);

            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'jenis_hewan' => trim((string)($tambahan['jenis_hewan'] ?? '-')),
                'jumlah_hewan' => $jumlahHewan,
                'tujuan_alamat' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_ahli_waris':
            $data = [
                'nomor_surat' => $nomorSurat,
                'warga_id' => $wargaId,
                'tanggal_meninggal' => $tanggal,
                'nomor_akta_kematian' => trim((string)($tambahan['nomor_akta_kematian'] ?? '-')),
                'pasangan' => trim((string)($tambahan['pasangan'] ?? '-')),
                'jumlah_anak' => (int)($tambahan['jumlah_anak'] ?? 0),
                'ahli_waris' => $text,
                'saksi' => trim((string)($tambahan['saksi'] ?? '-')),
            ];
            break;

        case 'surat_pembagian_waris':
            $mysqli->begin_transaction();

            try {
                $suratId = layanan_insert_row($mysqli, $table, [
                    'nama_alm' => trim((string)($tambahan['nama_alm'] ?? $nama)),
                    'desa' => trim((string)($warga['desa'] ?? 'Mambu')),
                    'kecamatan' => trim((string)($warga['kecamatan'] ?? 'Luyo')),
                    'kabupaten' => trim((string)($warga['kabupaten'] ?? 'Polewali Mandar')),
                    'obyek_waris' => $text,
                    'dusun' => trim((string)($warga['dusun'] ?? '-')),
                    'luas' => trim((string)($tambahan['luas'] ?? '-')),
                    'no_hak_milik' => trim((string)($tambahan['no_hak_milik'] ?? '-')),
                    'batas_utara' => trim((string)($tambahan['batas_utara'] ?? '-')),
                    'batas_timur' => trim((string)($tambahan['batas_timur'] ?? '-')),
                    'batas_selatan' => trim((string)($tambahan['batas_selatan'] ?? '-')),
                    'batas_barat' => trim((string)($tambahan['batas_barat'] ?? '-')),
                ]);

                if (layanan_table_exists($mysqli, 'surat_pembagian_waris_ahli')) {
                    layanan_insert_row($mysqli, 'surat_pembagian_waris_ahli', [
                        'surat_id' => $suratId,
                        'nama' => $nama,
                        'umur' => $umur,
                        'pekerjaan' => $pekerjaan,
                        'nik' => (string)($warga['nik'] ?? '-'),
                        'alamat' => $alamat,
                    ]);
                }

                $mysqli->commit();

                return [
                    'surat_id' => $suratId,
                    'nomor_surat' => '',
                    'table' => $table,
                    'file_surat' => layanan_print_path($adminPagePrefix, $config['print'], $suratId),
                ];
            } catch (Throwable $e) {
                $mysqli->rollback();
                throw $e;
            }

        case 'surat_gadai':
            $pihakKeduaId = (int)($tambahan['pihak_kedua_id'] ?? 0);

            if ($pihakKeduaId <= 0) {
                $pihakKeduaId = layanan_get_warga_lain($mysqli, $wargaId);
            }

            $data = [
                'pihak_pertama_id' => $wargaId,
                'pihak_kedua_id' => $pihakKeduaId,
                'luas_lahan' => trim((string)($tambahan['luas_lahan'] ?? '-')),
                'lokasi_lahan' => trim((string)($tambahan['lokasi_lahan'] ?? $alamat)),
                'batas_utara' => trim((string)($tambahan['batas_utara'] ?? '-')),
                'batas_selatan' => trim((string)($tambahan['batas_selatan'] ?? '-')),
                'batas_barat' => trim((string)($tambahan['batas_barat'] ?? '-')),
                'batas_timur' => trim((string)($tambahan['batas_timur'] ?? '-')),
                'jumlah_uang' => preg_replace('/\D/', '', (string)($tambahan['jumlah_uang'] ?? '0')),
                'tanggal_surat' => $tanggal,
            ];
            break;

        case 'surat_undangan':
            $data = [
                'nomor_surat' => $nomorSurat,
                'sifat' => trim((string)($tambahan['sifat'] ?? 'Biasa')),
                'lampiran' => trim((string)($tambahan['lampiran'] ?? '-')),
                'perihal' => trim((string)($tambahan['perihal'] ?? $pengajuan['nama_surat'] ?? 'Undangan')),
                'tujuan' => trim((string)($tambahan['tujuan'] ?? $nama)),
                'hari_tanggal' => trim((string)($tambahan['hari_tanggal'] ?? layanan_tanggal_indo($tanggal, false))),
                'pukul' => trim((string)($tambahan['pukul'] ?? '-')),
                'tempat' => trim((string)($tambahan['tempat'] ?? $alamat)),
                'isi' => $text,
                'tanggal_surat' => $tanggal,
                'waktu_ttd' => $now,
                'qr_kode' => $qrKode,
                'qr_hash' => $qrHash,
            ];
            break;

        case 'surat_pernyataan_kesanggupan':
            $data = [
                'warga_id' => $wargaId,
                'nomor_surat' => $nomorSurat,
                'tanggal_surat' => $tanggal,
                'no_hp' => $nomorHp,
            ];
            break;

        default:
            throw new RuntimeException('Jenis surat belum didukung.');
    }

    $suratId = layanan_insert_row($mysqli, $table, $data);

    return [
        'surat_id' => $suratId,
        'nomor_surat' => $nomorSurat,
        'table' => $table,
        'file_surat' => layanan_print_path($adminPagePrefix, $config['print'], $suratId),
    ];
}

layanan_ensure_table($mysqli);

/* =========================================================
   PROSES HAPUS
========================================================= */

if ($act === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if (!is_string($token) || !hash_equals($csrfToken, $token)) {
        layanan_redirect('admin_layanan_mandiri.php?msg=csrf');
    }

    if ($id <= 0) {
        layanan_redirect('admin_layanan_mandiri.php?msg=notfound');
    }

    $stmt = $mysqli->prepare("
        DELETE FROM layanan_surat_pengajuan
        WHERE id = ?
    ");

    if (!$stmt) {
        layanan_redirect('admin_layanan_mandiri.php?msg=error');
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();

    $deleted = $stmt->affected_rows > 0;

    $stmt->close();

    layanan_redirect('admin_layanan_mandiri.php?msg='.($deleted ? 'deleted' : 'notfound'));
}

/* =========================================================
   PROSES UPDATE STATUS
========================================================= */

if ($act === 'status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    $id = (int)($_POST['id'] ?? 0);
    $status = trim((string)($_POST['status'] ?? ''));
    $catatan = trim((string)($_POST['catatan_admin'] ?? ''));

    if (!is_string($token) || !hash_equals($csrfToken, $token)) {
        layanan_redirect('admin_layanan_mandiri.php?msg=csrf');
    }

    if ($id <= 0 || !in_array($status, ['diajukan', 'diproses', 'selesai', 'ditolak'], true)) {
        layanan_redirect('admin_layanan_mandiri.php?msg=error');
    }

    $stmt = $mysqli->prepare("
        UPDATE layanan_surat_pengajuan
        SET status = ?, catatan_admin = ?
        WHERE id = ?
    ");

    if (!$stmt) {
        layanan_redirect('admin_layanan_mandiri.php?msg=error');
    }

    $stmt->bind_param('ssi', $status, $catatan, $id);
    $stmt->execute();
    $stmt->close();

    layanan_redirect('admin_layanan_mandiri.php?a=detail&id='.$id.'&msg=status');
}

/* =========================================================
   PROSES BUAT SURAT OTOMATIS
========================================================= */

if ($act === 'buat' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if (!is_string($token) || !hash_equals($csrfToken, $token)) {
        layanan_redirect('admin_layanan_mandiri.php?msg=csrf');
    }

    if ($id <= 0) {
        layanan_redirect('admin_layanan_mandiri.php?msg=notfound');
    }

    $pengajuan = layanan_get_pengajuan($mysqli, $id);

    if (!$pengajuan) {
        layanan_redirect('admin_layanan_mandiri.php?msg=notfound');
    }

    try {
        $hasil = layanan_buat_surat($mysqli, $pengajuan, $daftarSurat, $adminPagePrefix);

        $status = 'selesai';
        $catatanDefault = trim((string)($pengajuan['catatan_admin'] ?? ''));

        if ($catatanDefault === '') {
            $catatanDefault = 'Surat telah dibuat oleh admin pada '.layanan_tanggal_indo(date('Y-m-d H:i:s'));
        }

        $stmt = $mysqli->prepare("
            UPDATE layanan_surat_pengajuan
            SET
                status = ?,
                catatan_admin = ?,
                file_surat = ?,
                nomor_surat = ?,
                generated_table = ?,
                generated_id = ?
            WHERE id = ?
        ");

        if (!$stmt) {
            throw new RuntimeException($mysqli->error);
        }

        $fileSurat = (string)$hasil['file_surat'];
        $nomorSurat = (string)$hasil['nomor_surat'];
        $generatedTable = (string)$hasil['table'];
        $generatedId = (int)$hasil['surat_id'];

        $stmt->bind_param(
            'sssssii',
            $status,
            $catatanDefault,
            $fileSurat,
            $nomorSurat,
            $generatedTable,
            $generatedId,
            $id
        );

        if (!$stmt->execute()) {
            throw new RuntimeException($stmt->error);
        }

        $stmt->close();

        layanan_redirect('admin_layanan_mandiri.php?a=detail&id='.$id.'&msg=generated');
    } catch (Throwable $e) {
        $_SESSION['layanan_mandiri_error'] = $e->getMessage();
        layanan_redirect('admin_layanan_mandiri.php?a=detail&id='.$id.'&msg=generate_error');
    }
}

/* =========================================================
   FILTER DAN DATA DAFTAR
========================================================= */

$q = trim((string)($_GET['q'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$filterJenis = trim((string)($_GET['jenis'] ?? ''));

$where = [];
$types = '';
$params = [];

if ($filterStatus !== '' && in_array($filterStatus, ['diajukan', 'diproses', 'selesai', 'ditolak'], true)) {
    $where[] = 'status = ?';
    $types .= 's';
    $params[] = $filterStatus;
}

if ($filterJenis !== '' && isset($daftarSurat[$filterJenis])) {
    $where[] = 'jenis_surat = ?';
    $types .= 's';
    $params[] = $filterJenis;
}

if ($q !== '') {
    $where[] = '(kode_pengajuan LIKE ? OR nama_lengkap LIKE ? OR nik LIKE ? OR nomor_kk LIKE ? OR nama_surat LIKE ? OR keperluan LIKE ?)';
    $like = '%'.$q.'%';

    for ($i = 0; $i < 6; $i++) {
        $types .= 's';
        $params[] = $like;
    }
}

$whereSql = $where ? 'WHERE '.implode(' AND ', $where) : '';

$listSql = "
    SELECT *
    FROM layanan_surat_pengajuan
    ".$whereSql."
    ORDER BY id DESC
";

if ($params) {
    $stmtList = $mysqli->prepare($listSql);

    if ($stmtList) {
        layanan_bind_dynamic($stmtList, $types, $params);
        $stmtList->execute();
        $list = $stmtList->get_result();
    } else {
        $list = null;
    }
} else {
    $list = $mysqli->query($listSql);
}

$totalData = $list ? $list->num_rows : 0;

$stats = [
    'total' => 0,
    'diajukan' => 0,
    'diproses' => 0,
    'selesai' => 0,
    'ditolak' => 0,
];

$statResult = $mysqli->query("
    SELECT status, COUNT(*) AS total
    FROM layanan_surat_pengajuan
    GROUP BY status
");

if ($statResult) {
    while ($row = $statResult->fetch_assoc()) {
        $statusKey = $row['status'];
        $totalStatus = (int)$row['total'];

        if (isset($stats[$statusKey])) {
            $stats[$statusKey] = $totalStatus;
        }

        $stats['total'] += $totalStatus;
    }
}

$detail = null;

if ($act === 'detail') {
    $detailId = (int)($_GET['id'] ?? 0);

    if ($detailId > 0) {
        $detail = layanan_get_pengajuan($mysqli, $detailId);
    }

    if (!$detail) {
        layanan_redirect('admin_layanan_mandiri.php?msg=notfound');
    }
}

$msgKey = $_GET['msg'] ?? '';
$msgText = [
    'generated' => 'Surat berhasil dibuat dan status pengajuan menjadi selesai.',
    'generate_error' => 'Surat gagal dibuat otomatis.',
    'status' => 'Status pengajuan berhasil diperbarui.',
    'deleted' => 'Pengajuan berhasil dihapus.',
    'notfound' => 'Data pengajuan tidak ditemukan.',
    'csrf' => 'Token keamanan tidak valid. Silakan ulangi proses.',
    'error' => 'Terjadi kesalahan saat memproses data.',
][$msgKey] ?? '';

$msgError = in_array($msgKey, ['generate_error', 'notfound', 'csrf', 'error'], true);

if ($msgKey === 'generate_error' && !empty($_SESSION['layanan_mandiri_error'])) {
    $msgText .= ' Detail: '.$_SESSION['layanan_mandiri_error'];
    unset($_SESSION['layanan_mandiri_error']);
}

include __DIR__.'/../includes/header.php';
?>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<link
    href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
    rel="stylesheet"
>

<link
    href="https://cdn.jsdelivr.net/npm/remixicon@4.6.0/fonts/remixicon.css"
    rel="stylesheet"
>

<style>
:root {
    --layanan-green-950: #002818;
    --layanan-green-900: #003d22;
    --layanan-green-800: #005530;
    --layanan-green-700: #047a3d;
    --layanan-green-600: #09a04f;
    --layanan-green-500: #15c46a;
    --layanan-green-400: #35e085;
    --layanan-green-100: #dcfaee;
    --layanan-green-50: #edfff5;

    --layanan-blue-500: #2080e8;
    --layanan-yellow-500: #f5b400;
    --layanan-orange-500: #f26b1d;
    --layanan-red-500: #dc3545;

    --layanan-ink: #0f1c16;
    --layanan-muted: #5e6e67;
    --layanan-line: #daeae1;
    --layanan-surface: #ffffff;
    --layanan-page: #f3faf6;
    --layanan-shadow: 0 8px 28px rgba(10, 40, 25, .10);
    --layanan-radius: 16px;
}

@keyframes layanan-gradient {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
}

@keyframes layanan-pulse {
    0% { box-shadow: 0 0 0 0 rgba(53, 224, 133, .45); }
    70% { box-shadow: 0 0 0 12px rgba(53, 224, 133, 0); }
    100% { box-shadow: 0 0 0 0 rgba(53, 224, 133, 0); }
}

* {
    box-sizing: border-box;
}

body {
    color: var(--layanan-ink);
    background-color: var(--layanan-page);
    background-image:
        radial-gradient(ellipse at 80% 0%, rgba(21, 196, 106, .06) 0%, transparent 50%),
        radial-gradient(ellipse at 20% 100%, rgba(9, 160, 79, .04) 0%, transparent 50%);
    font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
}

.layanan-page {
    padding: 26px;
}

.layanan-header {
    position: relative;
    overflow: hidden;
    margin-bottom: 18px;
    padding: 26px 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    color: #fff;
    background: linear-gradient(135deg, var(--layanan-green-950), var(--layanan-green-800), var(--layanan-green-900));
    background-size: 200% 100%;
    border-radius: var(--layanan-radius);
    box-shadow: 0 14px 40px rgba(0, 60, 30, .28);
    animation: layanan-gradient 8s ease infinite;
}

.layanan-header::before {
    content: "";
    position: absolute;
    width: 220px;
    height: 220px;
    top: -80px;
    right: -55px;
    background: radial-gradient(circle, rgba(53, 224, 133, .20), transparent 70%);
    border-radius: 50%;
}

.layanan-header-left,
.layanan-header-actions {
    position: relative;
    z-index: 1;
}

.layanan-eyebrow {
    margin: 0 0 8px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: var(--layanan-green-400);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .10em;
    text-transform: uppercase;
}

.layanan-header h2 {
    margin: 0;
    color: #fff;
    font-size: clamp(20px, 3vw, 27px);
    font-weight: 800;
    letter-spacing: -.03em;
    line-height: 1.2;
}

.layanan-title-icon {
    margin-right: 8px;
    color: var(--layanan-green-400);
    font-size: 27px;
    vertical-align: middle;
}

.layanan-description {
    margin: 10px 0 0;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: rgba(255, 255, 255, .75);
    font-size: 12px;
    font-weight: 600;
}

.layanan-live-dot {
    width: 8px;
    height: 8px;
    flex-shrink: 0;
    background: var(--layanan-green-400);
    border-radius: 50%;
    animation: layanan-pulse 2s ease infinite;
}

.layanan-header-actions {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 9px;
}

.layanan-clock {
    padding: 10px 15px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #fff;
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.18);
    border-radius: 12px;
    font-size: 13px;
    font-weight: 700;
    backdrop-filter: blur(8px);
}

.layanan-stat-grid {
    margin-bottom: 18px;
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 12px;
}

.layanan-stat-card {
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    background: var(--layanan-surface);
    border: 1px solid rgba(210, 232, 220, .85);
    border-radius: 15px;
    box-shadow: var(--layanan-shadow);
}

.layanan-stat-icon {
    width: 42px;
    height: 42px;
    flex-shrink: 0;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--layanan-green-500), var(--layanan-green-800));
    border-radius: 13px;
    font-size: 20px;
}

.layanan-stat-card strong,
.layanan-stat-card span {
    display: block;
}

.layanan-stat-card strong {
    color: var(--layanan-ink);
    font-size: 22px;
    font-weight: 900;
    line-height: 1;
}

.layanan-stat-card span {
    margin-top: 5px;
    color: var(--layanan-muted);
    font-size: 11px;
    font-weight: 800;
}

.layanan-panel {
    overflow: hidden;
    background: var(--layanan-surface);
    border: 1px solid rgba(210, 232, 220, .85);
    border-radius: var(--layanan-radius);
    box-shadow: var(--layanan-shadow);
}

.layanan-panel-head {
    padding: 18px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 14px;
    background: radial-gradient(circle at top right, rgba(21, 196, 106, .08), transparent 34%), #fff;
    border-bottom: 1px solid var(--layanan-line);
}

.layanan-panel-title {
    display: flex;
    align-items: center;
    gap: 12px;
}

.layanan-panel-icon {
    width: 42px;
    height: 42px;
    flex-shrink: 0;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--layanan-green-500), var(--layanan-green-800));
    border-radius: 13px;
    box-shadow: 0 4px 12px rgba(9,160,79,.28);
    font-size: 20px;
}

.layanan-panel-title h3 {
    margin: 0;
    color: var(--layanan-ink);
    font-size: 16px;
    font-weight: 800;
}

.layanan-panel-title p {
    margin: 3px 0 0;
    color: var(--layanan-muted);
    font-size: 12px;
    font-weight: 600;
}

.layanan-panel-body {
    padding: 20px;
}

.layanan-alert {
    margin-bottom: 16px;
    padding: 13px 15px;
    display: flex;
    align-items: center;
    gap: 9px;
    color: var(--layanan-green-800);
    background: var(--layanan-green-50);
    border: 1px solid var(--layanan-green-100);
    border-radius: 14px;
    box-shadow: var(--layanan-shadow);
    font-size: 14px;
    font-weight: 800;
}

.layanan-alert-error {
    color: #a73c00;
    background: #fff4eb;
    border-color: #ffd8bd;
}

.layanan-btn {
    padding: 10px 15px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    border: none;
    border-radius: 12px;
    cursor: pointer;
    text-decoration: none;
    font-family: inherit;
    font-size: 13px;
    font-weight: 800;
    line-height: 1;
    box-shadow: 0 8px 18px rgba(10, 40, 25, .12);
    transition: transform .2s ease, filter .2s ease;
}

.layanan-btn:hover {
    transform: translateY(-2px);
    filter: brightness(.98);
}

.layanan-btn-primary {
    color: #fff;
    background: linear-gradient(135deg, var(--layanan-green-500), var(--layanan-green-800));
}

.layanan-btn-light {
    color: #fff;
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.18);
    backdrop-filter: blur(8px);
}

.layanan-btn-edit {
    color: var(--layanan-ink);
    background: linear-gradient(135deg, #ffd95c, var(--layanan-yellow-500));
}

.layanan-btn-delete {
    color: #fff;
    background: linear-gradient(135deg, #ff9a52, var(--layanan-orange-500));
}

.layanan-btn-view {
    color: #fff;
    background: linear-gradient(135deg, #60b4ff, var(--layanan-blue-500));
}

.layanan-btn-ghost {
    color: var(--layanan-green-800);
    background: var(--layanan-green-50);
    border: 1px solid var(--layanan-green-100);
}

.layanan-btn-small {
    padding: 8px 11px;
    border-radius: 10px;
    box-shadow: none;
    font-size: 12px;
}

.layanan-toolbar {
    margin-bottom: 16px;
    display: grid;
    grid-template-columns: minmax(240px, 1fr) 190px 240px auto;
    gap: 10px;
    align-items: center;
}

.layanan-search {
    position: relative;
}

.layanan-search i {
    position: absolute;
    top: 50%;
    left: 14px;
    color: var(--layanan-green-700);
    font-size: 18px;
    transform: translateY(-50%);
}

.layanan-input {
    width: 100%;
    min-height: 44px;
    padding: 12px 13px;
    color: var(--layanan-ink);
    background: #f8fffb;
    border: 1px solid var(--layanan-line);
    border-radius: 13px;
    outline: none;
    font-family: inherit;
    font-size: 14px;
    font-weight: 600;
}

.layanan-search .layanan-input {
    padding-left: 42px;
}

.layanan-input:focus {
    background: #fff;
    border-color: var(--layanan-green-500);
    box-shadow: 0 0 0 4px rgba(21,196,106,.13);
}

textarea.layanan-input {
    resize: vertical;
    line-height: 1.6;
}

.layanan-table-wrap {
    overflow-x: auto;
    background: #fff;
    border: 1px solid var(--layanan-line);
    border-radius: 16px;
}

.layanan-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 14px;
}

.layanan-table th {
    padding: 14px 13px;
    color: var(--layanan-green-900);
    background: linear-gradient(180deg, var(--layanan-green-50), #f8fffb);
    border-bottom: 1px solid var(--layanan-line);
    font-size: 12px;
    font-weight: 800;
    letter-spacing: .04em;
    text-align: left;
    text-transform: uppercase;
    white-space: nowrap;
}

.layanan-table td {
    padding: 14px 13px;
    border-bottom: 1px solid #edf7f1;
    vertical-align: middle;
}

.layanan-table tbody tr:hover {
    background: var(--layanan-green-50);
}

.layanan-table tbody tr:last-child td {
    border-bottom: none;
}

.layanan-title-wrap {
    min-width: 250px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.layanan-avatar {
    width: 40px;
    height: 40px;
    flex-shrink: 0;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--layanan-green-500), var(--layanan-green-800));
    border-radius: 14px;
    box-shadow: 0 8px 16px rgba(9,160,79,.20);
    font-weight: 800;
}

.layanan-title-text {
    color: var(--layanan-ink);
    font-weight: 800;
    line-height: 1.4;
}

.layanan-subtitle {
    max-width: 350px;
    margin-top: 3px;
    overflow: hidden;
    color: var(--layanan-muted);
    font-size: 11px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.layanan-badge {
    padding: 7px 10px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 800;
    white-space: nowrap;
}

.layanan-badge-blue {
    color: var(--layanan-blue-500);
    background: #eef8ff;
}

.layanan-status-diajukan {
    color: #a35d00;
    background: #fff5d8;
    border: 1px solid #ffe5a0;
}

.layanan-status-diproses {
    color: #0d6db6;
    background: #eaf6ff;
    border: 1px solid #cce8ff;
}

.layanan-status-selesai {
    color: #08743b;
    background: #dcfaee;
    border: 1px solid #b9f0d6;
}

.layanan-status-ditolak {
    color: #b42318;
    background: #fff0ee;
    border: 1px solid #ffd0ca;
}

.layanan-actions {
    min-width: 230px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 7px;
}

.layanan-delete-form,
.layanan-inline-form {
    margin: 0;
}

.layanan-empty {
    padding: 36px !important;
    color: var(--layanan-muted);
    background: #fbfffd;
    font-weight: 600;
    text-align: center;
}

.layanan-empty i {
    display: block;
    margin-bottom: 8px;
    color: var(--layanan-green-600);
    font-size: 34px;
}

.layanan-detail-grid {
    display: grid;
    grid-template-columns: 1.1fr .9fr;
    gap: 18px;
}

.layanan-card {
    background: #fff;
    border: 1px solid var(--layanan-line);
    border-radius: 16px;
    box-shadow: var(--layanan-shadow);
    overflow: hidden;
}

.layanan-card-head {
    padding: 16px 18px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--layanan-green-900);
    background: var(--layanan-green-50);
    border-bottom: 1px solid var(--layanan-line);
    font-size: 14px;
    font-weight: 900;
}

.layanan-card-body {
    padding: 18px;
}

.layanan-info-list {
    display: grid;
    gap: 11px;
}

.layanan-info-row {
    padding-bottom: 11px;
    display: grid;
    grid-template-columns: 160px 1fr;
    gap: 14px;
    border-bottom: 1px dashed var(--layanan-line);
}

.layanan-info-row:last-child {
    padding-bottom: 0;
    border-bottom: none;
}

.layanan-info-row span:first-child {
    color: var(--layanan-muted);
    font-size: 12px;
    font-weight: 800;
}

.layanan-info-row span:last-child {
    color: var(--layanan-ink);
    font-size: 13px;
    font-weight: 700;
}

.layanan-status-form {
    display: grid;
    gap: 12px;
}

.layanan-note {
    margin-top: 14px;
    padding: 12px 14px;
    display: flex;
    align-items: flex-start;
    gap: 9px;
    color: var(--layanan-green-900);
    background: var(--layanan-green-50);
    border: 1px solid var(--layanan-green-100);
    border-radius: 13px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.6;
}

@media (max-width: 1180px) {
    .layanan-stat-grid {
        grid-template-columns: repeat(3, minmax(0, 1fr));
    }

    .layanan-toolbar {
        grid-template-columns: 1fr 1fr;
    }

    .layanan-toolbar .layanan-btn {
        width: 100%;
    }
}

@media (max-width: 860px) {
    .layanan-page {
        padding: 16px;
    }

    .layanan-header {
        padding: 20px;
    }

    .layanan-header-actions {
        width: 100%;
        flex-direction: column;
        align-items: stretch;
    }

    .layanan-clock,
    .layanan-btn-light {
        width: 100%;
        justify-content: center;
    }

    .layanan-stat-grid,
    .layanan-toolbar,
    .layanan-detail-grid {
        grid-template-columns: 1fr;
    }

    .layanan-info-row {
        grid-template-columns: 1fr;
        gap: 4px;
    }

    .layanan-actions {
        min-width: 240px;
    }
}
</style>

<div class="layanan-page">

    <div class="layanan-header">
        <div class="layanan-header-left">
            <p class="layanan-eyebrow">
                <i class="ri-customer-service-2-fill"></i>
                Layanan Mandiri Warga
            </p>

            <h2>
                <i class="ri-file-paper-2-fill layanan-title-icon"></i>
                Admin Layanan Mandiri
            </h2>

            <p class="layanan-description">
                <span class="layanan-live-dot"></span>
                Kelola pengajuan surat warga dan buat surat otomatis
            </p>
        </div>

        <div class="layanan-header-actions">
            <span class="layanan-clock">
                <i class="ri-time-fill"></i>
                <span id="layananLiveClock">--.--.--</span>
                <span style="color:rgba(255,255,255,.55)">WITA</span>
            </span>

            <?php if ($act === 'detail'): ?>
                <a class="layanan-btn layanan-btn-light" href="admin_layanan_mandiri.php">
                    <i class="ri-arrow-left-line"></i>
                    Kembali
                </a>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($msgText): ?>
        <div class="layanan-alert <?= $msgError ? 'layanan-alert-error' : '' ?>">
            <i class="<?= $msgError ? 'ri-error-warning-fill' : 'ri-checkbox-circle-fill' ?>"></i>
            <?= esc($msgText) ?>
        </div>
    <?php endif; ?>

    <?php if ($act === 'list'): ?>

        <div class="layanan-stat-grid">
            <div class="layanan-stat-card">
                <span class="layanan-stat-icon"><i class="ri-file-list-3-fill"></i></span>
                <span>
                    <strong><?= (int)$stats['total'] ?></strong>
                    <span>Total Pengajuan</span>
                </span>
            </div>

            <div class="layanan-stat-card">
                <span class="layanan-stat-icon"><i class="ri-send-plane-fill"></i></span>
                <span>
                    <strong><?= (int)$stats['diajukan'] ?></strong>
                    <span>Diajukan</span>
                </span>
            </div>

            <div class="layanan-stat-card">
                <span class="layanan-stat-icon"><i class="ri-loader-4-line"></i></span>
                <span>
                    <strong><?= (int)$stats['diproses'] ?></strong>
                    <span>Diproses</span>
                </span>
            </div>

            <div class="layanan-stat-card">
                <span class="layanan-stat-icon"><i class="ri-checkbox-circle-fill"></i></span>
                <span>
                    <strong><?= (int)$stats['selesai'] ?></strong>
                    <span>Selesai</span>
                </span>
            </div>

            <div class="layanan-stat-card">
                <span class="layanan-stat-icon"><i class="ri-close-circle-fill"></i></span>
                <span>
                    <strong><?= (int)$stats['ditolak'] ?></strong>
                    <span>Ditolak</span>
                </span>
            </div>
        </div>

        <div class="layanan-panel">
            <div class="layanan-panel-head">
                <div class="layanan-panel-title">
                    <div class="layanan-panel-icon">
                        <i class="ri-folder-open-fill"></i>
                    </div>

                    <div>
                        <h3>Daftar Pengajuan Surat</h3>
                        <p>Pengajuan masuk dari halaman layanan mandiri warga.</p>
                    </div>
                </div>

                <span class="layanan-badge layanan-badge-blue">
                    <i class="ri-database-2-fill"></i>
                    <?= (int)$totalData ?> Data Ditampilkan
                </span>
            </div>

            <div class="layanan-panel-body">
                <form method="get" action="admin_layanan_mandiri.php" class="layanan-toolbar">
                    <div class="layanan-search">
                        <i class="ri-search-line"></i>
                        <input
                            type="text"
                            name="q"
                            value="<?= esc($q) ?>"
                            class="layanan-input"
                            placeholder="Cari kode, nama, NIK, KK, surat, atau keperluan..."
                            autocomplete="off"
                        >
                    </div>

                    <select name="status" class="layanan-input">
                        <option value="">Semua Status</option>
                        <?php foreach (['diajukan', 'diproses', 'selesai', 'ditolak'] as $statusOption): ?>
                            <option value="<?= esc($statusOption) ?>" <?= $filterStatus === $statusOption ? 'selected' : '' ?>>
                                <?= esc(layanan_status_label($statusOption)) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <select name="jenis" class="layanan-input">
                        <option value="">Semua Jenis Surat</option>
                        <?php foreach ($daftarSurat as $key => $surat): ?>
                            <option value="<?= esc($key) ?>" <?= $filterJenis === $key ? 'selected' : '' ?>>
                                <?= esc($surat['nama']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <button type="submit" class="layanan-btn layanan-btn-primary">
                        <i class="ri-filter-3-fill"></i>
                        Filter
                    </button>
                </form>

                <div class="layanan-table-wrap">
                    <table class="layanan-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Warga</th>
                                <th>Jenis Surat</th>
                                <th>Tanggal</th>
                                <th>Status</th>
                                <th>Surat Jadi</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalData === 0): ?>
                                <tr>
                                    <td colspan="7" class="layanan-empty">
                                        <i class="ri-inbox-2-fill"></i>
                                        <?= $q !== '' || $filterStatus !== '' || $filterJenis !== ''
                                            ? 'Data pengajuan yang dicari tidak ditemukan.'
                                            : 'Belum ada pengajuan layanan mandiri.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

                            <?php if ($list): ?>
                                <?php $no = 1; ?>

                                <?php while ($row = $list->fetch_assoc()): ?>
                                    <?php
                                        $jenisKey = $row['jenis_surat'] ?? '';
                                        $suratInfo = $daftarSurat[$jenisKey] ?? [
                                            'nama' => $row['nama_surat'] ?? 'Surat',
                                            'ikon' => 'ri-file-list-3-fill',
                                            'template' => '#',
                                            'print' => '#',
                                            'table' => '',
                                        ];
                                    ?>

                                    <tr>
                                        <td><?= $no++ ?></td>

                                        <td>
                                            <div class="layanan-title-wrap">
                                                <div class="layanan-avatar">
                                                    <?= esc(layanan_inisial($row['nama_lengkap'] ?? 'W')) ?>
                                                </div>

                                                <div>
                                                    <div class="layanan-title-text">
                                                        <?= esc($row['nama_lengkap'] ?? '-') ?>
                                                    </div>

                                                    <div class="layanan-subtitle">
                                                        NIK <?= esc($row['nik'] ?? '-') ?> · KK <?= esc($row['nomor_kk'] ?? '-') ?><br>
                                                        <?= esc($row['kode_pengajuan'] ?? '-') ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <span class="layanan-badge layanan-badge-blue">
                                                <i class="<?= esc($suratInfo['ikon']) ?>"></i>
                                                <?= esc($row['nama_surat'] ?? $suratInfo['nama']) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <span class="layanan-badge layanan-badge-blue">
                                                <i class="ri-calendar-check-fill"></i>
                                                <?= esc(layanan_tanggal_indo($row['created_at'] ?? '')) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <span class="layanan-badge <?= esc(layanan_status_class($row['status'] ?? 'diajukan')) ?>">
                                                <i class="<?= esc(layanan_status_icon($row['status'] ?? 'diajukan')) ?>"></i>
                                                <?= esc(layanan_status_label($row['status'] ?? 'diajukan')) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <?php if (!empty($row['file_surat'])): ?>
                                                <a
                                                    class="layanan-btn layanan-btn-small layanan-btn-view"
                                                    href="<?= esc(layanan_file_url_admin($row['file_surat'])) ?>"
                                                    target="_blank"
                                                    rel="noopener"
                                                >
                                                    <i class="ri-printer-fill"></i>
                                                    Buka
                                                </a>
                                            <?php else: ?>
                                                <span class="layanan-badge layanan-status-diajukan">
                                                    <i class="ri-time-line"></i>
                                                    Belum
                                                </span>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <div class="layanan-actions">
                                                <a
                                                    class="layanan-btn layanan-btn-small layanan-btn-view"
                                                    href="admin_layanan_mandiri.php?a=detail&id=<?= (int)$row['id'] ?>"
                                                >
                                                    <i class="ri-eye-fill"></i>
                                                    Detail
                                                </a>

                                                <?php if (empty($row['generated_id'])): ?>
                                                    <form
                                                        method="post"
                                                        action="admin_layanan_mandiri.php?a=buat"
                                                        class="layanan-inline-form"
                                                        onsubmit="return confirm('Buat surat otomatis dari pengajuan ini? Data akan masuk ke database surat terkait.');"
                                                    >
                                                        <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                                        <button type="submit" class="layanan-btn layanan-btn-small layanan-btn-primary">
                                                            <i class="ri-magic-fill"></i>
                                                            Buat Surat
                                                        </button>
                                                    </form>
                                                <?php endif; ?>

                                                <form
                                                    method="post"
                                                    action="admin_layanan_mandiri.php?a=delete"
                                                    class="layanan-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus pengajuan ini? Data surat yang sudah dibuat tidak ikut dihapus.');"
                                                >
                                                    <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                                    <button type="submit" class="layanan-btn layanan-btn-small layanan-btn-delete">
                                                        <i class="ri-delete-bin-6-fill"></i>
                                                        Hapus
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    <?php else: ?>

        <?php
            $detailJenis = $detail['jenis_surat'] ?? '';
            $detailSurat = $daftarSurat[$detailJenis] ?? [
                'nama' => $detail['nama_surat'] ?? 'Surat',
                'ikon' => 'ri-file-list-3-fill',
                'template' => '#',
                'print' => '#',
                'table' => '',
            ];

            $dataTambahan = layanan_decode_json($detail['data_tambahan'] ?? '{}');

            $wargaDetail = [
                'tempat_lahir' => $detail['i_tempat_lahir'] ?? '',
                'tanggal_lahir' => $detail['i_tanggal_lahir'] ?? '',
                'jenis_kelamin' => $detail['i_jenis_kelamin'] ?? '',
                'dusun' => $detail['i_dusun'] ?? '',
                'desa' => $detail['i_desa'] ?? '',
                'kecamatan' => $detail['i_kecamatan'] ?? '',
                'kabupaten' => $detail['i_kabupaten'] ?? '',
                'provinsi' => $detail['i_provinsi'] ?? '',
                'agama' => $detail['i_agama'] ?? '',
                'status_perkawinan' => $detail['i_status_perkawinan'] ?? '',
                'pekerjaan' => $detail['i_pekerjaan'] ?? '',
            ];
        ?>

        <div class="layanan-panel">
            <div class="layanan-panel-head">
                <div class="layanan-panel-title">
                    <div class="layanan-panel-icon">
                        <i class="<?= esc($detailSurat['ikon']) ?>"></i>
                    </div>

                    <div>
                        <h3>Detail Pengajuan</h3>
                        <p><?= esc($detail['kode_pengajuan'] ?? '-') ?> · <?= esc($detail['nama_surat'] ?? $detailSurat['nama']) ?></p>
                    </div>
                </div>

                <span class="layanan-badge <?= esc(layanan_status_class($detail['status'] ?? 'diajukan')) ?>">
                    <i class="<?= esc(layanan_status_icon($detail['status'] ?? 'diajukan')) ?>"></i>
                    <?= esc(layanan_status_label($detail['status'] ?? 'diajukan')) ?>
                </span>
            </div>

            <div class="layanan-panel-body">
                <div class="layanan-detail-grid">

                    <div class="layanan-card">
                        <div class="layanan-card-head">
                            <i class="ri-user-3-fill"></i>
                            Data Warga dan Pengajuan
                        </div>

                        <div class="layanan-card-body">
                            <div class="layanan-info-list">
                                <div class="layanan-info-row">
                                    <span>Nama Lengkap</span>
                                    <span><?= esc($detail['nama_lengkap'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>NIK</span>
                                    <span><?= esc($detail['nik'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Nomor KK</span>
                                    <span><?= esc($detail['nomor_kk'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>TTL</span>
                                    <span><?= esc(layanan_ttl_warga($wargaDetail)) ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Jenis Kelamin</span>
                                    <span><?= esc($detail['i_jenis_kelamin'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Alamat</span>
                                    <span><?= esc(layanan_alamat_warga($wargaDetail)) ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Agama</span>
                                    <span><?= esc($detail['i_agama'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Pekerjaan</span>
                                    <span><?= esc($detail['i_pekerjaan'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Jenis Surat</span>
                                    <span><?= esc($detail['nama_surat'] ?? $detailSurat['nama']) ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Keperluan</span>
                                    <span><?= nl2br(esc($detail['keperluan'] ?? '-')) ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Nomor HP</span>
                                    <span><?= esc($dataTambahan['nomor_hp'] ?? '-') ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Keterangan Tambahan</span>
                                    <span><?= nl2br(esc($dataTambahan['keterangan'] ?? '-')) ?></span>
                                </div>

                                <div class="layanan-info-row">
                                    <span>Tanggal Pengajuan</span>
                                    <span><?= esc(layanan_tanggal_indo($detail['created_at'] ?? '')) ?></span>
                                </div>

                                <?php if (!empty($detail['nomor_surat'])): ?>
                                    <div class="layanan-info-row">
                                        <span>Nomor Surat</span>
                                        <span><?= esc($detail['nomor_surat']) ?></span>
                                    </div>
                                <?php endif; ?>

                                <?php if (!empty($detail['generated_table'])): ?>
                                    <div class="layanan-info-row">
                                        <span>Database Surat</span>
                                        <span>
                                            <?= esc($detail['generated_table']) ?>
                                            #<?= (int)($detail['generated_id'] ?? 0) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div>
                        <div class="layanan-card">
                            <div class="layanan-card-head">
                                <i class="ri-magic-fill"></i>
                                Aksi Surat
                            </div>

                            <div class="layanan-card-body">
                                <div class="layanan-actions" style="min-width:0">
                                    <?php if (empty($detail['generated_id'])): ?>
                                        <form
                                            method="post"
                                            action="admin_layanan_mandiri.php?a=buat"
                                            class="layanan-inline-form"
                                            onsubmit="return confirm('Buat surat otomatis dari pengajuan ini?');"
                                        >
                                            <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                            <input type="hidden" name="id" value="<?= (int)$detail['id'] ?>">

                                            <button type="submit" class="layanan-btn layanan-btn-primary">
                                                <i class="ri-magic-fill"></i>
                                                Buat Surat Otomatis
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <?php if (!empty($detail['file_surat'])): ?>
                                            <a
                                                class="layanan-btn layanan-btn-view"
                                                href="<?= esc(layanan_file_url_admin($detail['file_surat'])) ?>"
                                                target="_blank"
                                                rel="noopener"
                                            >
                                                <i class="ri-printer-fill"></i>
                                                Buka / Cetak Surat
                                            </a>
                                        <?php endif; ?>

                                        <?php if (!empty($detailSurat['template']) && !empty($detail['generated_id'])): ?>
                                            <a
                                                class="layanan-btn layanan-btn-edit"
                                                href="<?= esc($detailSurat['template']) ?>?a=form&id=<?= (int)$detail['generated_id'] ?>"
                                            >
                                                <i class="ri-edit-2-fill"></i>
                                                Edit Data Surat
                                            </a>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <a
                                        class="layanan-btn layanan-btn-ghost"
                                        href="<?= esc($detailSurat['template']) ?>?a=form"
                                    >
                                        <i class="ri-file-add-fill"></i>
                                        Buat Manual
                                    </a>
                                </div>

                                <div class="layanan-note">
                                    <i class="ri-information-fill"></i>
                                    <span>
                                        Tombol Buat Surat Otomatis akan memasukkan data ke tabel surat terkait.
                                        Untuk jenis surat yang butuh data tambahan, admin tetap dapat mengedit data surat setelah dibuat.
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="layanan-card" style="margin-top:18px">
                            <div class="layanan-card-head">
                                <i class="ri-settings-4-fill"></i>
                                Update Status Pengajuan
                            </div>

                            <div class="layanan-card-body">
                                <form
                                    method="post"
                                    action="admin_layanan_mandiri.php?a=status"
                                    class="layanan-status-form"
                                >
                                    <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                    <input type="hidden" name="id" value="<?= (int)$detail['id'] ?>">

                                    <label>
                                        <strong>Status</strong>
                                        <select name="status" class="layanan-input" required>
                                            <?php foreach (['diajukan', 'diproses', 'selesai', 'ditolak'] as $statusOption): ?>
                                                <option value="<?= esc($statusOption) ?>" <?= ($detail['status'] ?? '') === $statusOption ? 'selected' : '' ?>>
                                                    <?= esc(layanan_status_label($statusOption)) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </label>

                                    <label>
                                        <strong>Catatan Admin</strong>
                                        <textarea
                                            name="catatan_admin"
                                            class="layanan-input"
                                            rows="5"
                                            placeholder="Contoh: Silakan datang ke kantor desa untuk mengambil surat asli."
                                        ><?= esc($detail['catatan_admin'] ?? '') ?></textarea>
                                    </label>

                                    <button type="submit" class="layanan-btn layanan-btn-primary">
                                        <i class="ri-save-3-fill"></i>
                                        Simpan Status
                                    </button>
                                </form>
                            </div>
                        </div>

                        <div class="layanan-card" style="margin-top:18px">
                            <div class="layanan-card-head">
                                <i class="ri-delete-bin-6-fill"></i>
                                Hapus Pengajuan
                            </div>

                            <div class="layanan-card-body">
                                <form
                                    method="post"
                                    action="admin_layanan_mandiri.php?a=delete"
                                    onsubmit="return confirm('Yakin ingin menghapus pengajuan ini? Data surat yang sudah dibuat tidak ikut dihapus.');"
                                >
                                    <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                    <input type="hidden" name="id" value="<?= (int)$detail['id'] ?>">

                                    <button type="submit" class="layanan-btn layanan-btn-delete">
                                        <i class="ri-delete-bin-6-fill"></i>
                                        Hapus Pengajuan
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>

    <?php endif; ?>

</div>

<script>
(() => {
    const clockElement = document.getElementById('layananLiveClock');

    const updateClock = () => {
        if (!clockElement) {
            return;
        }

        clockElement.textContent = new Intl.DateTimeFormat(
            'id-ID',
            {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false,
                timeZone: 'Asia/Makassar'
            }
        )
        .format(new Date())
        .replaceAll(':', '.');
    };

    updateClock();
    setInterval(updateClock, 1000);
})();
</script>

<?php include __DIR__.'/../includes/footer.php'; ?>
