<?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 ($act === 'edit') {
    $act = 'form';
}

$tab = $_GET['tab'] ?? $_POST['tab'] ?? 'dokumen';

$tabs = [
    'dokumen' => [
        'label' => 'Dokumen',
        'icon'  => 'ri-file-list-3-fill',
    ],
    'kategori' => [
        'label' => 'Kategori',
        'icon'  => 'ri-price-tag-3-fill',
    ],
    'hukum' => [
        'label' => 'Dasar Hukum',
        'icon'  => 'ri-scales-3-fill',
    ],
    'alur' => [
        'label' => 'Alur Layanan',
        'icon'  => 'ri-route-fill',
    ],
];

if (!isset($tabs[$tab])) {
    $tab = 'dokumen';
}

if (!in_array($act, ['list', 'form', 'save', 'delete'], true)) {
    $act = 'list';
}

$uploadDir = __DIR__.'/../uploads';
$uploadUrl = '../uploads';
$dbUploadPrefix = '/uploads';

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

$csrfToken = $_SESSION['csrf_ppid'];

function ppid_redirect($tab, $msg)
{
    header('Location: ppid.php?tab='.urlencode((string)$tab).'&msg='.urlencode((string)$msg));
    exit;
}

function ppid_tanggal_valid($tanggal)
{
    if ($tanggal === '') {
        return false;
    }

    $date = DateTime::createFromFormat('Y-m-d', (string)$tanggal);

    return $date && $date->format('Y-m-d') === $tanggal;
}

function ppid_tanggal_indo($tanggal)
{
    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',
    ];

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

function ppid_slugify($text)
{
    $text = trim((string)$text);

    if ($text === '') {
        return '';
    }

    if (function_exists('iconv')) {
        $hasilIconv = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);

        if ($hasilIconv !== false) {
            $text = $hasilIconv;
        }
    }

    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);

    return trim((string)$text, '-');
}

function ppid_slug_unik($mysqli, $slug, $excludeId = 0)
{
    $slugDasar = ppid_slugify($slug);

    if ($slugDasar === '') {
        $slugDasar = 'kategori';
    }

    $slugFinal = $slugDasar;
    $nomor = 2;

    while (true) {
        $stmt = $mysqli->prepare("
            SELECT id
            FROM ppid_kategori
            WHERE slug = ?
              AND id <> ?
            LIMIT 1
        ");

        if (!$stmt) {
            return $slugFinal;
        }

        $excludeId = (int)$excludeId;

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

        $result = $stmt->get_result();
        $sudahAda = $result && $result->num_rows > 0;

        $stmt->close();

        if (!$sudahAda) {
            break;
        }

        $slugFinal = $slugDasar.'-'.$nomor;
        $nomor++;
    }

    return $slugFinal;
}

function ppid_file_admin_url($uploadUrl, $filePath)
{
    $filePath = trim((string)$filePath);

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

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

    return rtrim((string)$uploadUrl, '/').'/'.basename($filePath);
}

function ppid_hapus_file($uploadDir, $filePath)
{
    $namaFile = basename(trim((string)$filePath));

    if ($namaFile === '') {
        return;
    }

    $lokasiFile = rtrim((string)$uploadDir, DIRECTORY_SEPARATOR)
        .DIRECTORY_SEPARATOR
        .$namaFile;

    if (is_file($lokasiFile) && file_exists($lokasiFile)) {
        @unlink($lokasiFile);
    }
}

function ppid_upload_file($file, $uploadDir, &$errorText)
{
    if (
        !isset($file['error']) ||
        $file['error'] === UPLOAD_ERR_NO_FILE
    ) {
        return null;
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorText = 'Upload file gagal. Kode kesalahan: '.(int)$file['error'];
        return false;
    }

    if (
        !isset($file['tmp_name']) ||
        !is_uploaded_file($file['tmp_name'])
    ) {
        $errorText = 'File yang diunggah tidak valid.';
        return false;
    }

    $maksimalUkuran = 20 * 1024 * 1024;

    if ((int)$file['size'] > $maksimalUkuran) {
        $errorText = 'Ukuran file maksimal 20 MB.';
        return false;
    }

    $mimeType = '';

    if (class_exists('finfo')) {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);
    } elseif (function_exists('mime_content_type')) {
        $mimeType = mime_content_type($file['tmp_name']);
    }

    $allowedMime = [
        'application/pdf' => 'pdf',
        'application/msword' => 'doc',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
        'application/vnd.ms-excel' => 'xls',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
        'application/vnd.ms-powerpoint' => 'ppt',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
    ];

    $extensionAsli = strtolower(pathinfo((string)($file['name'] ?? ''), PATHINFO_EXTENSION));
    $allowedExt = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];

    if (isset($allowedMime[$mimeType])) {
        $extension = $allowedMime[$mimeType];
    } elseif (in_array($extensionAsli, $allowedExt, true)) {
        $extension = $extensionAsli;
    } else {
        $errorText = 'Format file harus PDF, DOC, DOCX, XLS, XLSX, PPT, atau PPTX.';
        return false;
    }

    if (!is_dir($uploadDir)) {
        $dibuat = mkdir($uploadDir, 0755, true);

        if (!$dibuat && !is_dir($uploadDir)) {
            $errorText = 'Folder uploads tidak dapat dibuat.';
            return false;
        }
    }

    if (!is_writable($uploadDir)) {
        $errorText = 'Folder uploads tidak memiliki izin tulis.';
        return false;
    }

    try {
        $randomName = bin2hex(random_bytes(8));
    } catch (Throwable $e) {
        $randomName = uniqid('', true);
    }

    $namaFileBaru = 'ppid_'
        .date('YmdHis')
        .'_'
        .$randomName
        .'.'
        .$extension;

    $namaFileBaru = preg_replace('/[^a-zA-Z0-9._-]/', '', $namaFileBaru);

    $tujuanUpload = rtrim((string)$uploadDir, DIRECTORY_SEPARATOR)
        .DIRECTORY_SEPARATOR
        .$namaFileBaru;

    if (!move_uploaded_file($file['tmp_name'], $tujuanUpload)) {
        $errorText = 'File gagal dipindahkan ke folder uploads.';
        return false;
    }

    return $namaFileBaru;
}

function ppid_ambil_kategori($mysqli)
{
    $rows = [];
    $result = $mysqli->query("
        SELECT id, judul
        FROM ppid_kategori
        WHERE aktif = 1
        ORDER BY urutan ASC, judul ASC
    ");

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }

    return $rows;
}

function ppid_inisial($text)
{
    $text = trim((string)$text);

    if ($text === '') {
        return 'P';
    }

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

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

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

    if (!isset($tabs[$deleteTab])) {
        $deleteTab = 'dokumen';
    }

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        ppid_redirect($deleteTab, 'csrf');
    }

    if ($id <= 0) {
        ppid_redirect($deleteTab, 'notfound');
    }

    if ($deleteTab === 'dokumen') {
        $fileLama = '';

        $cekStmt = $mysqli->prepare("
            SELECT file_path
            FROM ppid_dokumen
            WHERE id = ?
            LIMIT 1
        ");

        if ($cekStmt) {
            $cekStmt->bind_param('i', $id);
            $cekStmt->execute();

            $cekResult = $cekStmt->get_result();

            if ($cekResult && $dataLama = $cekResult->fetch_assoc()) {
                $fileLama = trim((string)($dataLama['file_path'] ?? ''));
            }

            $cekStmt->close();
        }

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

        if (!$stmt) {
            ppid_redirect($deleteTab, 'error');
        }

        $stmt->bind_param('i', $id);
        $berhasil = $stmt->execute();
        $terhapus = $berhasil && $stmt->affected_rows > 0;
        $stmt->close();

        if ($terhapus && $fileLama !== '') {
            ppid_hapus_file($uploadDir, $fileLama);
        }

        ppid_redirect($deleteTab, $terhapus ? 'deleted' : 'notfound');
    }

    if ($deleteTab === 'kategori') {
        $cekStmt = $mysqli->prepare("
            SELECT COUNT(*) AS total
            FROM ppid_dokumen
            WHERE kategori_id = ?
        ");

        $dipakai = 0;

        if ($cekStmt) {
            $cekStmt->bind_param('i', $id);
            $cekStmt->execute();
            $cekResult = $cekStmt->get_result();
            $dataPakai = $cekResult ? $cekResult->fetch_assoc() : null;
            $dipakai = (int)($dataPakai['total'] ?? 0);
            $cekStmt->close();
        }

        if ($dipakai > 0) {
            ppid_redirect($deleteTab, 'used');
        }

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

        if (!$stmt) {
            ppid_redirect($deleteTab, 'error');
        }

        $stmt->bind_param('i', $id);
        $berhasil = $stmt->execute();
        $terhapus = $berhasil && $stmt->affected_rows > 0;
        $stmt->close();

        ppid_redirect($deleteTab, $terhapus ? 'deleted' : 'notfound');
    }

    if ($deleteTab === 'hukum') {
        $stmt = $mysqli->prepare("
            DELETE FROM ppid_dasar_hukum
            WHERE id = ?
        ");

        if (!$stmt) {
            ppid_redirect($deleteTab, 'error');
        }

        $stmt->bind_param('i', $id);
        $berhasil = $stmt->execute();
        $terhapus = $berhasil && $stmt->affected_rows > 0;
        $stmt->close();

        ppid_redirect($deleteTab, $terhapus ? 'deleted' : 'notfound');
    }

    if ($deleteTab === 'alur') {
        $stmt = $mysqli->prepare("
            DELETE FROM ppid_alur_layanan
            WHERE id = ?
        ");

        if (!$stmt) {
            ppid_redirect($deleteTab, 'error');
        }

        $stmt->bind_param('i', $id);
        $berhasil = $stmt->execute();
        $terhapus = $berhasil && $stmt->affected_rows > 0;
        $stmt->close();

        ppid_redirect($deleteTab, $terhapus ? 'deleted' : 'notfound');
    }
}

$errorText = '';

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

    if (!isset($tabs[$saveTab])) {
        $saveTab = 'dokumen';
    }

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
        $tab = $saveTab;
    }

    if ($errorText === '' && $saveTab === 'dokumen') {
        $kategoriId = (int)($_POST['kategori_id'] ?? 0);
        $judul = trim((string)($_POST['judul'] ?? ''));
        $jenis = trim((string)($_POST['jenis'] ?? ''));
        $tanggal = trim((string)($_POST['tanggal'] ?? ''));
        $status = trim((string)($_POST['status'] ?? 'publish'));
        $urutan = max(0, (int)($_POST['urutan'] ?? 0));

        if ($kategoriId <= 0 || $judul === '' || $jenis === '' || $tanggal === '') {
            $errorText = 'Kategori, judul, jenis, dan tanggal wajib diisi.';
        } elseif (!ppid_tanggal_valid($tanggal)) {
            $errorText = 'Format tanggal tidak valid.';
        } elseif (!in_array($status, ['draft', 'publish'], true)) {
            $errorText = 'Status dokumen tidak valid.';
        }

        $filePathLama = '';
        $dataDitemukan = $id === 0;

        if ($errorText === '' && $id > 0) {
            $cekStmt = $mysqli->prepare("
                SELECT file_path
                FROM ppid_dokumen
                WHERE id = ?
                LIMIT 1
            ");

            if ($cekStmt) {
                $cekStmt->bind_param('i', $id);
                $cekStmt->execute();
                $cekResult = $cekStmt->get_result();

                if ($cekResult && $dataLama = $cekResult->fetch_assoc()) {
                    $dataDitemukan = true;
                    $filePathLama = trim((string)($dataLama['file_path'] ?? ''));
                }

                $cekStmt->close();
            }

            if (!$dataDitemukan) {
                ppid_redirect($saveTab, 'notfound');
            }
        }

        $filePath = $filePathLama;
        $fileBaruPath = '';

        if (
            $errorText === '' &&
            isset($_FILES['file_path']) &&
            $_FILES['file_path']['error'] !== UPLOAD_ERR_NO_FILE
        ) {
            $hasilUpload = ppid_upload_file($_FILES['file_path'], $uploadDir, $errorText);

            if ($hasilUpload !== false && $hasilUpload !== null) {
                $filePath = $dbUploadPrefix.'/'.$hasilUpload;
                $fileBaruPath = $filePath;
            }
        }

        if ($errorText === '' && $filePath === '') {
            $errorText = 'File dokumen wajib diupload.';
        }

        if ($errorText === '') {
            if ($id > 0) {
                $stmt = $mysqli->prepare("
                    UPDATE ppid_dokumen
                    SET
                        kategori_id = ?,
                        judul = ?,
                        jenis = ?,
                        tanggal = ?,
                        file_path = ?,
                        status = ?,
                        urutan = ?
                    WHERE id = ?
                ");

                if (!$stmt) {
                    $errorText = 'Query update dokumen gagal disiapkan: '.$mysqli->error;
                } else {
                    $stmt->bind_param(
                        'isssssii',
                        $kategoriId,
                        $judul,
                        $jenis,
                        $tanggal,
                        $filePath,
                        $status,
                        $urutan,
                        $id
                    );

                    if ($stmt->execute()) {
                        $stmt->close();

                        if ($fileBaruPath !== '' && $filePathLama !== '' && $filePathLama !== $filePath) {
                            ppid_hapus_file($uploadDir, $filePathLama);
                        }

                        ppid_redirect($saveTab, 'updated');
                    }

                    $errorText = 'Dokumen gagal diperbarui: '.$stmt->error;
                    $stmt->close();

                    if ($fileBaruPath !== '') {
                        ppid_hapus_file($uploadDir, $fileBaruPath);
                    }
                }
            } else {
                $stmt = $mysqli->prepare("
                    INSERT INTO ppid_dokumen
                    (
                        kategori_id,
                        judul,
                        jenis,
                        tanggal,
                        file_path,
                        status,
                        urutan
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");

                if (!$stmt) {
                    $errorText = 'Query insert dokumen gagal disiapkan: '.$mysqli->error;
                } else {
                    $stmt->bind_param(
                        'isssssi',
                        $kategoriId,
                        $judul,
                        $jenis,
                        $tanggal,
                        $filePath,
                        $status,
                        $urutan
                    );

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'saved');
                    }

                    $errorText = 'Dokumen gagal disimpan: '.$stmt->error;
                    $stmt->close();

                    if ($fileBaruPath !== '') {
                        ppid_hapus_file($uploadDir, $fileBaruPath);
                    }
                }
            }
        }

        $act = 'form';
        $tab = $saveTab;
    }

    if ($errorText === '' && $saveTab === 'kategori') {
        $judul = trim((string)($_POST['judul'] ?? ''));
        $slugInput = trim((string)($_POST['slug'] ?? ''));
        $ikon = trim((string)($_POST['ikon'] ?? 'ri-file-list-3-line'));
        $deskripsi = trim((string)($_POST['deskripsi'] ?? ''));
        $urutan = max(0, (int)($_POST['urutan'] ?? 0));
        $aktif = isset($_POST['aktif']) ? 1 : 0;

        if ($judul === '') {
            $errorText = 'Judul kategori wajib diisi.';
        }

        if ($ikon === '') {
            $ikon = 'ri-file-list-3-line';
        }

        if ($errorText === '') {
            $slug = ppid_slug_unik($mysqli, $slugInput !== '' ? $slugInput : $judul, $id);

            if ($id > 0) {
                $stmt = $mysqli->prepare("
                    UPDATE ppid_kategori
                    SET
                        slug = ?,
                        judul = ?,
                        ikon = ?,
                        deskripsi = ?,
                        urutan = ?,
                        aktif = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param('ssssiii', $slug, $judul, $ikon, $deskripsi, $urutan, $aktif, $id);

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'updated');
                    }

                    $errorText = 'Kategori gagal diperbarui: '.$stmt->error;
                    $stmt->close();
                } else {
                    $errorText = 'Query update kategori gagal disiapkan: '.$mysqli->error;
                }
            } else {
                $stmt = $mysqli->prepare("
                    INSERT INTO ppid_kategori
                    (
                        slug,
                        judul,
                        ikon,
                        deskripsi,
                        urutan,
                        aktif
                    )
                    VALUES (?, ?, ?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param('ssssii', $slug, $judul, $ikon, $deskripsi, $urutan, $aktif);

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'saved');
                    }

                    $errorText = 'Kategori gagal disimpan: '.$stmt->error;
                    $stmt->close();
                } else {
                    $errorText = 'Query insert kategori gagal disiapkan: '.$mysqli->error;
                }
            }
        }

        $act = 'form';
        $tab = $saveTab;
    }

    if ($errorText === '' && $saveTab === 'hukum') {
        $nomor = trim((string)($_POST['nomor'] ?? ''));
        $judul = trim((string)($_POST['judul'] ?? ''));
        $isi = trim((string)($_POST['isi'] ?? ''));
        $urutan = max(0, (int)($_POST['urutan'] ?? 0));
        $aktif = isset($_POST['aktif']) ? 1 : 0;

        if ($nomor === '' || $judul === '' || $isi === '') {
            $errorText = 'Nomor, judul, dan isi dasar hukum wajib diisi.';
        }

        if ($errorText === '') {
            if ($id > 0) {
                $stmt = $mysqli->prepare("
                    UPDATE ppid_dasar_hukum
                    SET
                        nomor = ?,
                        judul = ?,
                        isi = ?,
                        urutan = ?,
                        aktif = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param('sssiii', $nomor, $judul, $isi, $urutan, $aktif, $id);

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'updated');
                    }

                    $errorText = 'Dasar hukum gagal diperbarui: '.$stmt->error;
                    $stmt->close();
                } else {
                    $errorText = 'Query update dasar hukum gagal disiapkan: '.$mysqli->error;
                }
            } else {
                $stmt = $mysqli->prepare("
                    INSERT INTO ppid_dasar_hukum
                    (
                        nomor,
                        judul,
                        isi,
                        urutan,
                        aktif
                    )
                    VALUES (?, ?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param('sssii', $nomor, $judul, $isi, $urutan, $aktif);

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'saved');
                    }

                    $errorText = 'Dasar hukum gagal disimpan: '.$stmt->error;
                    $stmt->close();
                } else {
                    $errorText = 'Query insert dasar hukum gagal disiapkan: '.$mysqli->error;
                }
            }
        }

        $act = 'form';
        $tab = $saveTab;
    }

    if ($errorText === '' && $saveTab === 'alur') {
        $ikon = trim((string)($_POST['ikon'] ?? 'ri-file-list-3-line'));
        $judul = trim((string)($_POST['judul'] ?? ''));
        $isi = trim((string)($_POST['isi'] ?? ''));
        $urutan = max(0, (int)($_POST['urutan'] ?? 0));
        $aktif = isset($_POST['aktif']) ? 1 : 0;

        if ($judul === '' || $isi === '') {
            $errorText = 'Judul dan isi alur layanan wajib diisi.';
        }

        if ($ikon === '') {
            $ikon = 'ri-file-list-3-line';
        }

        if ($errorText === '') {
            if ($id > 0) {
                $stmt = $mysqli->prepare("
                    UPDATE ppid_alur_layanan
                    SET
                        ikon = ?,
                        judul = ?,
                        isi = ?,
                        urutan = ?,
                        aktif = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param('sssiii', $ikon, $judul, $isi, $urutan, $aktif, $id);

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'updated');
                    }

                    $errorText = 'Alur layanan gagal diperbarui: '.$stmt->error;
                    $stmt->close();
                } else {
                    $errorText = 'Query update alur layanan gagal disiapkan: '.$mysqli->error;
                }
            } else {
                $stmt = $mysqli->prepare("
                    INSERT INTO ppid_alur_layanan
                    (
                        ikon,
                        judul,
                        isi,
                        urutan,
                        aktif
                    )
                    VALUES (?, ?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param('sssii', $ikon, $judul, $isi, $urutan, $aktif);

                    if ($stmt->execute()) {
                        $stmt->close();
                        ppid_redirect($saveTab, 'saved');
                    }

                    $errorText = 'Alur layanan gagal disimpan: '.$stmt->error;
                    $stmt->close();
                } else {
                    $errorText = 'Query insert alur layanan gagal disiapkan: '.$mysqli->error;
                }
            }
        }

        $act = 'form';
        $tab = $saveTab;
    }
}

$edit = null;

if ($act === 'form') {
    $editId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);

    if ($editId > 0) {
        if ($tab === 'dokumen') {
            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_dokumen
                WHERE id = ?
                LIMIT 1
            ");
        } elseif ($tab === 'kategori') {
            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_kategori
                WHERE id = ?
                LIMIT 1
            ");
        } elseif ($tab === 'hukum') {
            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_dasar_hukum
                WHERE id = ?
                LIMIT 1
            ");
        } else {
            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_alur_layanan
                WHERE id = ?
                LIMIT 1
            ");
        }

        if ($stmt) {
            $stmt->bind_param('i', $editId);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result) {
                $edit = $result->fetch_assoc();
            }

            $stmt->close();
        }

        if (!$edit && $errorText === '') {
            ppid_redirect($tab, 'notfound');
        }
    }
}

if (!in_array($act, ['list', 'form'], true)) {
    $act = 'list';
}

$q = trim((string)($_GET['q'] ?? ''));
$list = null;

if ($act === 'list') {
    if ($tab === 'dokumen') {
        if ($q !== '') {
            $like = '%'.$q.'%';

            $stmt = $mysqli->prepare("
                SELECT
                    d.*,
                    k.judul AS kategori_judul,
                    k.slug AS kategori_slug
                FROM ppid_dokumen d
                LEFT JOIN ppid_kategori k ON k.id = d.kategori_id
                WHERE d.judul LIKE ?
                   OR d.jenis LIKE ?
                   OR d.status LIKE ?
                   OR d.tanggal LIKE ?
                   OR k.judul LIKE ?
                ORDER BY d.id DESC
            ");

            if ($stmt) {
                $stmt->bind_param('sssss', $like, $like, $like, $like, $like);
                $stmt->execute();
                $list = $stmt->get_result();
            }
        } else {
            $list = $mysqli->query("
                SELECT
                    d.*,
                    k.judul AS kategori_judul,
                    k.slug AS kategori_slug
                FROM ppid_dokumen d
                LEFT JOIN ppid_kategori k ON k.id = d.kategori_id
                ORDER BY d.id DESC
            ");
        }
    } elseif ($tab === 'kategori') {
        if ($q !== '') {
            $like = '%'.$q.'%';

            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_kategori
                WHERE judul LIKE ?
                   OR slug LIKE ?
                   OR ikon LIKE ?
                   OR deskripsi LIKE ?
                ORDER BY urutan ASC, id DESC
            ");

            if ($stmt) {
                $stmt->bind_param('ssss', $like, $like, $like, $like);
                $stmt->execute();
                $list = $stmt->get_result();
            }
        } else {
            $list = $mysqli->query("
                SELECT *
                FROM ppid_kategori
                ORDER BY urutan ASC, id DESC
            ");
        }
    } elseif ($tab === 'hukum') {
        if ($q !== '') {
            $like = '%'.$q.'%';

            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_dasar_hukum
                WHERE nomor LIKE ?
                   OR judul LIKE ?
                   OR isi LIKE ?
                ORDER BY urutan ASC, id DESC
            ");

            if ($stmt) {
                $stmt->bind_param('sss', $like, $like, $like);
                $stmt->execute();
                $list = $stmt->get_result();
            }
        } else {
            $list = $mysqli->query("
                SELECT *
                FROM ppid_dasar_hukum
                ORDER BY urutan ASC, id DESC
            ");
        }
    } else {
        if ($q !== '') {
            $like = '%'.$q.'%';

            $stmt = $mysqli->prepare("
                SELECT *
                FROM ppid_alur_layanan
                WHERE judul LIKE ?
                   OR ikon LIKE ?
                   OR isi LIKE ?
                ORDER BY urutan ASC, id DESC
            ");

            if ($stmt) {
                $stmt->bind_param('sss', $like, $like, $like);
                $stmt->execute();
                $list = $stmt->get_result();
            }
        } else {
            $list = $mysqli->query("
                SELECT *
                FROM ppid_alur_layanan
                ORDER BY urutan ASC, id DESC
            ");
        }
    }
}

$totalData = $list ? $list->num_rows : 0;
$kategoriOptions = ppid_ambil_kategori($mysqli);

$isEdit = !empty($edit);

$dokumenKategoriValue = $_POST['kategori_id']
    ?? $edit['kategori_id']
    ?? '';

$dokumenJudulValue = $_POST['judul']
    ?? $edit['judul']
    ?? '';

$dokumenJenisValue = $_POST['jenis']
    ?? $edit['jenis']
    ?? '';

$dokumenTanggalValue = $_POST['tanggal']
    ?? $edit['tanggal']
    ?? date('Y-m-d');

$dokumenStatusValue = $_POST['status']
    ?? $edit['status']
    ?? 'publish';

$dokumenUrutanValue = $_POST['urutan']
    ?? $edit['urutan']
    ?? 0;

$dokumenFileValue = $edit['file_path']
    ?? '';

$kategoriJudulValue = $_POST['judul']
    ?? $edit['judul']
    ?? '';

$kategoriSlugValue = $_POST['slug']
    ?? $edit['slug']
    ?? '';

$kategoriIkonValue = $_POST['ikon']
    ?? $edit['ikon']
    ?? 'ri-file-list-3-line';

$kategoriDeskripsiValue = $_POST['deskripsi']
    ?? $edit['deskripsi']
    ?? '';

$kategoriUrutanValue = $_POST['urutan']
    ?? $edit['urutan']
    ?? 0;

$kategoriAktifValue = isset($_POST['aktif'])
    ? 1
    : ($edit['aktif'] ?? 1);

$hukumNomorValue = $_POST['nomor']
    ?? $edit['nomor']
    ?? '';

$hukumJudulValue = $_POST['judul']
    ?? $edit['judul']
    ?? '';

$hukumIsiValue = $_POST['isi']
    ?? $edit['isi']
    ?? '';

$hukumUrutanValue = $_POST['urutan']
    ?? $edit['urutan']
    ?? 0;

$hukumAktifValue = isset($_POST['aktif'])
    ? 1
    : ($edit['aktif'] ?? 1);

$alurIkonValue = $_POST['ikon']
    ?? $edit['ikon']
    ?? 'ri-file-search-line';

$alurJudulValue = $_POST['judul']
    ?? $edit['judul']
    ?? '';

$alurIsiValue = $_POST['isi']
    ?? $edit['isi']
    ?? '';

$alurUrutanValue = $_POST['urutan']
    ?? $edit['urutan']
    ?? 0;

$alurAktifValue = isset($_POST['aktif'])
    ? 1
    : ($edit['aktif'] ?? 1);

$msgKey = $_GET['msg'] ?? '';

$msgText = [
    'saved' => 'Data PPID berhasil ditambahkan.',
    'updated' => 'Data PPID berhasil diperbarui.',
    'deleted' => 'Data PPID berhasil dihapus.',
    'notfound' => 'Data PPID tidak ditemukan.',
    'csrf' => 'Token keamanan tidak valid. Silakan ulangi proses.',
    'used' => 'Kategori tidak dapat dihapus karena masih digunakan oleh dokumen.',
    'error' => 'Terjadi kesalahan saat memproses data PPID.',
][$msgKey] ?? '';

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

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 {
    --ppid-green-950: #002818;
    --ppid-green-900: #003d22;
    --ppid-green-800: #005530;
    --ppid-green-700: #047a3d;
    --ppid-green-600: #09a04f;
    --ppid-green-500: #15c46a;
    --ppid-green-400: #35e085;
    --ppid-green-100: #dcfaee;
    --ppid-green-50: #edfff5;
    --ppid-blue-500: #2080e8;
    --ppid-yellow-500: #f5b400;
    --ppid-orange-500: #f26b1d;
    --ppid-red-500: #dc3545;
    --ppid-ink: #0f1c16;
    --ppid-muted: #5e6e67;
    --ppid-line: #daeae1;
    --ppid-surface: #ffffff;
    --ppid-page: #f3faf6;
    --ppid-shadow: 0 8px 28px rgba(10, 40, 25, .10);
    --ppid-radius: 16px;
}

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

@keyframes ppid-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(--ppid-ink);
    background-color: var(--ppid-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;
}

.ppid-page {
    padding: 26px;
}

.ppid-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(--ppid-green-950), var(--ppid-green-800), var(--ppid-green-900));
    background-size: 200% 100%;
    border-radius: var(--ppid-radius);
    box-shadow: 0 14px 40px rgba(0, 60, 30, .28);
    animation: ppid-gradient 8s ease infinite;
}

.ppid-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%;
}

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

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

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

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

.ppid-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;
}

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

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

.ppid-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);
}

.ppid-tabs {
    margin-bottom: 18px;
    display: flex;
    flex-wrap: wrap;
    gap: 9px;
}

.ppid-tab {
    padding: 11px 14px;
    display: inline-flex;
    align-items: center;
    gap: 7px;
    color: var(--ppid-green-800);
    background: #fff;
    border: 1px solid var(--ppid-line);
    border-radius: 13px;
    text-decoration: none;
    font-size: 13px;
    font-weight: 800;
    box-shadow: 0 5px 16px rgba(10, 40, 25, .06);
}

.ppid-tab-active {
    color: #fff;
    background: linear-gradient(135deg, var(--ppid-green-500), var(--ppid-green-800));
    border-color: transparent;
}

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

.ppid-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(--ppid-line);
}

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

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

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

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

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

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

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

.ppid-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;
}

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

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

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

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

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

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

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

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

.ppid-toolbar {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
}

.ppid-search {
    position: relative;
    min-width: 260px;
    flex: 1;
}

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

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

.ppid-stat {
    padding: 10px 14px;
    display: inline-flex;
    align-items: center;
    gap: 7px;
    color: var(--ppid-green-800);
    background: var(--ppid-green-50);
    border: 1px solid var(--ppid-green-100);
    border-radius: 999px;
    font-size: 13px;
    font-weight: 800;
}

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

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

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

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

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

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

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

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

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

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

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

.ppid-badge-green {
    color: #08743b;
    background: #dcfaee;
    border: 1px solid #b9f0d6;
}

.ppid-badge-yellow {
    color: #a35d00;
    background: #fff5d8;
    border: 1px solid #ffe5a0;
}

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

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

.ppid-delete-form {
    margin: 0;
}

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

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

.ppid-form {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

.ppid-field {
    display: flex;
    flex-direction: column;
    gap: 7px;
}

.ppid-field-full {
    grid-column: 1 / -1;
}

.ppid-field label {
    color: var(--ppid-ink);
    font-size: 13px;
    font-weight: 800;
}

.ppid-required {
    color: var(--ppid-orange-500);
}

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

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

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

.ppid-section {
    grid-column: 1 / -1;
    padding: 12px 14px;
    display: flex;
    align-items: center;
    gap: 9px;
    color: var(--ppid-green-900);
    background: var(--ppid-green-50);
    border: 1px solid var(--ppid-green-100);
    border-radius: 13px;
    font-size: 13px;
    font-weight: 800;
}

.ppid-upload-box {
    padding: 16px;
    background: #f8fffb;
    border: 1px dashed var(--ppid-green-500);
    border-radius: 14px;
}

.ppid-help {
    margin: 5px 0 0;
    color: var(--ppid-muted);
    font-size: 11px;
    font-weight: 600;
    line-height: 1.5;
}

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

.ppid-form-actions {
    grid-column: 1 / -1;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.ppid-checkbox {
    margin-top: 4px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: var(--ppid-green-800);
    font-size: 13px;
    font-weight: 800;
}

.ppid-checkbox input {
    width: 16px;
    height: 16px;
}

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

    .ppid-header {
        padding: 20px;
    }

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

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

    .ppid-toolbar {
        align-items: stretch;
    }

    .ppid-search,
    .ppid-stat {
        width: 100%;
    }

    .ppid-form {
        grid-template-columns: 1fr;
    }

    .ppid-field-full,
    .ppid-section,
    .ppid-note,
    .ppid-form-actions {
        grid-column: 1;
    }

    .ppid-actions {
        min-width: 230px;
    }
}
</style>

<div class="ppid-page">

    <div class="ppid-header">
        <div class="ppid-header-left">
            <p class="ppid-eyebrow">
                <i class="ri-file-list-3-fill"></i>
                Pengelola Informasi Publik
            </p>

            <h2>
                <i class="ri-file-shield-2-fill ppid-title-icon"></i>
                Admin PPID
            </h2>

            <p class="ppid-description">
                <span class="ppid-live-dot"></span>
                Kelola dokumen, kategori, dasar hukum, dan alur layanan PPID
            </p>
        </div>

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

            <?php if ($act === 'list'): ?>
                <a
                    class="ppid-btn ppid-btn-light"
                    href="ppid.php?tab=<?= esc($tab) ?>&a=form"
                >
                    <i class="ri-add-circle-fill"></i>
                    Tambah <?= esc($tabs[$tab]['label']) ?>
                </a>
            <?php else: ?>
                <a
                    class="ppid-btn ppid-btn-light"
                    href="ppid.php?tab=<?= esc($tab) ?>"
                >
                    <i class="ri-arrow-left-line"></i>
                    Kembali
                </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="ppid-tabs">
        <?php foreach ($tabs as $key => $item): ?>
            <a
                class="ppid-tab <?= $tab === $key ? 'ppid-tab-active' : '' ?>"
                href="ppid.php?tab=<?= esc($key) ?>"
            >
                <i class="<?= esc($item['icon']) ?>"></i>
                <?= esc($item['label']) ?>
            </a>
        <?php endforeach; ?>
    </div>

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

    <?php if ($errorText): ?>
        <div class="ppid-alert ppid-alert-error">
            <i class="ri-error-warning-fill"></i>
            <?= esc($errorText) ?>
        </div>
    <?php endif; ?>

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

        <div class="ppid-panel">
            <div class="ppid-panel-head">
                <div class="ppid-panel-title">
                    <div class="ppid-panel-icon">
                        <i class="<?= esc($tabs[$tab]['icon']) ?>"></i>
                    </div>

                    <div>
                        <h3>Daftar <?= esc($tabs[$tab]['label']) ?></h3>
                        <p>Data yang digunakan pada halaman PPID pengguna.</p>
                    </div>
                </div>

                <div class="ppid-stat">
                    <i class="<?= esc($tabs[$tab]['icon']) ?>"></i>
                    <?= (int)$totalData ?> Data
                </div>
            </div>

            <div class="ppid-panel-body">
                <div class="ppid-toolbar">
                    <form
                        method="get"
                        action="ppid.php"
                        class="ppid-search"
                    >
                        <input type="hidden" name="tab" value="<?= esc($tab) ?>">
                        <i class="ri-search-line"></i>
                        <input
                            type="text"
                            name="q"
                            value="<?= esc($q) ?>"
                            placeholder="Cari data PPID..."
                            autocomplete="off"
                        >
                    </form>
                </div>

                <div class="ppid-table-wrap">
                    <table class="ppid-table">
                        <thead>
                            <?php if ($tab === 'dokumen'): ?>
                                <tr>
                                    <th>No</th>
                                    <th>Judul Dokumen</th>
                                    <th>Kategori</th>
                                    <th>Tanggal</th>
                                    <th>Status</th>
                                    <th>Unduh</th>
                                    <th>Aksi</th>
                                </tr>
                            <?php elseif ($tab === 'kategori'): ?>
                                <tr>
                                    <th>No</th>
                                    <th>Kategori</th>
                                    <th>Ikon</th>
                                    <th>Urutan</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            <?php elseif ($tab === 'hukum'): ?>
                                <tr>
                                    <th>No</th>
                                    <th>Dasar Hukum</th>
                                    <th>Nomor</th>
                                    <th>Urutan</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <th>No</th>
                                    <th>Alur Layanan</th>
                                    <th>Ikon</th>
                                    <th>Urutan</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            <?php endif; ?>
                        </thead>

                        <tbody>
                            <?php if ($totalData === 0): ?>
                                <tr>
                                    <td
                                        colspan="<?= $tab === 'dokumen' ? '7' : '6' ?>"
                                        class="ppid-empty"
                                    >
                                        <i class="ri-inbox-2-fill"></i>
                                        <?= $q !== ''
                                            ? 'Data yang dicari tidak ditemukan.'
                                            : 'Belum ada data. Klik tombol Tambah untuk membuat data baru.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                <?php while ($row = $list->fetch_assoc()): ?>

                                    <?php if ($tab === 'dokumen'): ?>
                                        <tr>
                                            <td><?= $no++ ?></td>

                                            <td>
                                                <div class="ppid-title-wrap">
                                                    <div class="ppid-avatar">
                                                        <?= esc(ppid_inisial($row['judul'] ?? 'P')) ?>
                                                    </div>

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

                                                        <div class="ppid-subtitle">
                                                            <?= esc($row['jenis'] ?? '') ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>

                                            <td>
                                                <span class="ppid-badge ppid-badge-blue">
                                                    <i class="ri-price-tag-3-fill"></i>
                                                    <?= esc($row['kategori_judul'] ?? '-') ?>
                                                </span>
                                            </td>

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

                                            <td>
                                                <?php if (($row['status'] ?? '') === 'publish'): ?>
                                                    <span class="ppid-badge ppid-badge-green">
                                                        <i class="ri-checkbox-circle-fill"></i>
                                                        Publish
                                                    </span>
                                                <?php else: ?>
                                                    <span class="ppid-badge ppid-badge-yellow">
                                                        <i class="ri-draft-fill"></i>
                                                        Draft
                                                    </span>
                                                <?php endif; ?>
                                            </td>

                                            <td>
                                                <span class="ppid-badge ppid-badge-green">
                                                    <i class="ri-download-2-fill"></i>
                                                    <?= (int)($row['jumlah_unduh'] ?? 0) ?>x
                                                </span>
                                            </td>

                                            <td>
                                                <div class="ppid-actions">
                                                    <?php if (!empty($row['file_path'])): ?>
                                                        <a
                                                            class="ppid-btn ppid-btn-small ppid-btn-view"
                                                            href="<?= esc(ppid_file_admin_url($uploadUrl, $row['file_path'])) ?>"
                                                            target="_blank"
                                                            rel="noopener"
                                                        >
                                                            <i class="ri-eye-fill"></i>
                                                            Lihat
                                                        </a>
                                                    <?php endif; ?>

                                                    <a
                                                        class="ppid-btn ppid-btn-small ppid-btn-edit"
                                                        href="ppid.php?tab=dokumen&a=form&id=<?= (int)$row['id'] ?>"
                                                    >
                                                        <i class="ri-edit-2-fill"></i>
                                                        Edit
                                                    </a>

                                                    <form
                                                        method="post"
                                                        action="ppid.php?a=delete"
                                                        class="ppid-delete-form"
                                                        onsubmit="return confirm('Yakin ingin menghapus dokumen PPID ini? File upload juga akan dihapus dan data tidak dapat dikembalikan.');"
                                                    >
                                                        <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                                        <input type="hidden" name="tab" value="dokumen">
                                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                                        <button
                                                            type="submit"
                                                            class="ppid-btn ppid-btn-small ppid-btn-delete"
                                                        >
                                                            <i class="ri-delete-bin-6-fill"></i>
                                                            Hapus
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php elseif ($tab === 'kategori'): ?>
                                        <tr>
                                            <td><?= $no++ ?></td>

                                            <td>
                                                <div class="ppid-title-wrap">
                                                    <div class="ppid-avatar">
                                                        <?= esc(ppid_inisial($row['judul'] ?? 'K')) ?>
                                                    </div>

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

                                                        <div class="ppid-subtitle">
                                                            /<?= esc($row['slug'] ?? '') ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>

                                            <td>
                                                <span class="ppid-badge ppid-badge-blue">
                                                    <i class="<?= esc($row['ikon'] ?? 'ri-file-list-3-line') ?>"></i>
                                                    <?= esc($row['ikon'] ?? '') ?>
                                                </span>
                                            </td>

                                            <td><?= (int)($row['urutan'] ?? 0) ?></td>

                                            <td>
                                                <?php if ((int)($row['aktif'] ?? 0) === 1): ?>
                                                    <span class="ppid-badge ppid-badge-green">
                                                        <i class="ri-checkbox-circle-fill"></i>
                                                        Aktif
                                                    </span>
                                                <?php else: ?>
                                                    <span class="ppid-badge ppid-badge-yellow">
                                                        <i class="ri-indeterminate-circle-fill"></i>
                                                        Nonaktif
                                                    </span>
                                                <?php endif; ?>
                                            </td>

                                            <td>
                                                <div class="ppid-actions">
                                                    <a
                                                        class="ppid-btn ppid-btn-small ppid-btn-edit"
                                                        href="ppid.php?tab=kategori&a=form&id=<?= (int)$row['id'] ?>"
                                                    >
                                                        <i class="ri-edit-2-fill"></i>
                                                        Edit
                                                    </a>

                                                    <form
                                                        method="post"
                                                        action="ppid.php?a=delete"
                                                        class="ppid-delete-form"
                                                        onsubmit="return confirm('Yakin ingin menghapus kategori ini?');"
                                                    >
                                                        <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                                        <input type="hidden" name="tab" value="kategori">
                                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                                        <button
                                                            type="submit"
                                                            class="ppid-btn ppid-btn-small ppid-btn-delete"
                                                        >
                                                            <i class="ri-delete-bin-6-fill"></i>
                                                            Hapus
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php elseif ($tab === 'hukum'): ?>
                                        <tr>
                                            <td><?= $no++ ?></td>

                                            <td>
                                                <div class="ppid-title-wrap">
                                                    <div class="ppid-avatar">
                                                        <?= esc($row['nomor'] ?? 'H') ?>
                                                    </div>

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

                                                        <div class="ppid-subtitle">
                                                            <?= esc(strip_tags($row['isi'] ?? '')) ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>

                                            <td><?= esc($row['nomor'] ?? '') ?></td>
                                            <td><?= (int)($row['urutan'] ?? 0) ?></td>

                                            <td>
                                                <?php if ((int)($row['aktif'] ?? 0) === 1): ?>
                                                    <span class="ppid-badge ppid-badge-green">
                                                        <i class="ri-checkbox-circle-fill"></i>
                                                        Aktif
                                                    </span>
                                                <?php else: ?>
                                                    <span class="ppid-badge ppid-badge-yellow">
                                                        <i class="ri-indeterminate-circle-fill"></i>
                                                        Nonaktif
                                                    </span>
                                                <?php endif; ?>
                                            </td>

                                            <td>
                                                <div class="ppid-actions">
                                                    <a
                                                        class="ppid-btn ppid-btn-small ppid-btn-edit"
                                                        href="ppid.php?tab=hukum&a=form&id=<?= (int)$row['id'] ?>"
                                                    >
                                                        <i class="ri-edit-2-fill"></i>
                                                        Edit
                                                    </a>

                                                    <form
                                                        method="post"
                                                        action="ppid.php?a=delete"
                                                        class="ppid-delete-form"
                                                        onsubmit="return confirm('Yakin ingin menghapus dasar hukum ini?');"
                                                    >
                                                        <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                                        <input type="hidden" name="tab" value="hukum">
                                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                                        <button
                                                            type="submit"
                                                            class="ppid-btn ppid-btn-small ppid-btn-delete"
                                                        >
                                                            <i class="ri-delete-bin-6-fill"></i>
                                                            Hapus
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <tr>
                                            <td><?= $no++ ?></td>

                                            <td>
                                                <div class="ppid-title-wrap">
                                                    <div class="ppid-avatar">
                                                        <?= esc(ppid_inisial($row['judul'] ?? 'A')) ?>
                                                    </div>

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

                                                        <div class="ppid-subtitle">
                                                            <?= esc(strip_tags($row['isi'] ?? '')) ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>

                                            <td>
                                                <span class="ppid-badge ppid-badge-blue">
                                                    <i class="<?= esc($row['ikon'] ?? 'ri-file-list-3-line') ?>"></i>
                                                    <?= esc($row['ikon'] ?? '') ?>
                                                </span>
                                            </td>

                                            <td><?= (int)($row['urutan'] ?? 0) ?></td>

                                            <td>
                                                <?php if ((int)($row['aktif'] ?? 0) === 1): ?>
                                                    <span class="ppid-badge ppid-badge-green">
                                                        <i class="ri-checkbox-circle-fill"></i>
                                                        Aktif
                                                    </span>
                                                <?php else: ?>
                                                    <span class="ppid-badge ppid-badge-yellow">
                                                        <i class="ri-indeterminate-circle-fill"></i>
                                                        Nonaktif
                                                    </span>
                                                <?php endif; ?>
                                            </td>

                                            <td>
                                                <div class="ppid-actions">
                                                    <a
                                                        class="ppid-btn ppid-btn-small ppid-btn-edit"
                                                        href="ppid.php?tab=alur&a=form&id=<?= (int)$row['id'] ?>"
                                                    >
                                                        <i class="ri-edit-2-fill"></i>
                                                        Edit
                                                    </a>

                                                    <form
                                                        method="post"
                                                        action="ppid.php?a=delete"
                                                        class="ppid-delete-form"
                                                        onsubmit="return confirm('Yakin ingin menghapus alur layanan ini?');"
                                                    >
                                                        <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                                                        <input type="hidden" name="tab" value="alur">
                                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

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

                                <?php endwhile; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    <?php else: ?>

        <div class="ppid-panel">
            <div class="ppid-panel-head">
                <div class="ppid-panel-title">
                    <div class="ppid-panel-icon">
                        <i class="<?= $isEdit ? 'ri-edit-2-fill' : 'ri-draft-fill' ?>"></i>
                    </div>

                    <div>
                        <h3>
                            <?= $isEdit
                                ? 'Edit '.$tabs[$tab]['label']
                                : 'Tambah '.$tabs[$tab]['label'] ?>
                        </h3>

                        <p>Lengkapi data yang akan ditampilkan pada halaman PPID.</p>
                    </div>
                </div>
            </div>

            <div class="ppid-panel-body">
                <form
                    method="post"
                    action="ppid.php?a=save"
                    enctype="multipart/form-data"
                    class="ppid-form"
                    id="ppidForm"
                >
                    <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                    <input type="hidden" name="tab" value="<?= esc($tab) ?>">
                    <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">

                    <?php if ($tab === 'dokumen'): ?>

                        <div class="ppid-section">
                            <i class="ri-file-paper-2-fill"></i>
                            Informasi Dokumen
                        </div>

                        <div class="ppid-field">
                            <label for="kategori_id">
                                Kategori
                                <span class="ppid-required">*</span>
                            </label>

                            <select
                                class="ppid-input"
                                id="kategori_id"
                                name="kategori_id"
                                required
                            >
                                <option value="">Pilih kategori</option>

                                <?php foreach ($kategoriOptions as $kategoriOption): ?>
                                    <option
                                        value="<?= (int)$kategoriOption['id'] ?>"
                                        <?= (int)$dokumenKategoriValue === (int)$kategoriOption['id'] ? 'selected' : '' ?>
                                    >
                                        <?= esc($kategoriOption['judul']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>

                            <p class="ppid-help">
                                Tambahkan kategori terlebih dahulu jika pilihan belum tersedia.
                            </p>
                        </div>

                        <div class="ppid-field">
                            <label for="tanggal">
                                Tanggal
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="date"
                                class="ppid-input"
                                id="tanggal"
                                name="tanggal"
                                value="<?= esc($dokumenTanggalValue) ?>"
                                required
                            >
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="judul">
                                Judul Dokumen
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="judul"
                                name="judul"
                                value="<?= esc($dokumenJudulValue) ?>"
                                maxlength="255"
                                placeholder="Contoh: APBDes Desa Mambu T.A 2024"
                                required
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="jenis">
                                Jenis Informasi
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="jenis"
                                name="jenis"
                                value="<?= esc($dokumenJenisValue) ?>"
                                maxlength="160"
                                placeholder="Contoh: Anggaran Pendapatan dan Belanja Desa"
                                required
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="status">
                                Status
                                <span class="ppid-required">*</span>
                            </label>

                            <select
                                class="ppid-input"
                                id="status"
                                name="status"
                                required
                            >
                                <option
                                    value="draft"
                                    <?= $dokumenStatusValue === 'draft' ? 'selected' : '' ?>
                                >
                                    Draft
                                </option>

                                <option
                                    value="publish"
                                    <?= $dokumenStatusValue === 'publish' ? 'selected' : '' ?>
                                >
                                    Publish
                                </option>
                            </select>
                        </div>

                        <div class="ppid-field">
                            <label for="urutan">
                                Urutan
                            </label>

                            <input
                                type="number"
                                class="ppid-input"
                                id="urutan"
                                name="urutan"
                                value="<?= (int)$dokumenUrutanValue ?>"
                                min="0"
                            >
                        </div>

                        <div class="ppid-section">
                            <i class="ri-upload-cloud-2-fill"></i>
                            File Dokumen
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <div class="ppid-upload-box">
                                <label for="file_path">
                                    Upload File
                                    <?= $isEdit ? '' : '<span class="ppid-required">*</span>' ?>
                                </label>

                                <input
                                    type="file"
                                    class="ppid-input"
                                    id="file_path"
                                    name="file_path"
                                    accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,application/pdf"
                                    <?= $isEdit ? '' : 'required' ?>
                                >

                                <p class="ppid-help">
                                    File masuk ke folder admin/uploads dan database menyimpan path /uploads/nama-file.
                                    Format PDF, DOC, DOCX, XLS, XLSX, PPT, atau PPTX. Maksimal 20 MB.
                                </p>

                                <?php if ($dokumenFileValue !== ''): ?>
                                    <p class="ppid-help">
                                        File saat ini:
                                        <a
                                            href="<?= esc(ppid_file_admin_url($uploadUrl, $dokumenFileValue)) ?>"
                                            target="_blank"
                                            rel="noopener"
                                        >
                                            <?= esc(basename($dokumenFileValue)) ?>
                                        </a>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="ppid-note">
                            <i class="ri-information-fill"></i>
                            <span>
                                Dokumen berstatus Draft tidak tampil di halaman pengguna.
                                Gunakan status Publish untuk menampilkan dokumen kepada masyarakat.
                            </span>
                        </div>

                    <?php elseif ($tab === 'kategori'): ?>

                        <div class="ppid-section">
                            <i class="ri-price-tag-3-fill"></i>
                            Informasi Kategori
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="judul">
                                Judul Kategori
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="judul"
                                name="judul"
                                value="<?= esc($kategoriJudulValue) ?>"
                                maxlength="150"
                                placeholder="Contoh: Informasi Secara Berkala"
                                required
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="slug">
                                Slug
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="slug"
                                name="slug"
                                value="<?= esc($kategoriSlugValue) ?>"
                                maxlength="60"
                                placeholder="Otomatis dari judul"
                            >

                            <p class="ppid-help">
                                Kosongkan agar slug dibuat otomatis dari judul.
                            </p>
                        </div>

                        <div class="ppid-field">
                            <label for="ikon">
                                Ikon Remixicon
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="ikon"
                                name="ikon"
                                value="<?= esc($kategoriIkonValue) ?>"
                                maxlength="80"
                                placeholder="ri-folder-open-line"
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="urutan">
                                Urutan
                            </label>

                            <input
                                type="number"
                                class="ppid-input"
                                id="urutan"
                                name="urutan"
                                value="<?= (int)$kategoriUrutanValue ?>"
                                min="0"
                            >
                        </div>

                        <div class="ppid-field">
                            <label>Status</label>

                            <label class="ppid-checkbox">
                                <input
                                    type="checkbox"
                                    name="aktif"
                                    value="1"
                                    <?= (int)$kategoriAktifValue === 1 ? 'checked' : '' ?>
                                >
                                Aktif
                            </label>
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="deskripsi">
                                Deskripsi
                            </label>

                            <textarea
                                class="ppid-input"
                                id="deskripsi"
                                name="deskripsi"
                                rows="5"
                                placeholder="Deskripsi singkat kategori"
                            ><?= esc($kategoriDeskripsiValue) ?></textarea>
                        </div>

                    <?php elseif ($tab === 'hukum'): ?>

                        <div class="ppid-section">
                            <i class="ri-scales-3-fill"></i>
                            Informasi Dasar Hukum
                        </div>

                        <div class="ppid-field">
                            <label for="nomor">
                                Nomor
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="nomor"
                                name="nomor"
                                value="<?= esc($hukumNomorValue) ?>"
                                maxlength="10"
                                placeholder="01"
                                required
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="urutan">
                                Urutan
                            </label>

                            <input
                                type="number"
                                class="ppid-input"
                                id="urutan"
                                name="urutan"
                                value="<?= (int)$hukumUrutanValue ?>"
                                min="0"
                            >
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="judul">
                                Judul Dasar Hukum
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="judul"
                                name="judul"
                                value="<?= esc($hukumJudulValue) ?>"
                                maxlength="255"
                                placeholder="Contoh: Undang-Undang Nomor 14 Tahun 2008"
                                required
                            >
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="isi">
                                Isi / Keterangan
                                <span class="ppid-required">*</span>
                            </label>

                            <textarea
                                class="ppid-input"
                                id="isi"
                                name="isi"
                                rows="6"
                                placeholder="Tentang Keterbukaan Informasi Publik."
                                required
                            ><?= esc($hukumIsiValue) ?></textarea>
                        </div>

                        <div class="ppid-field">
                            <label>Status</label>

                            <label class="ppid-checkbox">
                                <input
                                    type="checkbox"
                                    name="aktif"
                                    value="1"
                                    <?= (int)$hukumAktifValue === 1 ? 'checked' : '' ?>
                                >
                                Aktif
                            </label>
                        </div>

                    <?php else: ?>

                        <div class="ppid-section">
                            <i class="ri-route-fill"></i>
                            Informasi Alur Layanan
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="judul">
                                Judul Alur
                                <span class="ppid-required">*</span>
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="judul"
                                name="judul"
                                value="<?= esc($alurJudulValue) ?>"
                                maxlength="150"
                                placeholder="Contoh: Pilih Informasi"
                                required
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="ikon">
                                Ikon Remixicon
                            </label>

                            <input
                                type="text"
                                class="ppid-input"
                                id="ikon"
                                name="ikon"
                                value="<?= esc($alurIkonValue) ?>"
                                maxlength="80"
                                placeholder="ri-file-search-line"
                            >
                        </div>

                        <div class="ppid-field">
                            <label for="urutan">
                                Urutan
                            </label>

                            <input
                                type="number"
                                class="ppid-input"
                                id="urutan"
                                name="urutan"
                                value="<?= (int)$alurUrutanValue ?>"
                                min="0"
                            >
                        </div>

                        <div class="ppid-field ppid-field-full">
                            <label for="isi">
                                Isi / Keterangan
                                <span class="ppid-required">*</span>
                            </label>

                            <textarea
                                class="ppid-input"
                                id="isi"
                                name="isi"
                                rows="6"
                                placeholder="Penjelasan alur layanan"
                                required
                            ><?= esc($alurIsiValue) ?></textarea>
                        </div>

                        <div class="ppid-field">
                            <label>Status</label>

                            <label class="ppid-checkbox">
                                <input
                                    type="checkbox"
                                    name="aktif"
                                    value="1"
                                    <?= (int)$alurAktifValue === 1 ? 'checked' : '' ?>
                                >
                                Aktif
                            </label>
                        </div>

                    <?php endif; ?>

                    <div class="ppid-form-actions">
                        <button
                            type="submit"
                            class="ppid-btn ppid-btn-primary"
                        >
                            <i class="ri-save-3-fill"></i>
                            <?= $isEdit ? 'Perbarui Data' : 'Simpan Data' ?>
                        </button>

                        <a
                            class="ppid-btn ppid-btn-ghost"
                            href="ppid.php?tab=<?= esc($tab) ?>"
                        >
                            <i class="ri-close-circle-fill"></i>
                            Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>

    <?php endif; ?>

</div>

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

    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);

    const judulInput = document.getElementById('judul');
    const slugInput = document.getElementById('slug');

    const slugify = (text) => {
        return text
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    };

    if (judulInput && slugInput) {
        let slugDiubahManual = slugInput.value.trim() !== '';

        slugInput.addEventListener('input', function () {
            slugDiubahManual = this.value.trim() !== '';
        });

        judulInput.addEventListener('input', function () {
            if (!slugDiubahManual) {
                slugInput.value = slugify(this.value);
            }
        });
    }

    const fileInput = document.getElementById('file_path');

    if (fileInput) {
        fileInput.addEventListener('change', function () {
            const file = this.files && this.files.length > 0
                ? this.files[0]
                : null;

            if (!file) {
                return;
            }

            const allowedExt = [
                'pdf',
                'doc',
                'docx',
                'xls',
                'xlsx',
                'ppt',
                'pptx'
            ];

            const ext = file.name
                .split('.')
                .pop()
                .toLowerCase();

            if (!allowedExt.includes(ext)) {
                alert('Format file harus PDF, DOC, DOCX, XLS, XLSX, PPT, atau PPTX.');
                this.value = '';
                return;
            }

            if (file.size > 20 * 1024 * 1024) {
                alert('Ukuran file maksimal 20 MB.');
                this.value = '';
            }
        });
    }
})();
</script>

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