<?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 (!in_array($act, ['list', 'form', 'save', 'delete'], true)) {
    $act = 'list';
}


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

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

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

$csrfToken = $_SESSION['csrf_sotk'];


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

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

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

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

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

function sotk_pastikan_folder(
    $uploadDir,
    &$errorText
) {
    if (!is_dir($uploadDir)) {
        $dibuat = mkdir(
            $uploadDir,
            0755,
            true
        );

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

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

    return true;
}

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

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

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

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

        return false;
    }

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

    $maksimalUkuran = 5 * 1024 * 1024;

    if ((int)$file['size'] > $maksimalUkuran) {
        $errorText = 'Ukuran foto 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']
        );
    } else {
        $infoGambar = @getimagesize(
            $file['tmp_name']
        );

        $mimeType = $infoGambar['mime'] ?? '';
    }

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

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

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

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

    $namaFile = 'sotk_'
        .date('YmdHis')
        .'_'
        .$kodeAcak
        .'.'
        .$tipeDiizinkan[$mimeType];

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

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

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

    return $namaFile;
}

function sotk_hapus_foto(
    $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);
    }
}


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

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

    $fotoLama = '';
    $dataDitemukan = false;

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

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

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

        if ($cekStmt->num_rows > 0) {
            $cekStmt->bind_result(
                $fotoLama
            );

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

        $cekStmt->close();
    }

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

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

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

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

    $berhasil = $stmt->execute();

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

    $stmt->close();

    if ($terhapus) {
        sotk_hapus_foto(
            $uploadDir,
            $fotoLama
        );
    }

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


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

$errorText = '';

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

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

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

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

    $urutan = (int)(
        $_POST['urutan'] ?? 0
    );

    $hapusFoto = isset($_POST['hapus_foto']) &&
        $_POST['hapus_foto'] === '1';

    if (
        !is_string($token) ||
        !hash_equals($csrfToken, $token)
    ) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
        $act = 'form';
    } elseif ($nama === '') {
        $errorText = 'Nama aparat wajib diisi.';
        $act = 'form';
    } elseif ($jabatan === '') {
        $errorText = 'Jabatan aparat wajib diisi.';
        $act = 'form';
    } elseif ($urutan < 0) {
        $errorText = 'Urutan tidak boleh bernilai negatif.';
        $act = 'form';
    } elseif (
        function_exists('mb_strlen') &&
        mb_strlen($nama, 'UTF-8') > 255
    ) {
        $errorText = 'Nama aparat maksimal 255 karakter.';
        $act = 'form';
    } elseif (
        function_exists('mb_strlen') &&
        mb_strlen($jabatan, 'UTF-8') > 255
    ) {
        $errorText = 'Jabatan maksimal 255 karakter.';
        $act = 'form';
    } else {
        $fotoLama = '';
        $dataDitemukan = $id === 0;

        if ($id > 0) {
            $cekStmt = $mysqli->prepare("
                SELECT foto
                FROM sotk
                WHERE id = ?
                LIMIT 1
            ");

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

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

                if ($cekStmt->num_rows > 0) {
                    $cekStmt->bind_result(
                        $fotoLama
                    );

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

                $cekStmt->close();
            }
        }

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

        $fotoBaru = sotk_upload_foto(
            $_FILES['foto'] ?? [],
            $uploadDir,
            $errorText
        );

        if ($fotoBaru === false) {
            $act = 'form';
        } else {
            $fotoFinal = (string)$fotoLama;
            $fotoUntukDihapus = '';

            if ($hapusFoto) {
                $fotoFinal = '';

                if ($fotoLama !== '') {
                    $fotoUntukDihapus =
                        $fotoLama;
                }
            }

            if (
                is_string($fotoBaru) &&
                $fotoBaru !== ''
            ) {
                $fotoFinal = $fotoBaru;

                if ($fotoLama !== '') {
                    $fotoUntukDihapus =
                        $fotoLama;
                }
            }

            if ($id > 0) {

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

                $stmt = $mysqli->prepare("
                    UPDATE sotk
                    SET
                        nama = ?,
                        jabatan = ?,
                        foto = ?,
                        urutan = ?
                    WHERE id = ?
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sssii',
                        $nama,
                        $jabatan,
                        $fotoFinal,
                        $urutan,
                        $id
                    );

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

                        if (
                            $fotoUntukDihapus !== '' &&
                            $fotoUntukDihapus !==
                            $fotoFinal
                        ) {
                            sotk_hapus_foto(
                                $uploadDir,
                                $fotoUntukDihapus
                            );
                        }

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

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

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

                if (
                    is_string($fotoBaru) &&
                    $fotoBaru !== ''
                ) {
                    sotk_hapus_foto(
                        $uploadDir,
                        $fotoBaru
                    );
                }

                $act = 'form';
            } else {

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

                $stmt = $mysqli->prepare("
                    INSERT INTO sotk
                    (
                        nama,
                        jabatan,
                        foto,
                        urutan
                    )
                    VALUES (?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sssi',
                        $nama,
                        $jabatan,
                        $fotoFinal,
                        $urutan
                    );

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

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

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

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

                if (
                    is_string($fotoBaru) &&
                    $fotoBaru !== ''
                ) {
                    sotk_hapus_foto(
                        $uploadDir,
                        $fotoBaru
                    );
                }

                $act = 'form';
            }
        }
    }
}


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

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT
                id,
                nama,
                jabatan,
                foto,
                urutan
            FROM sotk
            WHERE id = ?
            LIMIT 1
        ");

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

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

            if ($stmt->num_rows > 0) {
                $editResultId = 0;
                $editNama = '';
                $editJabatan = '';
                $editFoto = '';
                $editUrutan = 0;

                $stmt->bind_result(
                    $editResultId,
                    $editNama,
                    $editJabatan,
                    $editFoto,
                    $editUrutan
                );

                $stmt->fetch();

                $edit = [
                    'id' => $editResultId,
                    'nama' => $editNama,
                    'jabatan' => $editJabatan,
                    'foto' => $editFoto,
                    'urutan' => $editUrutan
                ];
            }

            $stmt->close();
        }

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


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

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


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

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

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

    $list = $mysqli->query("
        SELECT
            id,
            nama,
            jabatan,
            foto,
            urutan
        FROM sotk
        WHERE
            nama LIKE '%{$safeQ}%'
            OR jabatan LIKE '%{$safeQ}%'
            OR urutan LIKE '%{$safeQ}%'
        ORDER BY urutan ASC, id DESC
    ");
} else {
    $list = $mysqli->query("
        SELECT
            id,
            nama,
            jabatan,
            foto,
            urutan
        FROM sotk
        ORDER BY urutan ASC, id DESC
    ");
}

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


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

$isEdit = !empty($edit);

$namaValue = $_POST['nama']
    ?? $edit['nama']
    ?? '';

$jabatanValue = $_POST['jabatan']
    ?? $edit['jabatan']
    ?? '';

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

$fotoValue = $edit['foto']
    ?? '';


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

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

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

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

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

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

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.sotk-page {
    padding: 26px;
}


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

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

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

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

    animation:
        sotk-gradient 8s ease infinite;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.sotk-header h2 {
    margin: 0;

    color: #ffffff;

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

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

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

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

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

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

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

    animation:
        sotk-pulse 2s ease infinite;
}

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

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

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


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

.sotk-panel {
    overflow: hidden;

    background: var(--sotk-surface);

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

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

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

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

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 13px;

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

    font-size: 20px;
}

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

    color: var(--sotk-ink);

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

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

    color: var(--sotk-muted);

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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

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

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

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

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

    font-size: 12px;
}


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

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

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

.sotk-search {
    position: relative;

    min-width: 260px;
    flex: 1;
}

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

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

    transform: translateY(-50%);
}

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

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

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

    border-radius: 14px;
    outline: none;

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

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

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

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

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

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

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

    border-radius: 999px;

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


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

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

    background: #ffffff;

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

    border-radius: 16px;
}

.sotk-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

    border-bottom:
        1px solid #edf7f1;

    vertical-align: middle;
}

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

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

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

.sotk-photo {
    width: 72px;
    height: 72px;

    display: block;

    object-fit: cover;

    background: #edf7f1;

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

    border-radius: 16px;

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

    cursor: pointer;

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

.sotk-photo:hover {
    transform: scale(1.05);

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

.sotk-photo-empty {
    width: 72px;
    height: 72px;

    display: grid;
    place-items: center;

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

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

    border-radius: 16px;

    font-size: 28px;
}

.sotk-person {
    min-width: 230px;

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

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

    display: grid;
    place-items: center;

    color: #ffffff;

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

    border-radius: 14px;

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

    font-weight: 800;
}

.sotk-name {
    color: var(--sotk-ink);

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

.sotk-subtext {
    margin-top: 3px;

    color: var(--sotk-muted);

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

.sotk-position {
    padding: 7px 10px;

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

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

    border-radius: 999px;

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

.sotk-order {
    width: 38px;
    height: 38px;

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

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

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

    border-radius: 12px;

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

.sotk-actions {
    min-width: 230px;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

.sotk-upload-box {
    padding: 17px;

    background: #f8fffb;

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

    border-radius: 14px;
}

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

    color: var(--sotk-muted);

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

.sotk-preview {
    width: 190px;
    height: 230px;

    display: block;
    margin-top: 14px;

    object-fit: cover;

    background: #ffffff;

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

    border-radius: 16px;

    box-shadow:
        0 9px 22px rgba(0, 0, 0, .12);
}

.sotk-preview-placeholder {
    width: 190px;
    height: 230px;

    margin-top: 14px;

    display: grid;
    place-items: center;

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

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

    border-radius: 16px;

    font-size: 54px;
}

.sotk-checkbox {
    margin-top: 11px;

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

    color: var(--sotk-red);

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

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

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

    padding: 12px 14px;

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

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

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

    border-radius: 13px;

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

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

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

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

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


/* =========================================================
   MODAL FOTO
========================================================= */

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

    padding: 24px;

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

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

    backdrop-filter: blur(8px);
}

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

.sotk-modal-content {
    position: relative;

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

    padding: 14px;

    background: #ffffff;

    border-radius: 18px;

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

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

    display: block;

    object-fit: contain;

    border-radius: 12px;
}

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

    width: 40px;
    height: 40px;

    display: grid;
    place-items: center;

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

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

    cursor: pointer;

    font-size: 21px;

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


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

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

    .sotk-header {
        padding: 20px;
    }

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

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

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

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

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

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

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


<div class="sotk-page">

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

        <div class="sotk-header">
            <div class="sotk-header-left">
                <p class="sotk-eyebrow">
                    <i class="ri-government-fill"></i>
                    Pemerintahan Desa
                </p>

                <h2>
                    <i class="ri-team-fill sotk-title-icon"></i>
                    Manajemen SOTK
                </h2>

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

                    Kelola struktur organisasi dan aparat pemerintah desa
                </p>
            </div>

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

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

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

                <a
                    class="sotk-btn sotk-btn-light"
                    href="sotk.php?a=form"
                >
                    <i class="ri-user-add-fill"></i>
                    Tambah Aparat
                </a>
            </div>
        </div>


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

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


        <div class="sotk-panel">
            <div class="sotk-panel-head">
                <div class="sotk-panel-title">
                    <div class="sotk-panel-icon">
                        <i class="ri-organization-chart"></i>
                    </div>

                    <div>
                        <h3>Daftar Aparat Desa</h3>

                        <p>
                            Data struktur organisasi pemerintah desa berdasarkan urutan jabatan.
                        </p>
                    </div>
                </div>

                <div class="sotk-stat">
                    <i class="ri-group-fill"></i>
                    <?= (int)$totalAparat ?> Aparat
                </div>
            </div>

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

                        <input
                            type="text"
                            name="q"
                            value="<?= esc($q) ?>"
                            placeholder="Cari nama, jabatan, atau urutan..."
                            autocomplete="off"
                        >
                    </form>

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

                <div class="sotk-table-wrap">
                    <table class="sotk-table">
                        <thead>
                            <tr>
                                <th>Foto</th>
                                <th>Nama Aparat</th>
                                <th>Jabatan</th>
                                <th>Urutan</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($totalAparat === 0): ?>
                                <tr>
                                    <td
                                        colspan="5"
                                        class="sotk-empty"
                                    >
                                        <i class="ri-team-line"></i>

                                        <?= $q !== ''
                                            ? 'Data aparat yang dicari tidak ditemukan.'
                                            : 'Belum ada data aparat. Klik tombol Tambah Aparat untuk menambahkan data baru.' ?>
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                    $urlFoto = $namaFoto !== ''
                                        ? $uploadUrl.'/'.$namaFoto
                                        : '';
                                    ?>

                                    <tr class="sotk-data-row">
                                        <td>
                                            <?php if ($urlFoto !== ''): ?>
                                                <img
                                                    src="<?= esc($urlFoto) ?>"
                                                    alt="<?= esc(
                                                        $row['nama']
                                                    ) ?>"
                                                    class="sotk-photo sotk-open-photo"
                                                    data-src="<?= esc(
                                                        $urlFoto
                                                    ) ?>"
                                                    data-title="<?= esc(
                                                        $row['nama']
                                                    ) ?>"
                                                    loading="lazy"
                                                >
                                            <?php else: ?>
                                                <div class="sotk-photo-empty">
                                                    <i class="ri-user-3-line"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <div class="sotk-person">
                                                <div class="sotk-avatar">
                                                    <?= esc(
                                                        sotk_inisial(
                                                            $row['nama']
                                                        )
                                                    ) ?>
                                                </div>

                                                <div>
                                                    <div class="sotk-name">
                                                        <?= esc(
                                                            $row['nama']
                                                        ) ?>
                                                    </div>

                                                    <div class="sotk-subtext">
                                                        Aparat Pemerintah Desa
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <span class="sotk-position">
                                                <i class="ri-briefcase-4-fill"></i>

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

                                        <td>
                                            <span class="sotk-order">
                                                <?= (int)$row['urutan'] ?>
                                            </span>
                                        </td>

                                        <td>
                                            <div class="sotk-actions">
                                                <?php if ($urlFoto !== ''): ?>
                                                    <button
                                                        type="button"
                                                        class="sotk-btn sotk-btn-small sotk-btn-view sotk-view-photo"
                                                        data-src="<?= esc(
                                                            $urlFoto
                                                        ) ?>"
                                                        data-title="<?= esc(
                                                            $row['nama']
                                                        ) ?>"
                                                    >
                                                        <i class="ri-eye-fill"></i>
                                                        Lihat
                                                    </button>
                                                <?php endif; ?>

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

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

                    <?= $isEdit
                        ? 'Edit Struktur Organisasi'
                        : 'Tambah Struktur Organisasi' ?>
                </p>

                <h2>
                    <i class="ri-team-fill sotk-title-icon"></i>

                    <?= $isEdit
                        ? 'Edit Data Aparat'
                        : 'Tambah Data Aparat' ?>
                </h2>

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

                    <?= $isEdit
                        ? 'Perbarui nama, jabatan, foto, dan urutan aparat.'
                        : 'Tambahkan aparat baru ke struktur organisasi desa.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            Nama, jabatan, dan urutan wajib diisi dengan benar.
                        </p>
                    </div>
                </div>
            </div>

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

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


                    <div class="sotk-section">
                        <i class="ri-user-settings-fill"></i>
                        Identitas Aparat
                    </div>

                    <div class="sotk-field">
                        <label for="nama">
                            Nama Lengkap
                            <span class="sotk-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="sotk-input"
                            id="nama"
                            name="nama"
                            value="<?= esc($namaValue) ?>"
                            placeholder="Masukkan nama lengkap aparat"
                            maxlength="255"
                            required
                        >
                    </div>

                    <div class="sotk-field">
                        <label for="jabatan">
                            Jabatan
                            <span class="sotk-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="sotk-input"
                            id="jabatan"
                            name="jabatan"
                            value="<?= esc($jabatanValue) ?>"
                            placeholder="Contoh: Kepala Desa"
                            maxlength="255"
                            required
                        >
                    </div>

                    <div class="sotk-field sotk-field-full">
                        <label for="urutan">
                            Urutan Tampilan
                            <span class="sotk-required">*</span>
                        </label>

                        <input
                            type="number"
                            class="sotk-input"
                            id="urutan"
                            name="urutan"
                            value="<?= esc($urutanValue) ?>"
                            min="0"
                            step="1"
                            required
                        >

                        <p class="sotk-help">
                            Angka yang lebih kecil akan tampil lebih dahulu pada daftar struktur organisasi.
                        </p>
                    </div>


                    <div class="sotk-section">
                        <i class="ri-image-add-fill"></i>
                        Foto Aparat
                    </div>

                    <div class="sotk-field sotk-field-full">
                        <div class="sotk-upload-box">
                            <label for="foto">
                                <?= $isEdit
                                    ? 'Ganti Foto'
                                    : 'Pilih Foto' ?>
                            </label>

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

                            <p class="sotk-help">
                                Format JPG, PNG, WEBP, atau GIF.
                                Ukuran maksimal 5 MB.
                                <?= $isEdit
                                    ? 'Kosongkan jika tidak ingin mengganti foto lama.'
                                    : 'Foto bersifat opsional.' ?>
                            </p>

                            <?php if ($fotoValue !== ''): ?>
                                <img
                                    id="fotoPreview"
                                    class="sotk-preview"
                                    src="<?= esc(
                                        $uploadUrl
                                        .'/'
                                        .basename($fotoValue)
                                    ) ?>"
                                    alt="Preview foto aparat"
                                >

                                <div
                                    id="fotoPlaceholder"
                                    class="sotk-preview-placeholder"
                                    style="display:none"
                                >
                                    <i class="ri-user-3-line"></i>
                                </div>

                                <label class="sotk-checkbox">
                                    <input
                                        type="checkbox"
                                        name="hapus_foto"
                                        value="1"
                                        id="hapusFoto"
                                    >

                                    Hapus foto lama
                                </label>
                            <?php else: ?>
                                <div
                                    id="fotoPlaceholder"
                                    class="sotk-preview-placeholder"
                                >
                                    <i class="ri-user-3-line"></i>
                                </div>

                                <img
                                    id="fotoPreview"
                                    class="sotk-preview"
                                    alt="Preview foto aparat"
                                    style="display:none"
                                >
                            <?php endif; ?>
                        </div>
                    </div>


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

                        <span>
                            Ketika foto baru diunggah saat mengedit data,
                            foto lama akan dihapus setelah pembaruan berhasil.
                            Menghapus data aparat juga akan menghapus file
                            foto terkait dari server.
                        </span>
                    </div>

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

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

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

    <?php endif; ?>

</div>


<div
    class="sotk-modal"
    id="sotkPhotoModal"
>
    <div class="sotk-modal-content">
        <button
            type="button"
            class="sotk-modal-close"
            id="closeSotkModal"
            aria-label="Tutup"
        >
            <i class="ri-close-line"></i>
        </button>

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


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

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

    let searchTimer = null;

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

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


    const fotoInput = document.getElementById(
        'foto'
    );

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

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

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

    if (fotoInput && fotoPreview) {
        fotoInput.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(
                        'Foto harus berformat JPG, PNG, WEBP, atau GIF.'
                    );

                    this.value = '';
                    return;
                }

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

                    this.value = '';
                    return;
                }

                const reader = new FileReader();

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

                    fotoPreview.style.display =
                        'block';

                    fotoPreview.style.opacity =
                        '1';

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

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

                reader.readAsDataURL(file);
            }
        );
    }

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


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

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

    const closeModalButton = document.getElementById(
        'closeSotkModal'
    );

    const bukaModal = (src, title) => {
        if (!modal || !modalImage) {
            return;
        }

        modalImage.src = src;
        modalImage.alt = title || 'Foto aparat';

        modal.classList.add('active');

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

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

        modal.classList.remove('active');

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

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

    document
        .querySelectorAll(
            '.sotk-open-photo, .sotk-view-photo'
        )
        .forEach((element) => {
            element.addEventListener(
                'click',
                function () {
                    bukaModal(
                        this.dataset.src || '',
                        this.dataset.title || ''
                    );
                }
            );
        });

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

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

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

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