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

$allowedActions = [
    'list',
    'form',
    'save',
    'delete'
];

if (!in_array($act, $allowedActions, true)) {
    $act = 'list';
}


/* =========================================================
   TOKEN KEAMANAN
========================================================= */

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

$csrfToken = $_SESSION['csrf_pengumuman'];


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

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

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

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

function pengumuman_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 pengumuman_ringkasan($content, $panjang = 120)
{
    $text = trim(
        preg_replace(
            '/\s+/',
            ' ',
            strip_tags((string)$content)
        )
    );

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

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

function pengumuman_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 pengumuman_status_periode(
    $tanggalMulai,
    $tanggalSelesai
) {
    $hariIni = date('Y-m-d');

    if ($hariIni < $tanggalMulai) {
        return [
            'kode' => 'belum',
            'label' => 'Belum Dimulai',
            'icon' => 'ri-time-fill'
        ];
    }

    if ($hariIni > $tanggalSelesai) {
        return [
            'kode' => 'selesai',
            'label' => 'Sudah Berakhir',
            'icon' => 'ri-calendar-close-fill'
        ];
    }

    return [
        'kode' => 'berjalan',
        'label' => 'Sedang Berjalan',
        'icon' => 'ri-calendar-check-fill'
    ];
}


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

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

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

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

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

    $berhasil = $stmt->execute();

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

    $stmt->close();

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


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

$errorText = '';

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

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

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

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

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

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

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

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
    } elseif (
        $title === '' ||
        $content === '' ||
        $startDate === '' ||
        $endDate === ''
    ) {
        $errorText = 'Judul, isi pengumuman, tanggal mulai, dan tanggal selesai wajib diisi.';
        $act = 'form';
    } elseif (
        function_exists('mb_strlen') &&
        mb_strlen($title, 'UTF-8') > 255
    ) {
        $errorText = 'Judul pengumuman maksimal 255 karakter.';
        $act = 'form';
    } elseif (
        !function_exists('mb_strlen') &&
        strlen($title) > 255
    ) {
        $errorText = 'Judul pengumuman maksimal 255 karakter.';
        $act = 'form';
    } elseif (
        !pengumuman_tanggal_valid($startDate) ||
        !pengumuman_tanggal_valid($endDate)
    ) {
        $errorText = 'Format tanggal pengumuman tidak valid.';
        $act = 'form';
    } elseif ($endDate < $startDate) {
        $errorText = 'Tanggal selesai tidak boleh lebih awal dari tanggal mulai.';
        $act = 'form';
    } elseif (
        !in_array(
            $status,
            ['aktif', 'nonaktif'],
            true
        )
    ) {
        $errorText = 'Status pengumuman tidak valid.';
        $act = 'form';
    } elseif ($id > 0) {

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

        $dataDitemukan = false;

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

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

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

            $dataDitemukan =
                $cekStmt->num_rows > 0;

            $cekStmt->close();
        }

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

        $stmt = $mysqli->prepare("
            UPDATE pengumuman
            SET
                title = ?,
                content = ?,
                start_date = ?,
                end_date = ?,
                status = ?
            WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sssssi',
                $title,
                $content,
                $startDate,
                $endDate,
                $status,
                $id
            );

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

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

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

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

        $act = 'form';
    } else {

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

        $stmt = $mysqli->prepare("
            INSERT INTO pengumuman
            (
                title,
                content,
                start_date,
                end_date,
                status
            )
            VALUES (?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sssss',
                $title,
                $content,
                $startDate,
                $endDate,
                $status
            );

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

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

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

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

        $act = 'form';
    }
}


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

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT
                id,
                title,
                content,
                start_date,
                end_date,
                status
            FROM pengumuman
            WHERE id = ?
            LIMIT 1
        ");

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

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

            if ($stmt->num_rows > 0) {
                $editIdResult = 0;
                $editTitle = '';
                $editContent = '';
                $editStartDate = '';
                $editEndDate = '';
                $editStatus = '';

                $stmt->bind_result(
                    $editIdResult,
                    $editTitle,
                    $editContent,
                    $editStartDate,
                    $editEndDate,
                    $editStatus
                );

                $stmt->fetch();

                $edit = [
                    'id' => $editIdResult,
                    'title' => $editTitle,
                    'content' => $editContent,
                    'start_date' => $editStartDate,
                    'end_date' => $editEndDate,
                    'status' => $editStatus
                ];
            }

            $stmt->close();
        }

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


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

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


/* =========================================================
   PENCARIAN DAN DAFTAR DATA
========================================================= */

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

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

$where = [];

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

    $where[] = "(
        title LIKE '%{$safeQ}%'
        OR content LIKE '%{$safeQ}%'
        OR start_date LIKE '%{$safeQ}%'
        OR end_date LIKE '%{$safeQ}%'
    )";
}

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

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

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

$list = $mysqli->query("
    SELECT
        id,
        title,
        content,
        start_date,
        end_date,
        status
    FROM pengumuman
    {$whereSql}
    ORDER BY id DESC
");

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


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

$isEdit = !empty($edit);

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

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

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

$endDateValue = $_POST['end_date']
    ?? $edit['end_date']
    ?? date(
        'Y-m-d',
        strtotime('+7 days')
    );

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


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

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

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

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

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

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

    --pengumuman-radius: 16px;
}

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.pengumuman-page {
    padding: 26px;
}


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

.pengumuman-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(--pengumuman-green-950),
        var(--pengumuman-green-800),
        var(--pengumuman-green-900)
    );

    background-size: 200% 100%;

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

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

    animation:
        pengumuman-gradient 8s ease infinite;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.pengumuman-header h2 {
    margin: 0;

    color: #ffffff;

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

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

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

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

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

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

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

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

    animation:
        pengumuman-pulse 2s ease infinite;
}

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

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

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


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

.pengumuman-panel {
    overflow: hidden;

    background: var(--pengumuman-surface);

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

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

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

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 13px;

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

    font-size: 20px;
}

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

    color: var(--pengumuman-ink);

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

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

    color: var(--pengumuman-muted);

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

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


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

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

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

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

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

    border-radius: 14px;

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

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

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


/* =========================================================
   BUTTON
========================================================= */

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

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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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

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

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

    font-size: 12px;
}


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

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

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

.pengumuman-search {
    position: relative;
}

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

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

    transform: translateY(-50%);
}

.pengumuman-search input {
    width: 100%;
    min-height: 44px;
    padding: 12px 14px 12px 42px;

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

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

    border-radius: 14px;
    outline: none;

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

.pengumuman-filter {
    width: 100%;
    min-height: 44px;
    padding: 10px 13px;

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

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

    border-radius: 14px;
    outline: none;

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

.pengumuman-search input:focus,
.pengumuman-filter:focus {
    background: #ffffff;

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

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

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

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

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

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

    border-radius: 999px;

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


/* =========================================================
   TABLE
========================================================= */

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

    background: #ffffff;

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

    border-radius: 16px;
}

.pengumuman-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

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

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

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

.pengumuman-id {
    width: 36px;
    height: 36px;

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

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

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

    border-radius: 11px;

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

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 14px;

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

    font-weight: 800;
}

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

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

.pengumuman-summary {
    max-width: 360px;
    margin-top: 4px;

    color: var(--pengumuman-muted);

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

.pengumuman-date {
    min-width: 175px;

    display: flex;
    flex-direction: column;
    gap: 6px;
}

.pengumuman-date-item {
    display: flex;
    align-items: center;
    gap: 6px;

    color: var(--pengumuman-muted);

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

.pengumuman-date-item i {
    color: var(--pengumuman-blue-500);
}

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

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

    border-radius: 999px;

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

.pengumuman-status-aktif {
    color: #08743b;
    background: #dcfaee;

    border:
        1px solid #b9f0d6;
}

.pengumuman-status-nonaktif {
    color: #a13b00;
    background: #fff0e7;

    border:
        1px solid #ffd1b3;
}

.pengumuman-period {
    margin-top: 6px;
    padding: 6px 9px;

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

    border-radius: 999px;

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

.pengumuman-period-belum {
    color: #8b5b00;
    background: #fff5d8;
}

.pengumuman-period-berjalan {
    color: #08743b;
    background: #dcfaee;
}

.pengumuman-period-selesai {
    color: #6b7280;
    background: #f1f5f9;
}

.pengumuman-actions {
    min-width: 175px;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

textarea.pengumuman-input {
    min-height: 220px;
    resize: vertical;

    line-height: 1.7;
}

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

.pengumuman-help {
    margin: 0;

    color: var(--pengumuman-muted);

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

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

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

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


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

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

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

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

    .pengumuman-header {
        padding: 20px;
    }

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

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

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

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

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

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

    .pengumuman-actions {
        min-width: 200px;
    }
}
</style>


<div class="pengumuman-page">

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

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

                <h2>
                    <i class="ri-notification-3-fill pengumuman-title-icon"></i>
                    Pengumuman Desa
                </h2>

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

                    Kelola informasi dan pengumuman resmi desa
                </p>
            </div>

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

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Pengumuman</h3>

                        <p>
                            Data pengumuman aktif dan nonaktif.
                        </p>
                    </div>
                </div>

                <div class="pengumuman-stat">
                    <i class="ri-notification-badge-fill"></i>
                    <?= (int)$totalPengumuman ?> Pengumuman
                </div>
            </div>

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

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

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

                        <option
                            value="aktif"
                            <?= $statusFilter === 'aktif'
                                ? 'selected'
                                : '' ?>
                        >
                            Aktif
                        </option>

                        <option
                            value="nonaktif"
                            <?= $statusFilter === 'nonaktif'
                                ? 'selected'
                                : '' ?>
                        >
                            Nonaktif
                        </option>
                    </select>

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

                <div class="pengumuman-table-wrap">
                    <table class="pengumuman-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Pengumuman</th>
                                <th>Periode</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalPengumuman === 0): ?>
                                <tr>
                                    <td
                                        colspan="5"
                                        class="pengumuman-empty"
                                    >
                                        <i class="ri-notification-off-fill"></i>

                                        <?= (
                                            $q !== '' ||
                                            $statusFilter !== ''
                                        )
                                            ? 'Pengumuman yang dicari tidak ditemukan.'
                                            : 'Belum ada pengumuman. Klik tombol Tambah Pengumuman untuk membuat data baru.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                <?php while ($row = $list->fetch_assoc()): ?>
                                    <?php
                                    $periode = pengumuman_status_periode(
                                        $row['start_date'],
                                        $row['end_date']
                                    );
                                    ?>

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

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

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

                                                    <div class="pengumuman-summary">
                                                        <?= esc(
                                                            pengumuman_ringkasan(
                                                                $row['content']
                                                            )
                                                        ) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <div class="pengumuman-date">
                                                <span class="pengumuman-date-item">
                                                    <i class="ri-calendar-event-fill"></i>

                                                    Mulai:
                                                    <?= esc(
                                                        pengumuman_tanggal_indo(
                                                            $row['start_date']
                                                        )
                                                    ) ?>
                                                </span>

                                                <span class="pengumuman-date-item">
                                                    <i class="ri-calendar-close-fill"></i>

                                                    Selesai:
                                                    <?= esc(
                                                        pengumuman_tanggal_indo(
                                                            $row['end_date']
                                                        )
                                                    ) ?>
                                                </span>

                                                <span
                                                    class="pengumuman-period pengumuman-period-<?= esc(
                                                        $periode['kode']
                                                    ) ?>"
                                                >
                                                    <i class="<?= esc(
                                                        $periode['icon']
                                                    ) ?>"></i>

                                                    <?= esc(
                                                        $periode['label']
                                                    ) ?>
                                                </span>
                                            </div>
                                        </td>

                                        <td>
                                            <?php if (
                                                $row['status'] === 'aktif'
                                            ): ?>
                                                <span
                                                    class="pengumuman-status pengumuman-status-aktif"
                                                >
                                                    <i class="ri-checkbox-circle-fill"></i>
                                                    Aktif
                                                </span>
                                            <?php else: ?>
                                                <span
                                                    class="pengumuman-status pengumuman-status-nonaktif"
                                                >
                                                    <i class="ri-close-circle-fill"></i>
                                                    Nonaktif
                                                </span>
                                            <?php endif; ?>
                                        </td>

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

                                                <form
                                                    method="post"
                                                    action="pengumuman.php?a=delete"
                                                    class="pengumuman-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus pengumuman ini? Data yang dihapus 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="pengumuman-btn pengumuman-btn-small pengumuman-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="pengumuman-header">
            <div class="pengumuman-header-left">
                <p class="pengumuman-eyebrow">
                    <i class="<?= $isEdit
                        ? 'ri-edit-2-fill'
                        : 'ri-add-circle-fill' ?>"></i>

                    <?= $isEdit
                        ? 'Edit Informasi Desa'
                        : 'Tambah Informasi Desa' ?>
                </p>

                <h2>
                    <i class="ri-notification-3-fill pengumuman-title-icon"></i>

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

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

                    <?= $isEdit
                        ? 'Perbarui isi, periode, dan status pengumuman.'
                        : 'Masukkan isi, periode, dan status pengumuman.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Tanggal selesai tidak boleh lebih awal dari tanggal mulai.
                        </p>
                    </div>
                </div>
            </div>

            <div class="pengumuman-panel-body">
                <form
                    method="post"
                    action="pengumuman.php?a=save"
                    class="pengumuman-form"
                    id="pengumumanForm"
                >
                    <input
                        type="hidden"
                        name="csrf_token"
                        value="<?= esc($csrfToken) ?>"
                    >

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


                    <div class="pengumuman-section">
                        <i class="ri-file-text-fill"></i>
                        Informasi Pengumuman
                    </div>

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

                        <input
                            type="text"
                            class="pengumuman-input"
                            id="title"
                            name="title"
                            value="<?= esc($titleValue) ?>"
                            placeholder="Contoh: Pemberitahuan Kerja Bakti Desa"
                            maxlength="255"
                            required
                        >
                    </div>

                    <div class="pengumuman-field pengumuman-field-full">
                        <label for="content">
                            Isi Pengumuman
                            <span class="pengumuman-required">*</span>
                        </label>

                        <textarea
                            class="pengumuman-input"
                            id="content"
                            name="content"
                            rows="10"
                            placeholder="Masukkan isi pengumuman secara lengkap..."
                            required
                        ><?= esc($contentValue) ?></textarea>
                    </div>


                    <div class="pengumuman-section">
                        <i class="ri-calendar-schedule-fill"></i>
                        Periode Pengumuman
                    </div>

                    <div class="pengumuman-field">
                        <label for="startDate">
                            Tanggal Mulai
                            <span class="pengumuman-required">*</span>
                        </label>

                        <input
                            type="date"
                            class="pengumuman-input"
                            id="startDate"
                            name="start_date"
                            value="<?= esc($startDateValue) ?>"
                            required
                        >
                    </div>

                    <div class="pengumuman-field">
                        <label for="endDate">
                            Tanggal Selesai
                            <span class="pengumuman-required">*</span>
                        </label>

                        <input
                            type="date"
                            class="pengumuman-input"
                            id="endDate"
                            name="end_date"
                            value="<?= esc($endDateValue) ?>"
                            required
                        >
                    </div>


                    <div class="pengumuman-section">
                        <i class="ri-toggle-fill"></i>
                        Status Publikasi
                    </div>

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

                        <select
                            class="pengumuman-input"
                            id="status"
                            name="status"
                            required
                        >
                            <option
                                value="aktif"
                                <?= $statusValue === 'aktif'
                                    ? 'selected'
                                    : '' ?>
                            >
                                Aktif
                            </option>

                            <option
                                value="nonaktif"
                                <?= $statusValue === 'nonaktif'
                                    ? 'selected'
                                    : '' ?>
                            >
                                Nonaktif
                            </option>
                        </select>

                        <p class="pengumuman-help">
                            Status aktif digunakan agar pengumuman dapat ditampilkan kepada masyarakat.
                        </p>
                    </div>


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

                        <span>
                            Periode tanggal menunjukkan masa berlaku
                            pengumuman. Status aktif atau nonaktif tetap
                            mengikuti pilihan pada form dan tidak berubah
                            otomatis ketika tanggal berakhir.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


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

    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(
        '.pengumuman-search input'
    );

    let searchTimer = null;

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

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


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

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

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

    if (startDate && endDate) {
        startDate.addEventListener('change', function () {
            endDate.min = this.value;

            if (
                endDate.value !== '' &&
                endDate.value < this.value
            ) {
                endDate.value = this.value;
            }
        });

        if (startDate.value !== '') {
            endDate.min = startDate.value;
        }
    }

    if (
        form &&
        startDate &&
        endDate
    ) {
        form.addEventListener('submit', function (event) {
            if (
                startDate.value !== '' &&
                endDate.value !== '' &&
                endDate.value < startDate.value
            ) {
                event.preventDefault();

                alert(
                    'Tanggal selesai tidak boleh lebih awal dari tanggal mulai.'
                );

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

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