<?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();
}

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

if ($act === 'edit') {
    $act = 'form';
}


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

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

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

$csrfToken = $_SESSION['csrf_berita'];


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

function berita_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($text, '-');
}

function berita_slug_unik($mysqli, $slug, $excludeId = 0)
{
    $slugDasar = berita_slugify($slug);

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

    $slugFinal = $slugDasar;
    $nomor = 2;

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

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

        $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 berita_tanggal_valid($tanggal)
{
    if ($tanggal === '') {
        return false;
    }

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

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

function berita_tanggal_indo($tanggal)
{
    if (!$tanggal) {
        return '-';
    }

    $waktu = strtotime($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 berita_inisial($judul)
{
    $judul = trim((string)$judul);

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

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

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

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

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

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

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

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

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

        return false;
    }

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

    $maksimalUkuran = 5 * 1024 * 1024;

    if ((int)$file['size'] > $maksimalUkuran) {
        $errorText = 'Ukuran gambar maksimal 5 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 = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
        'image/gif'  => 'gif'
    ];

    if (!isset($allowedMime[$mimeType])) {
        $errorText = 'Format gambar harus JPG, PNG, WEBP, atau GIF.';
        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 = 'berita_'
        .date('YmdHis')
        .'_'
        .$randomName
        .'.'
        .$allowedMime[$mimeType];

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

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

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

    return $namaFileBaru;
}


/* =========================================================
   HAPUS BERITA
========================================================= */

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: berita.php?msg=csrf'
        );
        exit;
    }

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

    $gambarLama = '';

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

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

        $cekResult = $cekStmt->get_result();

        if (
            $cekResult &&
            $dataLama = $cekResult->fetch_assoc()
        ) {
            $gambarLama = trim(
                $dataLama['image'] ?? ''
            );
        }

        $cekStmt->close();
    }

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

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

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

    $berhasil = $stmt->execute();
    $terhapus = $berhasil &&
        $stmt->affected_rows > 0;

    $stmt->close();

    if ($terhapus && $gambarLama !== '') {
        berita_hapus_gambar(
            $uploadDir,
            $gambarLama
        );
    }

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


/* =========================================================
   SIMPAN / UPDATE BERITA
========================================================= */

$errorText = '';

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

    $token = $_POST['csrf_token'] ?? '';

    $title = trim(
        $_POST['title'] ?? ''
    );

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

    $publishedAt = trim(
        $_POST['published_at'] ?? ''
    );

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

    $content = trim(
        $_POST['content'] ?? ''
    );

    $hapusGambar = isset(
        $_POST['hapus_gambar']
    );

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
    } elseif (
        $title === '' ||
        $publishedAt === '' ||
        $content === ''
    ) {
        $errorText = 'Judul, tanggal, dan isi berita wajib diisi.';
        $act = 'form';
    } elseif (
        !berita_tanggal_valid($publishedAt)
    ) {
        $errorText = 'Format tanggal publikasi tidak valid.';
        $act = 'form';
    } elseif (
        !in_array(
            $status,
            ['draft', 'publish'],
            true
        )
    ) {
        $errorText = 'Status berita tidak valid.';
        $act = 'form';
    } else {
        $slugDasar = $slugInput !== ''
            ? $slugInput
            : $title;

        $slug = berita_slug_unik(
            $mysqli,
            $slugDasar,
            $id
        );

        $gambarLama = '';
        $dataDitemukan = $id === 0;

        if ($id > 0) {
            $cekStmt = $mysqli->prepare("
                SELECT image
                FROM berita
                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;

                    $gambarLama = trim(
                        $dataLama['image'] ?? ''
                    );
                }

                $cekStmt->close();
            }
        }

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

        $namaGambar = $gambarLama;
        $gambarBaru = '';
        $gambarUntukDihapus = '';

        if ($hapusGambar) {
            $namaGambar = '';

            if ($gambarLama !== '') {
                $gambarUntukDihapus = $gambarLama;
            }
        }

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

            if ($hasilUpload === false) {
                $act = 'form';
            } else {
                $gambarBaru = $hasilUpload;
                $namaGambar = $gambarBaru;

                if ($gambarLama !== '') {
                    $gambarUntukDihapus = $gambarLama;
                }
            }
        }

        if ($errorText === '') {
            if ($id > 0) {

                /* =========================
                   UPDATE
                ========================= */

                $stmt = $mysqli->prepare("
                    UPDATE berita
                    SET
                        title = ?,
                        slug = ?,
                        published_at = ?,
                        status = ?,
                        image = ?,
                        content = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'ssssssi',
                        $title,
                        $slug,
                        $publishedAt,
                        $status,
                        $namaGambar,
                        $content,
                        $id
                    );

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

                        if (
                            $gambarUntukDihapus !== '' &&
                            $gambarUntukDihapus !== $namaGambar
                        ) {
                            berita_hapus_gambar(
                                $uploadDir,
                                $gambarUntukDihapus
                            );
                        }

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

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

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

                if ($gambarBaru !== '') {
                    berita_hapus_gambar(
                        $uploadDir,
                        $gambarBaru
                    );
                }

                $act = 'form';
            } else {

                /* =========================
                   INSERT
                ========================= */

                $stmt = $mysqli->prepare("
                    INSERT INTO berita
                    (
                        title,
                        slug,
                        published_at,
                        status,
                        image,
                        content
                    )
                    VALUES (?, ?, ?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'ssssss',
                        $title,
                        $slug,
                        $publishedAt,
                        $status,
                        $namaGambar,
                        $content
                    );

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

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

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

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

                if ($gambarBaru !== '') {
                    berita_hapus_gambar(
                        $uploadDir,
                        $gambarBaru
                    );
                }

                $act = 'form';
            }
        }
    }
}


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

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT *
            FROM berita
            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 === '') {
            header(
                'Location: berita.php?msg=notfound'
            );
            exit;
        }
    }
}


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

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


/* =========================================================
   DATA DAFTAR BERITA
========================================================= */

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

$list = null;

if ($q !== '') {
    $like = '%'.$q.'%';

    $stmt = $mysqli->prepare("
        SELECT *
        FROM berita
        WHERE title LIKE ?
           OR slug LIKE ?
           OR status LIKE ?
           OR published_at LIKE ?
        ORDER BY id DESC
    ");

    if ($stmt) {
        $stmt->bind_param(
            'ssss',
            $like,
            $like,
            $like,
            $like
        );

        $stmt->execute();

        $list = $stmt->get_result();
    }
} else {
    $list = $mysqli->query("
        SELECT *
        FROM berita
        ORDER BY id DESC
    ");
}

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


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

$isEdit = !empty($edit);

$titleValue = $_POST['title']
    ?? $edit['title']
    ?? '';

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

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

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

$contentValue = $_POST['content']
    ?? $edit['content']
    ?? '';

$imageValue = $edit['image']
    ?? '';


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

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

$msgText = [
    'saved' => 'Berita berhasil ditambahkan.',
    'updated' => 'Berita berhasil diperbarui.',
    'deleted' => 'Berita berhasil dihapus.',
    'notfound' => 'Data berita tidak ditemukan.',
    'csrf' => 'Token keamanan tidak valid. Silakan ulangi proses.',
    'error' => 'Terjadi kesalahan saat memproses berita.'
][$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 {
    --berita-green-950: #002818;
    --berita-green-900: #003d22;
    --berita-green-800: #005530;
    --berita-green-700: #047a3d;
    --berita-green-600: #09a04f;
    --berita-green-500: #15c46a;
    --berita-green-400: #35e085;
    --berita-green-100: #dcfaee;
    --berita-green-50: #edfff5;

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

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

    --berita-shadow:
        0 8px 28px rgba(10, 40, 25, .10);

    --berita-radius: 16px;
}

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

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

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

@keyframes berita-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 berita-float {
    0%,
    100% {
        transform: translateY(0);
    }

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

* {
    box-sizing: border-box;
}

body {
    color: var(--berita-ink);
    background-color: var(--berita-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;
}

.berita-page {
    padding: 26px;
}


/* =========================================================
   HEADER
========================================================= */

.berita-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(--berita-green-950),
        var(--berita-green-800),
        var(--berita-green-900)
    );
    background-size: 200% 100%;

    border-radius: var(--berita-radius);

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

    animation:
        berita-gradient 8s ease infinite;
}

.berita-header::before,
.berita-header::after {
    content: "";
    position: absolute;
    border-radius: 50%;
    pointer-events: none;
}

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.berita-header h2 {
    margin: 0;

    color: #ffffff;

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

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

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

    font-size: 27px;
    vertical-align: middle;

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

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

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

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

    animation:
        berita-pulse 2s ease infinite;
}

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

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

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


/* =========================================================
   PANEL
========================================================= */

.berita-panel {
    overflow: hidden;

    background: var(--berita-surface);

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

    border-radius: var(--berita-radius);

    box-shadow: var(--berita-shadow);
}

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 13px;

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

    font-size: 20px;
}

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

    color: var(--berita-ink);

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

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

    color: var(--berita-muted);

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

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


/* =========================================================
   ALERT
========================================================= */

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

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

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

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

    border-radius: 14px;

    box-shadow: var(--berita-shadow);

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

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


/* =========================================================
   TOMBOL
========================================================= */

.berita-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,
        box-shadow .2s ease;
}

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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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

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

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

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

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

    font-size: 12px;
}


/* =========================================================
   TOOLBAR
========================================================= */

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

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

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

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

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

    transform: translateY(-50%);
}

.berita-search input {
    width: 100%;
    padding: 12px 14px 12px 42px;

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

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

    border-radius: 14px;
    outline: none;

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

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

.berita-search input:focus {
    background: #ffffff;

    border-color:
        var(--berita-green-500);

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

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

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

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

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

    border-radius: 999px;

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


/* =========================================================
   TABEL
========================================================= */

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

    background: #ffffff;

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

    border-radius: 16px;
}

.berita-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

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

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

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

.berita-cover {
    width: 105px;
    height: 72px;

    display: block;

    object-fit: cover;

    background: #edf7f1;

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

    border-radius: 13px;

    box-shadow:
        0 6px 16px rgba(0, 0, 0, .10);
}

.berita-cover-empty {
    width: 105px;
    height: 72px;

    display: grid;
    place-items: center;

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

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

    border-radius: 13px;

    font-size: 25px;
}

.berita-title-wrap {
    min-width: 220px;

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

.berita-avatar {
    width: 40px;
    height: 40px;
    flex-shrink: 0;

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 14px;

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

    font-weight: 800;
}

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

.berita-slug {
    max-width: 270px;
    margin-top: 3px;

    overflow: hidden;

    color: var(--berita-muted);

    font-size: 11px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.berita-date-badge {
    padding: 7px 10px;

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

    color: var(--berita-blue-500);
    background: #eef8ff;

    border-radius: 999px;

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

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

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

    border-radius: 999px;

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

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

    border:
        1px solid #b9f0d6;
}

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

    border:
        1px solid #ffe5a0;
}

.berita-actions {
    min-width: 170px;

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

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

.berita-empty {
    padding: 36px !important;

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

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

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

    color: var(--berita-green-600);
    font-size: 34px;
}


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

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

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

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

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

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

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

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

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

    border:
        1px solid var(--berita-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;
}

.berita-input:focus {
    background: #ffffff;

    border-color:
        var(--berita-green-500);

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

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

.berita-upload-box {
    padding: 16px;

    background: #f8fffb;

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

    border-radius: 14px;
}

.berita-upload-preview {
    width: 100%;
    max-width: 320px;
    height: 190px;

    display: block;
    margin-top: 12px;

    object-fit: cover;

    background: #ffffff;

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

    border-radius: 14px;

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

.berita-upload-placeholder {
    width: 100%;
    max-width: 320px;
    height: 190px;

    margin-top: 12px;

    display: grid;
    place-items: center;

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

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

    border-radius: 14px;

    font-size: 45px;
}

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

    color: var(--berita-muted);

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

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

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

    color: var(--berita-red-500);

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

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

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

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

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


/* =========================================================
   CKEDITOR
========================================================= */

.berita-field .cke {
    overflow: hidden;

    border:
        1px solid var(--berita-line) !important;

    border-radius: 13px !important;

    box-shadow: none !important;
}

.berita-field .cke_top {
    background: var(--berita-green-50) !important;

    border-bottom:
        1px solid var(--berita-line) !important;
}

.berita-field .cke_bottom {
    background: #f8fffb !important;

    border-top:
        1px solid var(--berita-line) !important;
}


/* =========================================================
   RESPONSIVE
========================================================= */

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

    .berita-header {
        padding: 20px;
    }

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

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

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

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

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

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

    .berita-actions {
        min-width: 220px;
    }
}
</style>


<div class="berita-page">

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

        <!-- =================================================
             HALAMAN DAFTAR
        ================================================== -->

        <div class="berita-header">
            <div class="berita-header-left">
                <p class="berita-eyebrow">
                    <i class="ri-newspaper-fill"></i>
                    Informasi Desa
                </p>

                <h2>
                    <i class="ri-news-fill berita-title-icon"></i>
                    Berita Desa
                </h2>

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

                    Kelola informasi dan publikasi berita desa
                </p>
            </div>

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

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Berita</h3>

                        <p>
                            Berita draft maupun berita yang telah dipublikasikan.
                        </p>
                    </div>
                </div>

                <div class="berita-stat">
                    <i class="ri-newspaper-fill"></i>
                    <?= (int)$totalBerita ?> Berita
                </div>
            </div>

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

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

                <div class="berita-table-wrap">
                    <table class="berita-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Cover</th>
                                <th>Judul</th>
                                <th>Tanggal</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalBerita === 0): ?>
                                <tr>
                                    <td
                                        colspan="6"
                                        class="berita-empty"
                                    >
                                        <i class="ri-inbox-2-fill"></i>

                                        <?= $q !== ''
                                            ? 'Berita yang dicari tidak ditemukan.'
                                            : 'Belum ada berita. Klik tombol Tambah Berita untuk membuat berita baru.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                <?php while ($row = $list->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <?= $no++ ?>
                                        </td>

                                        <td>
                                            <?php if (!empty($row['image'])): ?>
                                                <img
                                                    src="<?= esc(
                                                        $uploadUrl
                                                        .'/'
                                                        .basename(
                                                            $row['image']
                                                        )
                                                    ) ?>"
                                                    alt="<?= esc(
                                                        $row['title']
                                                    ) ?>"
                                                    class="berita-cover"
                                                    loading="lazy"
                                                >
                                            <?php else: ?>
                                                <div class="berita-cover-empty">
                                                    <i class="ri-image-line"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>

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

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

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

                                        <td>
                                            <span class="berita-date-badge">
                                                <i class="ri-calendar-check-fill"></i>

                                                <?= esc(
                                                    berita_tanggal_indo(
                                                        $row['published_at']
                                                    )
                                                ) ?>
                                            </span>
                                        </td>

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

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

                                                <form
                                                    method="post"
                                                    action="berita.php?a=delete"
                                                    class="berita-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus berita ini? Gambar cover juga akan dihapus dan data 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="berita-btn berita-btn-small berita-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: ?>

        <!-- =================================================
             HALAMAN FORM
        ================================================== -->

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

                    <?= $isEdit
                        ? 'Edit Publikasi'
                        : 'Buat Publikasi' ?>
                </p>

                <h2>
                    <i class="ri-news-fill berita-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui isi, cover, tanggal, dan status berita.'
                        : 'Lengkapi judul, isi, cover, tanggal, dan status berita.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Kolom judul, tanggal, dan isi berita wajib diisi.
                        </p>
                    </div>
                </div>
            </div>

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

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


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

                    <div class="berita-field berita-field-full">
                        <label for="title">
                            Judul Berita
                            <span class="berita-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="berita-input"
                            id="title"
                            name="title"
                            value="<?= esc($titleValue) ?>"
                            placeholder="Masukkan judul berita"
                            maxlength="255"
                            required
                        >
                    </div>

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

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

                        <p class="berita-help">
                            Kosongkan untuk membuat slug otomatis dari judul.
                        </p>
                    </div>

                    <div class="berita-field">
                        <label for="publishedAt">
                            Tanggal Publikasi
                            <span class="berita-required">*</span>
                        </label>

                        <input
                            type="date"
                            class="berita-input"
                            id="publishedAt"
                            name="published_at"
                            value="<?= esc($publishedAtValue) ?>"
                            required
                        >
                    </div>

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

                        <select
                            class="berita-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="berita-section">
                        <i class="ri-article-fill"></i>
                        Isi Berita
                    </div>

                    <div class="berita-field berita-field-full">
                        <label for="editor">
                            Isi Berita
                            <span class="berita-required">*</span>
                        </label>

                        <textarea
                            id="editor"
                            name="content"
                            class="berita-input"
                            rows="12"
                            required
                        ><?= esc($contentValue) ?></textarea>
                    </div>


                    <div class="berita-section">
                        <i class="ri-image-add-fill"></i>
                        Gambar Cover
                    </div>

                    <div class="berita-field berita-field-full">
                        <div class="berita-upload-box">
                            <label for="image">
                                Upload Cover
                            </label>

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

                            <p class="berita-help">
                                Format JPG, PNG, WEBP, atau GIF. Ukuran maksimal 5 MB.
                            </p>

                            <?php if ($imageValue !== ''): ?>
                                <img
                                    id="imagePreview"
                                    class="berita-upload-preview"
                                    src="<?= esc(
                                        $uploadUrl
                                        .'/'
                                        .basename($imageValue)
                                    ) ?>"
                                    alt="Cover berita"
                                >

                                <label class="berita-checkbox">
                                    <input
                                        type="checkbox"
                                        name="hapus_gambar"
                                        value="1"
                                        id="hapusGambar"
                                    >

                                    Hapus gambar cover lama
                                </label>
                            <?php else: ?>
                                <div
                                    id="imagePlaceholder"
                                    class="berita-upload-placeholder"
                                >
                                    <i class="ri-image-line"></i>
                                </div>

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


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

                        <span>
                            Berita berstatus Draft tidak dianggap sebagai
                            berita yang sudah diterbitkan. Pilih Publish
                            ketika berita sudah siap ditampilkan kepada
                            masyarakat.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


<?php if ($act === 'form'): ?>
<script src="https://cdn.ckeditor.com/4.21.0/standard/ckeditor.js"></script>
<?php endif; ?>

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

    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 titleInput = document.getElementById('title');
    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 (titleInput && slugInput) {
        let slugDiubahManual = slugInput.value.trim() !== '';

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

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


    const imageInput = document.getElementById('image');
    const imagePreview = document.getElementById(
        'imagePreview'
    );
    const imagePlaceholder = document.getElementById(
        'imagePlaceholder'
    );
    const hapusGambar = document.getElementById(
        'hapusGambar'
    );

    if (imageInput && imagePreview) {
        imageInput.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(
                    'Format gambar harus JPG, PNG, WEBP, atau GIF.'
                );

                this.value = '';
                return;
            }

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

                this.value = '';
                return;
            }

            const reader = new FileReader();

            reader.onload = function (event) {
                imagePreview.src = event.target.result;
                imagePreview.style.display = 'block';

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

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

            reader.readAsDataURL(file);
        });
    }


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


    const form = document.getElementById('beritaForm');

    if (
        form &&
        typeof CKEDITOR !== 'undefined'
    ) {
        CKEDITOR.replace(
            'editor',
            {
                versionCheck: false,
                height: 360,
                removePlugins: 'elementspath',
                resize_enabled: true
            }
        );

        form.addEventListener('submit', function (event) {
            const editor = CKEDITOR.instances.editor;

            if (editor) {
                editor.updateElement();

                const isiBerita = editor
                    .getData()
                    .replace(/<[^>]*>/g, '')
                    .replace(/&nbsp;/g, ' ')
                    .trim();

                if (isiBerita === '') {
                    event.preventDefault();

                    alert(
                        'Isi berita wajib diisi.'
                    );

                    editor.focus();
                }
            }
        });
    }
})();
</script>

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