<?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';
}

if ($act === 'del') {
    $act = 'delete';
}

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


/* =========================================================
   KONFIGURASI
========================================================= */

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

if (empty($_SESSION['csrf_pustaka'])) {
    try {
        $_SESSION['csrf_pustaka'] = bin2hex(
            random_bytes(32)
        );
    } catch (Throwable $e) {
        $_SESSION['csrf_pustaka'] = hash(
            'sha256',
            uniqid('', true).microtime(true)
        );
    }
}

$csrfToken = $_SESSION['csrf_pustaka'];


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

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

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

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

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

    if (function_exists('mb_strtolower')) {
        $text = mb_strtolower($text, 'UTF-8');
    } else {
        $text = strtolower($text);
    }

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

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

function pustaka_slug_unik(
    $mysqli,
    $slug,
    $excludeId = 0
) {
    $slugDasar = pustaka_slugify($slug);

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

    $slugFinal = $slugDasar;
    $nomor = 2;

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

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

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

        $stmt->execute();
        $stmt->store_result();

        $sudahAda = $stmt->num_rows > 0;

        $stmt->close();

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

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

function pustaka_pesan_upload($kode)
{
    $pesan = [
        UPLOAD_ERR_INI_SIZE =>
            'Ukuran file melebihi batas server.',
        UPLOAD_ERR_FORM_SIZE =>
            'Ukuran file melebihi batas formulir.',
        UPLOAD_ERR_PARTIAL =>
            'File hanya terunggah sebagian.',
        UPLOAD_ERR_NO_FILE =>
            'Tidak ada file yang dipilih.',
        UPLOAD_ERR_NO_TMP_DIR =>
            'Folder sementara upload tidak tersedia.',
        UPLOAD_ERR_CANT_WRITE =>
            'Server gagal menulis file.',
        UPLOAD_ERR_EXTENSION =>
            'Upload dihentikan oleh ekstensi server.'
    ];

    return $pesan[$kode]
        ?? 'Terjadi kesalahan saat mengunggah file.';
}

function pustaka_pastikan_folder(
    $uploadDir,
    &$errorText
) {
    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;
    }

    return true;
}

function pustaka_nama_file_baru(
    $awalan,
    $ekstensi
) {
    try {
        $acak = bin2hex(
            random_bytes(8)
        );
    } catch (Throwable $e) {
        $acak = str_replace(
            '.',
            '',
            uniqid('', true)
        );
    }

    return $awalan
        .'_'
        .date('YmdHis')
        .'_'
        .$acak
        .'.'
        .$ekstensi;
}

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

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorText = 'Upload cover gagal: '
            .pustaka_pesan_upload($file['error']);

        return false;
    }

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

    $maksimalUkuran = 5 * 1024 * 1024;

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

    $mime = '';

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

    $tipeDiizinkan = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
        'image/gif'  => 'gif'
    ];

    if (
        !isset($tipeDiizinkan[$mime]) ||
        @getimagesize($file['tmp_name']) === false
    ) {
        $errorText = 'Cover harus berupa gambar JPG, PNG, WEBP, atau GIF.';
        return false;
    }

    if (
        !pustaka_pastikan_folder(
            $uploadDir,
            $errorText
        )
    ) {
        return false;
    }

    $namaFile = pustaka_nama_file_baru(
        'cover',
        $tipeDiizinkan[$mime]
    );

    $tujuan = rtrim(
        $uploadDir,
        DIRECTORY_SEPARATOR
    )
    .DIRECTORY_SEPARATOR
    .$namaFile;

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

    return $namaFile;
}

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

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorText = 'Upload PDF gagal: '
            .pustaka_pesan_upload($file['error']);

        return false;
    }

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

    $maksimalUkuran = 20 * 1024 * 1024;

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

    $handle = @fopen(
        $file['tmp_name'],
        'rb'
    );

    $signature = $handle
        ? fread($handle, 4)
        : '';

    if ($handle) {
        fclose($handle);
    }

    if ($signature !== '%PDF') {
        $errorText = 'File yang diunggah bukan dokumen PDF yang valid.';
        return false;
    }

    if (
        !pustaka_pastikan_folder(
            $uploadDir,
            $errorText
        )
    ) {
        return false;
    }

    $namaFile = pustaka_nama_file_baru(
        'pustaka',
        'pdf'
    );

    $tujuan = rtrim(
        $uploadDir,
        DIRECTORY_SEPARATOR
    )
    .DIRECTORY_SEPARATOR
    .$namaFile;

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

    return $namaFile;
}

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

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

    $lokasi = rtrim(
        $uploadDir,
        DIRECTORY_SEPARATOR
    )
    .DIRECTORY_SEPARATOR
    .$namaFile;

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

function pustaka_inisial($judul)
{
    $judul = trim((string)$judul);

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

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

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

function pustaka_ringkasan(
    $deskripsi,
    $panjang = 100
) {
    $text = trim(
        preg_replace(
            '/\s+/',
            ' ',
            strip_tags((string)$deskripsi)
        )
    );

    if ($text === '') {
        return 'Tidak ada deskripsi.';
    }

    if (function_exists('mb_strlen')) {
        if (
            mb_strlen($text, 'UTF-8') <=
            $panjang
        ) {
            return $text;
        }

        return mb_substr(
            $text,
            0,
            $panjang,
            'UTF-8'
        ).'...';
    }

    if (strlen($text) <= $panjang) {
        return $text;
    }

    return substr(
        $text,
        0,
        $panjang
    ).'...';
}


/* =========================================================
   HAPUS DATA
========================================================= */

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

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        header(
            'Location: pustaka.php?msg=csrf'
        );
        exit;
    }

    if ($id <= 0) {
        header(
            'Location: pustaka.php?msg=notfound'
        );
        exit;
    }

    $coverLama = '';
    $pdfLama = '';
    $ditemukan = false;

    $cekStmt = $mysqli->prepare("
        SELECT cover, file_pdf
        FROM pustaka
        WHERE id = ?
        LIMIT 1
    ");

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

        if ($cekStmt->num_rows > 0) {
            $cekStmt->bind_result(
                $coverLama,
                $pdfLama
            );

            $cekStmt->fetch();
            $ditemukan = true;
        }

        $cekStmt->close();
    }

    if (!$ditemukan) {
        header(
            'Location: pustaka.php?msg=notfound'
        );
        exit;
    }

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

    if (!$stmt) {
        header(
            'Location: pustaka.php?msg=error'
        );
        exit;
    }

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

    $berhasil = $stmt->execute();

    $terhapus = $berhasil &&
        $stmt->affected_rows > 0;

    $stmt->close();

    if ($terhapus) {
        pustaka_hapus_file(
            $uploadDir,
            $coverLama
        );

        pustaka_hapus_file(
            $uploadDir,
            $pdfLama
        );
    }

    header(
        'Location: pustaka.php?msg='
        .($terhapus ? 'deleted' : 'error')
    );
    exit;
}


/* =========================================================
   SIMPAN / UPDATE DATA
========================================================= */

$errorText = '';

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

    $judul = trim(
        (string)($_POST['judul'] ?? '')
    );

    $slugInput = trim(
        (string)($_POST['slug'] ?? '')
    );

    $kategori = trim(
        (string)($_POST['kategori'] ?? '')
    );

    $deskripsi = trim(
        (string)($_POST['deskripsi'] ?? '')
    );

    $status = trim(
        (string)($_POST['status'] ?? 'draft')
    );

    $hapusCover = isset($_POST['hapus_cover']) &&
        $_POST['hapus_cover'] === '1';

    $hapusPdf = isset($_POST['hapus_pdf']) &&
        $_POST['hapus_pdf'] === '1';

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
    } elseif ($judul === '') {
        $errorText = 'Judul pustaka wajib diisi.';
        $act = 'form';
    } elseif (
        function_exists('mb_strlen') &&
        mb_strlen($judul, 'UTF-8') > 255
    ) {
        $errorText = 'Judul pustaka maksimal 255 karakter.';
        $act = 'form';
    } elseif (
        !function_exists('mb_strlen') &&
        strlen($judul) > 255
    ) {
        $errorText = 'Judul pustaka maksimal 255 karakter.';
        $act = 'form';
    } elseif (
        !in_array(
            $status,
            ['draft', 'publish'],
            true
        )
    ) {
        $errorText = 'Status pustaka tidak valid.';
        $act = 'form';
    } else {
        $slug = pustaka_slug_unik(
            $mysqli,
            $slugInput !== ''
                ? $slugInput
                : $judul,
            $id
        );

        $coverLama = '';
        $pdfLama = '';
        $dataDitemukan = $id === 0;

        if ($id > 0) {
            $cekStmt = $mysqli->prepare("
                SELECT cover, file_pdf
                FROM pustaka
                WHERE id = ?
                LIMIT 1
            ");

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

                $cekStmt->execute();
                $cekStmt->store_result();

                if ($cekStmt->num_rows > 0) {
                    $cekStmt->bind_result(
                        $coverLama,
                        $pdfLama
                    );

                    $cekStmt->fetch();
                    $dataDitemukan = true;
                }

                $cekStmt->close();
            }
        }

        if (!$dataDitemukan) {
            header(
                'Location: pustaka.php?msg=notfound'
            );
            exit;
        }

        $coverBaru = pustaka_upload_cover(
            $_FILES['cover'] ?? [],
            $uploadDir,
            $errorText
        );

        if ($coverBaru === false) {
            $act = 'form';
        }

        $pdfBaru = null;

        if ($errorText === '') {
            $pdfBaru = pustaka_upload_pdf(
                $_FILES['file_pdf'] ?? [],
                $uploadDir,
                $errorText
            );

            if ($pdfBaru === false) {
                if (
                    is_string($coverBaru) &&
                    $coverBaru !== ''
                ) {
                    pustaka_hapus_file(
                        $uploadDir,
                        $coverBaru
                    );
                }

                $act = 'form';
            }
        }

        if ($errorText === '') {
            $coverFinal = (string)$coverLama;
            $pdfFinal = (string)$pdfLama;

            $hapusCoverSetelahSimpan = '';
            $hapusPdfSetelahSimpan = '';

            if ($hapusCover) {
                $coverFinal = '';

                if ($coverLama !== '') {
                    $hapusCoverSetelahSimpan =
                        $coverLama;
                }
            }

            if ($hapusPdf) {
                $pdfFinal = '';

                if ($pdfLama !== '') {
                    $hapusPdfSetelahSimpan =
                        $pdfLama;
                }
            }

            if (
                is_string($coverBaru) &&
                $coverBaru !== ''
            ) {
                $coverFinal = $coverBaru;

                if ($coverLama !== '') {
                    $hapusCoverSetelahSimpan =
                        $coverLama;
                }
            }

            if (
                is_string($pdfBaru) &&
                $pdfBaru !== ''
            ) {
                $pdfFinal = $pdfBaru;

                if ($pdfLama !== '') {
                    $hapusPdfSetelahSimpan =
                        $pdfLama;
                }
            }

            if ($id > 0) {
                $stmt = $mysqli->prepare("
                    UPDATE pustaka
                    SET
                        judul = ?,
                        slug = ?,
                        kategori = ?,
                        deskripsi = ?,
                        cover = ?,
                        file_pdf = ?,
                        status = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sssssssi',
                        $judul,
                        $slug,
                        $kategori,
                        $deskripsi,
                        $coverFinal,
                        $pdfFinal,
                        $status,
                        $id
                    );

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

                        if (
                            $hapusCoverSetelahSimpan !== '' &&
                            $hapusCoverSetelahSimpan !==
                            $coverFinal
                        ) {
                            pustaka_hapus_file(
                                $uploadDir,
                                $hapusCoverSetelahSimpan
                            );
                        }

                        if (
                            $hapusPdfSetelahSimpan !== '' &&
                            $hapusPdfSetelahSimpan !==
                            $pdfFinal
                        ) {
                            pustaka_hapus_file(
                                $uploadDir,
                                $hapusPdfSetelahSimpan
                            );
                        }

                        header(
                            'Location: pustaka.php?msg=updated'
                        );
                        exit;
                    }

                    $errorText = 'Pustaka gagal diperbarui: '
                        .$stmt->error;

                    $stmt->close();
                } else {
                    $errorText = 'Query pembaruan gagal disiapkan: '
                        .$mysqli->error;
                }
            } else {
                $stmt = $mysqli->prepare("
                    INSERT INTO pustaka
                    (
                        judul,
                        slug,
                        kategori,
                        deskripsi,
                        cover,
                        file_pdf,
                        status
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sssssss',
                        $judul,
                        $slug,
                        $kategori,
                        $deskripsi,
                        $coverFinal,
                        $pdfFinal,
                        $status
                    );

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

                        header(
                            'Location: pustaka.php?msg=saved'
                        );
                        exit;
                    }

                    $errorText = 'Pustaka gagal disimpan: '
                        .$stmt->error;

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

            if (
                is_string($coverBaru) &&
                $coverBaru !== ''
            ) {
                pustaka_hapus_file(
                    $uploadDir,
                    $coverBaru
                );
            }

            if (
                is_string($pdfBaru) &&
                $pdfBaru !== ''
            ) {
                pustaka_hapus_file(
                    $uploadDir,
                    $pdfBaru
                );
            }

            $act = 'form';
        }
    }
}


/* =========================================================
   DATA EDIT
========================================================= */

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT
                id,
                judul,
                slug,
                kategori,
                deskripsi,
                cover,
                file_pdf,
                status
            FROM pustaka
            WHERE id = ?
            LIMIT 1
        ");

        if ($stmt) {
            $stmt->bind_param(
                'i',
                $editId
            );

            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $editResultId = 0;
                $editJudul = '';
                $editSlug = '';
                $editKategori = '';
                $editDeskripsi = '';
                $editCover = '';
                $editPdf = '';
                $editStatus = '';

                $stmt->bind_result(
                    $editResultId,
                    $editJudul,
                    $editSlug,
                    $editKategori,
                    $editDeskripsi,
                    $editCover,
                    $editPdf,
                    $editStatus
                );

                $stmt->fetch();

                $edit = [
                    'id' => $editResultId,
                    'judul' => $editJudul,
                    'slug' => $editSlug,
                    'kategori' => $editKategori,
                    'deskripsi' => $editDeskripsi,
                    'cover' => $editCover,
                    'file_pdf' => $editPdf,
                    'status' => $editStatus
                ];
            }

            $stmt->close();
        }

        if (!$edit && $errorText === '') {
            header(
                'Location: pustaka.php?msg=notfound'
            );
            exit;
        }
    }
}


/* =========================================================
   NORMALISASI HALAMAN
========================================================= */

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


/* =========================================================
   DATA KATEGORI
========================================================= */

$kategoriData = [];

$kategoriResult = $mysqli->query("
    SELECT DISTINCT kategori
    FROM pustaka
    WHERE kategori IS NOT NULL
      AND kategori <> ''
    ORDER BY kategori ASC
");

if ($kategoriResult) {
    while (
        $kategoriRow =
        $kategoriResult->fetch_assoc()
    ) {
        $kategoriData[] =
            $kategoriRow['kategori'];
    }
}


/* =========================================================
   PENCARIAN DAN FILTER
========================================================= */

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

$statusFilter = trim(
    (string)($_GET['status'] ?? '')
);

$kategoriFilter = trim(
    (string)($_GET['kategori'] ?? '')
);

$where = [];

if ($q !== '') {
    $safeQ = $mysqli->real_escape_string($q);

    $where[] = "(
        judul LIKE '%{$safeQ}%'
        OR slug LIKE '%{$safeQ}%'
        OR kategori LIKE '%{$safeQ}%'
        OR deskripsi LIKE '%{$safeQ}%'
    )";
}

if (
    in_array(
        $statusFilter,
        ['draft', 'publish'],
        true
    )
) {
    $safeStatus = $mysqli->real_escape_string(
        $statusFilter
    );

    $where[] = "status = '{$safeStatus}'";
}

if ($kategoriFilter !== '') {
    $safeKategori = $mysqli->real_escape_string(
        $kategoriFilter
    );

    $where[] = "kategori = '{$safeKategori}'";
}

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

$list = $mysqli->query("
    SELECT
        id,
        judul,
        slug,
        kategori,
        deskripsi,
        cover,
        file_pdf,
        status
    FROM pustaka
    {$whereSql}
    ORDER BY id DESC
");

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


/* =========================================================
   NILAI FORM
========================================================= */

$isEdit = !empty($edit);

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

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

$kategoriValue = $_POST['kategori']
    ?? $edit['kategori']
    ?? '';

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

$statusValue = $_POST['status']
    ?? $edit['status']
    ?? 'draft';

$coverValue = $edit['cover']
    ?? '';

$pdfValue = $edit['file_pdf']
    ?? '';


/* =========================================================
   PESAN
========================================================= */

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

$msgText = [
    'saved' =>
        'Pustaka berhasil ditambahkan.',
    'updated' =>
        'Pustaka berhasil diperbarui.',
    'deleted' =>
        'Pustaka berhasil dihapus.',
    'notfound' =>
        'Data pustaka tidak ditemukan.',
    'csrf' =>
        'Token keamanan tidak valid. Silakan ulangi proses.',
    'error' =>
        'Terjadi kesalahan saat memproses data pustaka.'
][$msgKey] ?? '';

$msgError = in_array(
    $msgKey,
    ['notfound', 'csrf', '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 {
    --pst-green-950: #002818;
    --pst-green-900: #003d22;
    --pst-green-800: #005530;
    --pst-green-700: #047a3d;
    --pst-green-600: #09a04f;
    --pst-green-500: #15c46a;
    --pst-green-400: #35e085;
    --pst-green-100: #dcfaee;
    --pst-green-50: #edfff5;

    --pst-blue: #2080e8;
    --pst-purple: #7956d8;
    --pst-yellow: #f5b400;
    --pst-orange: #f26b1d;
    --pst-red: #dc3545;

    --pst-ink: #0f1c16;
    --pst-muted: #5e6e67;
    --pst-line: #daeae1;
    --pst-surface: #ffffff;
    --pst-page: #f3faf6;

    --pst-radius: 16px;
    --pst-shadow:
        0 8px 28px rgba(10, 40, 25, .10);
}

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

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

@keyframes pst-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);
    }
}

@keyframes pst-float {
    0%,
    100% {
        transform: translateY(0);
    }

    50% {
        transform: translateY(-8px);
    }
}

* {
    box-sizing: border-box;
}

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

.pst-page {
    padding: 26px;
}


/* HEADER */

.pst-header {
    position: relative;
    overflow: hidden;

    margin-bottom: 22px;
    padding: 26px 30px;

    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;

    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--pst-green-950),
        var(--pst-green-800),
        var(--pst-green-900)
    );

    background-size: 200% 100%;
    border-radius: var(--pst-radius);

    box-shadow:
        0 14px 40px rgba(0, 60, 30, .28);

    animation:
        pst-gradient 8s ease infinite;
}

.pst-header::before,
.pst-header::after {
    content: "";
    position: absolute;

    border-radius: 50%;
    pointer-events: none;
}

.pst-header::before {
    width: 220px;
    height: 220px;
    top: -80px;
    right: -55px;

    background: radial-gradient(
        circle,
        rgba(53, 224, 133, .20),
        transparent 70%
    );

    animation:
        pst-float 7s ease-in-out infinite;
}

.pst-header::after {
    width: 130px;
    height: 130px;
    bottom: -40px;
    left: 30%;

    background: radial-gradient(
        circle,
        rgba(245, 180, 0, .12),
        transparent 70%
    );

    animation:
        pst-float 5s ease-in-out infinite reverse;
}

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

.pst-eyebrow {
    margin: 0 0 8px;

    display: inline-flex;
    align-items: center;
    gap: 8px;

    color: var(--pst-green-400);

    font-size: 11px;
    font-weight: 800;
    letter-spacing: .1em;
    text-transform: uppercase;
}

.pst-eyebrow::before {
    content: "";

    width: 22px;
    height: 2px;

    background: linear-gradient(
        90deg,
        var(--pst-green-400),
        var(--pst-green-500)
    );

    border-radius: 2px;
}

.pst-header h2 {
    margin: 0;

    color: #ffffff;

    font-size: clamp(20px, 3vw, 27px);
    font-weight: 800;
    letter-spacing: -.03em;
    line-height: 1.2;
}

.pst-title-icon {
    margin-right: 8px;

    color: var(--pst-green-400);
    font-size: 27px;
    vertical-align: middle;

    filter:
        drop-shadow(
            0 0 8px rgba(53, 224, 133, .5)
        );
}

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

.pst-live-dot {
    width: 8px;
    height: 8px;
    flex-shrink: 0;

    background: var(--pst-green-400);
    border-radius: 50%;

    animation:
        pst-pulse 2s ease infinite;
}

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

.pst-clock {
    padding: 10px 15px;

    display: inline-flex;
    align-items: center;
    gap: 8px;

    color: #ffffff;
    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);
}

.pst-clock i {
    color: var(--pst-green-400);
    font-size: 18px;
}


/* PANEL */

.pst-panel {
    overflow: hidden;

    background: var(--pst-surface);

    border:
        1px solid rgba(210, 232, 220, .85);

    border-radius: var(--pst-radius);
    box-shadow: var(--pst-shadow);
}

.pst-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%
        ),
        #ffffff;

    border-bottom:
        1px solid var(--pst-line);
}

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

.pst-panel-icon {
    width: 42px;
    height: 42px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--pst-green-500),
        var(--pst-green-800)
    );

    border-radius: 13px;

    box-shadow:
        0 4px 12px rgba(9, 160, 79, .28);

    font-size: 20px;
}

.pst-panel-title h3 {
    margin: 0;

    color: var(--pst-ink);

    font-size: 16px;
    font-weight: 800;
}

.pst-panel-title p {
    margin: 3px 0 0;

    color: var(--pst-muted);

    font-size: 12px;
    font-weight: 600;
}

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


/* ALERT */

.pst-alert {
    margin-bottom: 16px;
    padding: 13px 15px;

    display: flex;
    align-items: center;
    gap: 9px;

    color: var(--pst-green-800);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 14px;
    box-shadow: var(--pst-shadow);

    font-size: 14px;
    font-weight: 800;
}

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


/* BUTTON */

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

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

.pst-btn-primary {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--pst-green-500),
        var(--pst-green-800)
    );
}

.pst-btn-light {
    color: #ffffff;
    background: rgba(255, 255, 255, .12);

    border:
        1px solid rgba(255, 255, 255, .18);

    backdrop-filter: blur(8px);
}

.pst-btn-pdf {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        #9c7be8,
        var(--pst-purple)
    );
}

.pst-btn-view {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        #60b4ff,
        var(--pst-blue)
    );
}

.pst-btn-edit {
    color: var(--pst-ink);

    background: linear-gradient(
        135deg,
        #ffd95c,
        var(--pst-yellow)
    );
}

.pst-btn-delete {
    color: #ffffff;

    background: linear-gradient(
        135deg,
        #ff9a52,
        var(--pst-orange)
    );
}

.pst-btn-ghost {
    color: var(--pst-green-800);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);
}

.pst-btn-small {
    padding: 8px 11px;

    border-radius: 10px;
    box-shadow: none;

    font-size: 12px;
}


/* TOOLBAR */

.pst-toolbar {
    margin-bottom: 16px;

    display: grid;
    grid-template-columns:
        minmax(220px, 1fr)
        170px
        190px
        auto;
    gap: 10px;
}

.pst-search {
    position: relative;
}

.pst-search i {
    position: absolute;
    top: 50%;
    left: 14px;

    color: var(--pst-green-700);
    font-size: 18px;

    transform: translateY(-50%);
}

.pst-search input,
.pst-filter {
    width: 100%;
    min-height: 44px;

    color: var(--pst-ink);
    background: #f8fffb;

    border:
        1px solid var(--pst-line);

    border-radius: 14px;
    outline: none;

    font-family: inherit;
    font-size: 13px;
    font-weight: 700;
}

.pst-search input {
    padding: 12px 14px 12px 42px;
}

.pst-filter {
    padding: 10px 13px;
}

.pst-search input:focus,
.pst-filter:focus {
    background: #ffffff;
    border-color: var(--pst-green-500);

    box-shadow:
        0 0 0 4px rgba(21, 196, 106, .13);
}

.pst-stat {
    padding: 10px 14px;

    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;

    color: var(--pst-green-800);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 999px;

    font-size: 13px;
    font-weight: 800;
    white-space: nowrap;
}


/* TABLE */

.pst-table-wrap {
    overflow-x: auto;

    background: #ffffff;

    border:
        1px solid var(--pst-line);

    border-radius: 16px;
}

.pst-table {
    width: 100%;

    border-collapse: separate;
    border-spacing: 0;

    font-size: 14px;
}

.pst-table th {
    padding: 14px 13px;

    color: var(--pst-green-900);

    background: linear-gradient(
        180deg,
        var(--pst-green-50),
        #f8fffb
    );

    border-bottom:
        1px solid var(--pst-line);

    font-size: 12px;
    font-weight: 800;
    letter-spacing: .04em;
    text-align: left;
    text-transform: uppercase;
    white-space: nowrap;
}

.pst-table td {
    padding: 14px 13px;

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

.pst-table tbody tr {
    transition: background .16s ease;
}

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

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

.pst-number {
    width: 36px;
    height: 36px;

    display: inline-grid;
    place-items: center;

    color: var(--pst-green-800);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 11px;

    font-size: 12px;
    font-weight: 800;
}

.pst-title-wrap {
    min-width: 260px;

    display: flex;
    align-items: flex-start;
    gap: 11px;
}

.pst-avatar {
    width: 42px;
    height: 42px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #ffffff;

    background: linear-gradient(
        135deg,
        var(--pst-green-500),
        var(--pst-green-800)
    );

    border-radius: 14px;

    box-shadow:
        0 8px 16px rgba(9, 160, 79, .20);

    font-weight: 800;
}

.pst-title {
    color: var(--pst-ink);

    font-weight: 800;
    line-height: 1.45;
}

.pst-description-small {
    max-width: 360px;
    margin-top: 4px;

    color: var(--pst-muted);

    font-size: 11px;
    line-height: 1.5;
}

.pst-slug {
    margin-top: 3px;

    color: var(--pst-green-700);

    font-size: 10px;
    font-weight: 700;
}

.pst-category {
    padding: 7px 10px;

    display: inline-flex;
    align-items: center;
    gap: 6px;

    color: var(--pst-purple);
    background: #f5f1ff;

    border-radius: 999px;

    font-size: 12px;
    font-weight: 800;
    white-space: nowrap;
}

.pst-status {
    padding: 7px 10px;

    display: inline-flex;
    align-items: center;
    gap: 6px;

    border-radius: 999px;

    font-size: 12px;
    font-weight: 800;
    white-space: nowrap;
}

.pst-status-publish {
    color: #08743b;
    background: #dcfaee;

    border:
        1px solid #b9f0d6;
}

.pst-status-draft {
    color: #a35d00;
    background: #fff5d8;

    border:
        1px solid #ffe5a0;
}

.pst-cover {
    width: 90px;
    height: 110px;

    display: block;

    object-fit: cover;

    background: #eef8f2;

    border:
        1px solid var(--pst-line);

    border-radius: 13px;

    box-shadow:
        0 7px 18px rgba(0, 0, 0, .12);

    cursor: pointer;

    transition:
        transform .2s ease,
        box-shadow .2s ease;
}

.pst-cover:hover {
    transform: scale(1.04);

    box-shadow:
        0 12px 25px rgba(0, 0, 0, .18);
}

.pst-cover-empty {
    width: 90px;
    height: 110px;

    display: grid;
    place-items: center;

    color: var(--pst-green-700);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 13px;

    font-size: 28px;
}

.pst-file-empty {
    color: var(--pst-muted);

    font-size: 12px;
    font-weight: 600;
}

.pst-actions {
    min-width: 190px;

    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 7px;
}

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

.pst-empty {
    padding: 38px !important;

    color: var(--pst-muted);
    background: #fbfffd;

    font-weight: 600;
    text-align: center;
}

.pst-empty i {
    display: block;
    margin-bottom: 8px;

    color: var(--pst-green-600);
    font-size: 36px;
}


/* FORM */

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

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

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

.pst-field label {
    color: var(--pst-ink);

    font-size: 13px;
    font-weight: 800;
}

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

.pst-input {
    width: 100%;
    min-height: 44px;
    padding: 12px 13px;

    color: var(--pst-ink);
    background: #f8fffb;

    border:
        1px solid var(--pst-line);

    border-radius: 13px;
    outline: none;

    font-family: inherit;
    font-size: 14px;
    font-weight: 600;

    transition:
        border-color .2s ease,
        background .2s ease,
        box-shadow .2s ease;
}

.pst-input:focus {
    background: #ffffff;
    border-color: var(--pst-green-500);

    box-shadow:
        0 0 0 4px rgba(21, 196, 106, .13);
}

textarea.pst-input {
    min-height: 160px;

    resize: vertical;
    line-height: 1.7;
}

.pst-section {
    grid-column: 1 / -1;

    padding: 12px 14px;

    display: flex;
    align-items: center;
    gap: 9px;

    color: var(--pst-green-900);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 13px;

    font-size: 13px;
    font-weight: 800;
}

.pst-section i {
    color: var(--pst-green-600);
    font-size: 18px;
}

.pst-upload-box {
    height: 100%;
    padding: 16px;

    background: #f8fffb;

    border:
        1px dashed var(--pst-green-500);

    border-radius: 14px;
}

.pst-help {
    margin: 5px 0 0;

    color: var(--pst-muted);

    font-size: 11px;
    font-weight: 600;
    line-height: 1.5;
}

.pst-cover-preview {
    width: 150px;
    height: 190px;

    display: block;
    margin-top: 13px;

    object-fit: cover;

    background: #ffffff;

    border:
        1px solid var(--pst-line);

    border-radius: 14px;

    box-shadow:
        0 8px 20px rgba(0, 0, 0, .12);
}

.pst-cover-placeholder {
    width: 150px;
    height: 190px;

    margin-top: 13px;

    display: grid;
    place-items: center;

    color: var(--pst-green-700);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 14px;

    font-size: 40px;
}

.pst-current-file {
    margin-top: 13px;
    padding: 12px;

    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 10px;

    background: #ffffff;

    border:
        1px solid var(--pst-line);

    border-radius: 13px;
}

.pst-current-file-info {
    min-width: 0;

    display: flex;
    align-items: center;
    gap: 10px;
}

.pst-current-file-icon {
    width: 40px;
    height: 40px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #ffffff;

    background: linear-gradient(
        135deg,
        #9c7be8,
        var(--pst-purple)
    );

    border-radius: 12px;

    font-size: 20px;
}

.pst-current-file-name {
    max-width: 260px;

    overflow: hidden;

    color: var(--pst-ink);

    font-size: 12px;
    font-weight: 800;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.pst-checkbox {
    margin-top: 10px;

    display: inline-flex;
    align-items: center;
    gap: 8px;

    color: var(--pst-red);

    font-size: 12px;
    font-weight: 800;
}

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

.pst-note {
    grid-column: 1 / -1;

    padding: 12px 14px;

    display: flex;
    align-items: flex-start;
    gap: 9px;

    color: var(--pst-green-900);
    background: var(--pst-green-50);

    border:
        1px solid var(--pst-green-100);

    border-radius: 13px;

    font-size: 12px;
    font-weight: 600;
    line-height: 1.6;
}

.pst-note i {
    margin-top: 1px;

    color: var(--pst-green-600);
    font-size: 18px;
}

.pst-form-actions {
    grid-column: 1 / -1;

    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}


/* MODAL COVER */

.pst-modal {
    position: fixed;
    z-index: 99999;
    inset: 0;

    padding: 24px;

    display: none;
    align-items: center;
    justify-content: center;

    background: rgba(0, 20, 12, .84);

    backdrop-filter: blur(8px);
}

.pst-modal.active {
    display: flex;
}

.pst-modal-content {
    position: relative;

    width: min(100%, 720px);
    max-height: 90vh;

    padding: 14px;

    background: #ffffff;

    border-radius: 18px;

    box-shadow:
        0 25px 70px rgba(0, 0, 0, .42);
}

.pst-modal-content img {
    width: 100%;
    max-height: calc(90vh - 28px);

    display: block;

    object-fit: contain;

    border-radius: 12px;
}

.pst-modal-close {
    position: absolute;
    top: -13px;
    right: -13px;

    width: 40px;
    height: 40px;

    display: grid;
    place-items: center;

    color: #ffffff;
    background: var(--pst-orange);

    border: 3px solid #ffffff;
    border-radius: 50%;

    cursor: pointer;

    font-size: 21px;
}


/* RESPONSIVE */

@media (max-width: 980px) {
    .pst-toolbar {
        grid-template-columns:
            1fr
            170px
            180px;
    }

    .pst-stat {
        grid-column: 1 / -1;
    }
}

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

    .pst-header {
        padding: 20px;
    }

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

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

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

    .pst-stat {
        grid-column: 1;
    }

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

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

    .pst-actions {
        min-width: 210px;
    }
}
</style>


<div class="pst-page">

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

        <div class="pst-header">
            <div class="pst-header-left">
                <p class="pst-eyebrow">
                    <i class="ri-book-3-fill"></i>
                    Dokumen Desa
                </p>

                <h2>
                    <i class="ri-book-open-fill pst-title-icon"></i>
                    Pustaka Desa
                </h2>

                <p class="pst-description">
                    <span class="pst-live-dot"></span>

                    Kelola buku, dokumen, dan arsip digital desa
                </p>
            </div>

            <div class="pst-header-actions">
                <span class="pst-clock">
                    <i class="ri-time-fill"></i>

                    <span id="pstLiveClock">
                        --.--.--
                    </span>

                    <span style="color:rgba(255,255,255,.55)">
                        WITA
                    </span>
                </span>

                <a
                    class="pst-btn pst-btn-light"
                    href="pustaka.php?a=form"
                >
                    <i class="ri-add-circle-fill"></i>
                    Tambah Pustaka
                </a>
            </div>
        </div>


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

                <?= esc($msgText) ?>
            </div>
        <?php endif; ?>


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

                    <div>
                        <h3>Daftar Pustaka Desa</h3>

                        <p>
                            Dokumen digital berstatus draft maupun publish.
                        </p>
                    </div>
                </div>

                <div class="pst-stat">
                    <i class="ri-book-shelf-fill"></i>
                    <?= (int)$totalPustaka ?> Pustaka
                </div>
            </div>

            <div class="pst-panel-body">
                <form
                    method="get"
                    action="pustaka.php"
                    class="pst-toolbar"
                    id="filterPustaka"
                >
                    <div class="pst-search">
                        <i class="ri-search-line"></i>

                        <input
                            type="text"
                            name="q"
                            value="<?= esc($q) ?>"
                            placeholder="Cari judul, kategori, slug, atau deskripsi..."
                            autocomplete="off"
                        >
                    </div>

                    <select
                        name="status"
                        class="pst-filter"
                        onchange="this.form.submit()"
                    >
                        <option value="">
                            Semua Status
                        </option>

                        <option
                            value="publish"
                            <?= $statusFilter === 'publish'
                                ? 'selected'
                                : '' ?>
                        >
                            Publish
                        </option>

                        <option
                            value="draft"
                            <?= $statusFilter === 'draft'
                                ? 'selected'
                                : '' ?>
                        >
                            Draft
                        </option>
                    </select>

                    <select
                        name="kategori"
                        class="pst-filter"
                        onchange="this.form.submit()"
                    >
                        <option value="">
                            Semua Kategori
                        </option>

                        <?php foreach ($kategoriData as $kategoriItem): ?>
                            <option
                                value="<?= esc($kategoriItem) ?>"
                                <?= $kategoriFilter === $kategoriItem
                                    ? 'selected'
                                    : '' ?>
                            >
                                <?= esc($kategoriItem) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <?php if (
                        $q !== '' ||
                        $statusFilter !== '' ||
                        $kategoriFilter !== ''
                    ): ?>
                        <a
                            href="pustaka.php"
                            class="pst-btn pst-btn-ghost"
                        >
                            <i class="ri-refresh-line"></i>
                            Reset
                        </a>
                    <?php endif; ?>
                </form>

                <div class="pst-table-wrap">
                    <table class="pst-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Judul</th>
                                <th>Kategori</th>
                                <th>Status</th>
                                <th>Cover</th>
                                <th>Dokumen</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalPustaka === 0): ?>
                                <tr>
                                    <td
                                        colspan="7"
                                        class="pst-empty"
                                    >
                                        <i class="ri-book-open-line"></i>

                                        <?= (
                                            $q !== '' ||
                                            $statusFilter !== '' ||
                                            $kategoriFilter !== ''
                                        )
                                            ? 'Pustaka yang dicari tidak ditemukan.'
                                            : 'Belum ada pustaka. Klik tombol Tambah Pustaka untuk menambahkan dokumen baru.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                <?php while ($row = $list->fetch_assoc()): ?>
                                    <?php
                                    $coverName = basename(
                                        trim(
                                            (string)(
                                                $row['cover']
                                                ?? ''
                                            )
                                        )
                                    );

                                    $pdfName = basename(
                                        trim(
                                            (string)(
                                                $row['file_pdf']
                                                ?? ''
                                            )
                                        )
                                    );

                                    $coverPath = $coverName !== ''
                                        ? $uploadUrl.'/'.$coverName
                                        : '';

                                    $pdfPath = $pdfName !== ''
                                        ? $uploadUrl.'/'.$pdfName
                                        : '';
                                    ?>

                                    <tr class="pst-data-row">
                                        <td>
                                            <span class="pst-number">
                                                <?= $no++ ?>
                                            </span>
                                        </td>

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

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

                                                    <div class="pst-description-small">
                                                        <?= esc(
                                                            pustaka_ringkasan(
                                                                $row['deskripsi']
                                                            )
                                                        ) ?>
                                                    </div>

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

                                        <td>
                                            <span class="pst-category">
                                                <i class="ri-price-tag-3-fill"></i>

                                                <?= esc(
                                                    $row['kategori']
                                                        ?: 'Tanpa Kategori'
                                                ) ?>
                                            </span>
                                        </td>

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

                                        <td>
                                            <?php if ($coverPath !== ''): ?>
                                                <img
                                                    src="<?= esc($coverPath) ?>"
                                                    alt="<?= esc(
                                                        $row['judul']
                                                    ) ?>"
                                                    class="pst-cover pst-open-cover"
                                                    data-src="<?= esc(
                                                        $coverPath
                                                    ) ?>"
                                                    data-title="<?= esc(
                                                        $row['judul']
                                                    ) ?>"
                                                    loading="lazy"
                                                >
                                            <?php else: ?>
                                                <div class="pst-cover-empty">
                                                    <i class="ri-book-2-line"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <?php if ($pdfPath !== ''): ?>
                                                <a
                                                    class="pst-btn pst-btn-small pst-btn-pdf"
                                                    href="<?= esc($pdfPath) ?>"
                                                    target="_blank"
                                                    rel="noopener"
                                                >
                                                    <i class="ri-file-pdf-2-fill"></i>
                                                    Buka PDF
                                                </a>
                                            <?php else: ?>
                                                <span class="pst-file-empty">
                                                    Tidak ada PDF
                                                </span>
                                            <?php endif; ?>
                                        </td>

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

                                                <form
                                                    method="post"
                                                    action="pustaka.php?a=delete"
                                                    class="pst-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus pustaka ini? Cover dan file PDF juga akan dihapus dan tidak dapat dikembalikan.');"
                                                >
                                                    <input
                                                        type="hidden"
                                                        name="csrf_token"
                                                        value="<?= esc(
                                                            $csrfToken
                                                        ) ?>"
                                                    >

                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$row['id'] ?>"
                                                    >

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


    <?php else: ?>

        <div class="pst-header">
            <div class="pst-header-left">
                <p class="pst-eyebrow">
                    <i class="<?= $isEdit
                        ? 'ri-edit-2-fill'
                        : 'ri-file-add-fill' ?>"></i>

                    <?= $isEdit
                        ? 'Edit Dokumen Digital'
                        : 'Tambah Dokumen Digital' ?>
                </p>

                <h2>
                    <i class="ri-book-open-fill pst-title-icon"></i>

                    <?= $isEdit
                        ? 'Edit Pustaka Desa'
                        : 'Tambah Pustaka Desa' ?>
                </h2>

                <p class="pst-description">
                    <span class="pst-live-dot"></span>

                    <?= $isEdit
                        ? 'Perbarui informasi, cover, dan file PDF pustaka.'
                        : 'Tambahkan buku, dokumen, atau arsip digital desa.' ?>
                </p>
            </div>

            <div class="pst-header-actions">
                <a
                    class="pst-btn pst-btn-light"
                    href="pustaka.php"
                >
                    <i class="ri-arrow-left-line"></i>
                    Kembali
                </a>
            </div>
        </div>


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


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

                    <div>
                        <h3>
                            <?= $isEdit
                                ? 'Edit Data Pustaka'
                                : 'Form Tambah Pustaka' ?>
                        </h3>

                        <p>
                            Cover maksimal 5 MB dan file PDF maksimal 20 MB.
                        </p>
                    </div>
                </div>
            </div>

            <div class="pst-panel-body">
                <form
                    method="post"
                    action="pustaka.php?a=save"
                    enctype="multipart/form-data"
                    class="pst-form"
                    id="pustakaForm"
                >
                    <input
                        type="hidden"
                        name="csrf_token"
                        value="<?= esc($csrfToken) ?>"
                    >

                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)($edit['id'] ?? 0) ?>"
                    >


                    <div class="pst-section">
                        <i class="ri-file-text-fill"></i>
                        Informasi Pustaka
                    </div>

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

                        <input
                            type="text"
                            class="pst-input"
                            id="judul"
                            name="judul"
                            value="<?= esc($judulValue) ?>"
                            placeholder="Masukkan judul buku atau dokumen"
                            maxlength="255"
                            required
                        >
                    </div>

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

                        <input
                            type="text"
                            class="pst-input"
                            id="slug"
                            name="slug"
                            value="<?= esc($slugValue) ?>"
                            placeholder="Otomatis dari judul"
                            maxlength="255"
                        >

                        <p class="pst-help">
                            Slug akan dibuat otomatis dan dipastikan tidak sama dengan pustaka lain.
                        </p>
                    </div>

                    <div class="pst-field">
                        <label for="kategori">
                            Kategori
                        </label>

                        <input
                            type="text"
                            class="pst-input"
                            id="kategori"
                            name="kategori"
                            value="<?= esc($kategoriValue) ?>"
                            placeholder="Contoh: Peraturan Desa"
                            maxlength="150"
                            list="daftarKategori"
                        >

                        <datalist id="daftarKategori">
                            <?php foreach ($kategoriData as $kategoriItem): ?>
                                <option
                                    value="<?= esc($kategoriItem) ?>"
                                >
                            <?php endforeach; ?>
                        </datalist>
                    </div>

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

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

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

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

                        <textarea
                            class="pst-input"
                            id="deskripsi"
                            name="deskripsi"
                            rows="7"
                            placeholder="Masukkan deskripsi singkat dokumen atau buku..."
                        ><?= esc($deskripsiValue) ?></textarea>
                    </div>


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

                    <div class="pst-field">
                        <div class="pst-upload-box">
                            <label for="cover">
                                Cover
                            </label>

                            <input
                                type="file"
                                class="pst-input"
                                id="cover"
                                name="cover"
                                accept=".jpg,.jpeg,.png,.webp,.gif,image/jpeg,image/png,image/webp,image/gif"
                            >

                            <p class="pst-help">
                                Format JPG, PNG, WEBP, atau GIF. Ukuran maksimal 5 MB.
                                <?= $isEdit
                                    ? 'Kosongkan jika tidak ingin mengganti cover.'
                                    : '' ?>
                            </p>

                            <?php if ($coverValue !== ''): ?>
                                <img
                                    id="coverPreview"
                                    class="pst-cover-preview"
                                    src="<?= esc(
                                        $uploadUrl
                                        .'/'
                                        .basename($coverValue)
                                    ) ?>"
                                    alt="Preview cover"
                                >

                                <div
                                    id="coverPlaceholder"
                                    class="pst-cover-placeholder"
                                    style="display:none"
                                >
                                    <i class="ri-book-2-line"></i>
                                </div>

                                <label class="pst-checkbox">
                                    <input
                                        type="checkbox"
                                        name="hapus_cover"
                                        value="1"
                                        id="hapusCover"
                                    >

                                    Hapus cover lama
                                </label>
                            <?php else: ?>
                                <div
                                    id="coverPlaceholder"
                                    class="pst-cover-placeholder"
                                >
                                    <i class="ri-book-2-line"></i>
                                </div>

                                <img
                                    id="coverPreview"
                                    class="pst-cover-preview"
                                    alt="Preview cover"
                                    style="display:none"
                                >
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="pst-field">
                        <div class="pst-upload-box">
                            <label for="filePdf">
                                File PDF
                            </label>

                            <input
                                type="file"
                                class="pst-input"
                                id="filePdf"
                                name="file_pdf"
                                accept=".pdf,application/pdf"
                            >

                            <p class="pst-help">
                                File harus berupa PDF dengan ukuran maksimal 20 MB.
                                <?= $isEdit
                                    ? 'Kosongkan jika tidak ingin mengganti file lama.'
                                    : '' ?>
                            </p>

                            <div
                                id="pdfSelected"
                                class="pst-current-file"
                                style="display:none"
                            >
                                <div class="pst-current-file-info">
                                    <div class="pst-current-file-icon">
                                        <i class="ri-file-pdf-2-fill"></i>
                                    </div>

                                    <div
                                        class="pst-current-file-name"
                                        id="pdfSelectedName"
                                    ></div>
                                </div>
                            </div>

                            <?php if ($pdfValue !== ''): ?>
                                <div class="pst-current-file">
                                    <div class="pst-current-file-info">
                                        <div class="pst-current-file-icon">
                                            <i class="ri-file-pdf-2-fill"></i>
                                        </div>

                                        <div class="pst-current-file-name">
                                            <?= esc(
                                                basename($pdfValue)
                                            ) ?>
                                        </div>
                                    </div>

                                    <a
                                        class="pst-btn pst-btn-small pst-btn-pdf"
                                        href="<?= esc(
                                            $uploadUrl
                                            .'/'
                                            .basename($pdfValue)
                                        ) ?>"
                                        target="_blank"
                                        rel="noopener"
                                    >
                                        <i class="ri-eye-fill"></i>
                                        Buka
                                    </a>
                                </div>

                                <label class="pst-checkbox">
                                    <input
                                        type="checkbox"
                                        name="hapus_pdf"
                                        value="1"
                                        id="hapusPdf"
                                    >

                                    Hapus file PDF lama
                                </label>
                            <?php endif; ?>
                        </div>
                    </div>


                    <div class="pst-note">
                        <i class="ri-information-fill"></i>

                        <span>
                            Ketika cover atau PDF baru diunggah saat edit,
                            file lama akan dihapus setelah pembaruan berhasil.
                            Menghapus data pustaka juga akan menghapus cover
                            dan file PDF dari server.
                        </span>
                    </div>

                    <div class="pst-form-actions">
                        <button
                            type="submit"
                            class="pst-btn pst-btn-primary"
                        >
                            <i class="ri-save-3-fill"></i>

                            <?= $isEdit
                                ? 'Perbarui Pustaka'
                                : 'Simpan Pustaka' ?>
                        </button>

                        <a
                            class="pst-btn pst-btn-ghost"
                            href="pustaka.php"
                        >
                            <i class="ri-close-circle-fill"></i>
                            Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>

    <?php endif; ?>

</div>


<div
    class="pst-modal"
    id="coverModal"
>
    <div class="pst-modal-content">
        <button
            type="button"
            class="pst-modal-close"
            id="closeCoverModal"
            aria-label="Tutup"
        >
            <i class="ri-close-line"></i>
        </button>

        <img
            id="coverModalImage"
            src=""
            alt=""
        >
    </div>
</div>


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

    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 searchInput = document.querySelector(
        '.pst-search input'
    );

    let searchTimer = null;

    if (searchInput) {
        searchInput.addEventListener('input', function () {
            clearTimeout(searchTimer);

            searchTimer = setTimeout(() => {
                this.form.submit();
            }, 650);
        });
    }


    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 slugManual =
            slugInput.value.trim() !== '';

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

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


    const coverInput = document.getElementById(
        'cover'
    );

    const coverPreview = document.getElementById(
        'coverPreview'
    );

    const coverPlaceholder = document.getElementById(
        'coverPlaceholder'
    );

    const hapusCover = document.getElementById(
        'hapusCover'
    );

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

                if (!file) {
                    return;
                }

                const allowedTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/webp',
                    'image/gif'
                ];

                if (!allowedTypes.includes(file.type)) {
                    alert(
                        'Cover harus berupa JPG, PNG, WEBP, atau GIF.'
                    );

                    this.value = '';
                    return;
                }

                if (file.size > 5 * 1024 * 1024) {
                    alert(
                        'Ukuran cover maksimal 5 MB.'
                    );

                    this.value = '';
                    return;
                }

                const reader = new FileReader();

                reader.onload = function (event) {
                    coverPreview.src =
                        event.target.result;

                    coverPreview.style.display =
                        'block';

                    if (coverPlaceholder) {
                        coverPlaceholder.style.display =
                            'none';
                    }

                    if (hapusCover) {
                        hapusCover.checked = false;
                        coverPreview.style.opacity = '1';
                    }
                };

                reader.readAsDataURL(file);
            }
        );
    }

    if (hapusCover && coverPreview) {
        hapusCover.addEventListener(
            'change',
            function () {
                coverPreview.style.opacity =
                    this.checked ? '.3' : '1';
            }
        );
    }


    const pdfInput = document.getElementById(
        'filePdf'
    );

    const pdfSelected = document.getElementById(
        'pdfSelected'
    );

    const pdfSelectedName = document.getElementById(
        'pdfSelectedName'
    );

    const hapusPdf = document.getElementById(
        'hapusPdf'
    );

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

                if (!file) {
                    if (pdfSelected) {
                        pdfSelected.style.display =
                            'none';
                    }

                    return;
                }

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

                if (
                    file.type !== 'application/pdf' &&
                    extension !== 'pdf'
                ) {
                    alert(
                        'File yang dipilih harus berupa PDF.'
                    );

                    this.value = '';
                    return;
                }

                if (file.size > 20 * 1024 * 1024) {
                    alert(
                        'Ukuran file PDF maksimal 20 MB.'
                    );

                    this.value = '';
                    return;
                }

                if (
                    pdfSelected &&
                    pdfSelectedName
                ) {
                    pdfSelectedName.textContent =
                        file.name;

                    pdfSelected.style.display =
                        'flex';
                }

                if (hapusPdf) {
                    hapusPdf.checked = false;
                }
            }
        );
    }


    const modal = document.getElementById(
        'coverModal'
    );

    const modalImage = document.getElementById(
        'coverModalImage'
    );

    const closeModal = document.getElementById(
        'closeCoverModal'
    );

    const tutupModal = () => {
        if (!modal) {
            return;
        }

        modal.classList.remove('active');

        if (modalImage) {
            modalImage.src = '';
        }

        document.body.style.overflow = '';
    };

    document
        .querySelectorAll('.pst-open-cover')
        .forEach((image) => {
            image.addEventListener(
                'click',
                function () {
                    if (!modal || !modalImage) {
                        return;
                    }

                    modalImage.src =
                        this.dataset.src || '';

                    modalImage.alt =
                        this.dataset.title || 'Cover pustaka';

                    modal.classList.add('active');

                    document.body.style.overflow =
                        'hidden';
                }
            );
        });

    if (closeModal) {
        closeModal.addEventListener(
            'click',
            tutupModal
        );
    }

    if (modal) {
        modal.addEventListener(
            'click',
            function (event) {
                if (event.target === modal) {
                    tutupModal();
                }
            }
        );
    }

    document.addEventListener(
        'keydown',
        function (event) {
            if (event.key === 'Escape') {
                tutupModal();
            }
        }
    );
})();
</script>

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