<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';

date_default_timezone_set('Asia/Makassar');

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


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

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

    $waktu = strtotime($tanggal);

    if (!$waktu) {
        return '-';
    }

    return date('d-m-Y', $waktu);
}

function format_tanggal_indo_waris($tanggal, $bulanIndonesia)
{
    if (!$tanggal) {
        return '-';
    }

    $waktu = strtotime($tanggal);

    if (!$waktu) {
        return '-';
    }

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


/* ================= NOMOR SURAT OTOMATIS ================= */

$bulanRomawi = [
    'I', 'II', 'III', 'IV', 'V', 'VI',
    'VII', 'VIII', 'IX', 'X', 'XI', 'XII'
];

$lastResult = $mysqli->query("
    SELECT id
    FROM surat_ahli_waris
    ORDER BY id DESC
    LIMIT 1
");

$last = $lastResult ? $lastResult->fetch_assoc() : null;
$urut = $last ? ((int)$last['id'] + 1) : 1;

$nomorSuratOtomatis = sprintf(
    'AW/%03d/Ds.M/%s/%s',
    $urut,
    $bulanRomawi[(int)date('n') - 1],
    date('Y')
);


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

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

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

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

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

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

    $stmt->close();

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


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

$errorText = '';

if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id                    = (int)($_POST['id'] ?? 0);
    $nomor_surat           = trim($_POST['nomor_surat'] ?? '');
    $warga_id              = (int)($_POST['warga_id'] ?? 0);
    $tanggal_meninggal     = trim($_POST['tanggal_meninggal'] ?? '');
    $nomor_akta_kematian   = trim($_POST['nomor_akta_kematian'] ?? '');
    $pasangan               = trim($_POST['pasangan'] ?? '');
    $jumlah_anak           = max(0, (int)($_POST['jumlah_anak'] ?? 0));
    $ahli_waris             = trim($_POST['ahli_waris'] ?? '');
    $saksi                  = trim($_POST['saksi'] ?? '');

    if (
        $nomor_surat === '' ||
        $warga_id <= 0 ||
        $tanggal_meninggal === '' ||
        $ahli_waris === '' ||
        $saksi === ''
    ) {
        $errorText = 'Mohon lengkapi semua data yang wajib diisi.';
        $act = 'form';
    } elseif ($id > 0) {

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

        $stmt = $mysqli->prepare("
            UPDATE surat_ahli_waris
            SET
                nomor_surat = ?,
                warga_id = ?,
                tanggal_meninggal = ?,
                nomor_akta_kematian = ?,
                pasangan = ?,
                jumlah_anak = ?,
                ahli_waris = ?,
                saksi = ?
            WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sisssissi',
                $nomor_surat,
                $warga_id,
                $tanggal_meninggal,
                $nomor_akta_kematian,
                $pasangan,
                $jumlah_anak,
                $ahli_waris,
                $saksi,
                $id
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat ahli waris gagal diperbarui. Silakan coba kembali.';
        $act = 'form';
    } else {

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

        $stmt = $mysqli->prepare("
            INSERT INTO surat_ahli_waris
            (
                nomor_surat,
                warga_id,
                tanggal_meninggal,
                nomor_akta_kematian,
                pasangan,
                jumlah_anak,
                ahli_waris,
                saksi
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param(
                'sisssiss',
                $nomor_surat,
                $warga_id,
                $tanggal_meninggal,
                $nomor_akta_kematian,
                $pasangan,
                $jumlah_anak,
                $ahli_waris,
                $saksi
            );

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

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

            $stmt->close();
        }

        $errorText = 'Surat ahli waris gagal disimpan. Silakan coba kembali.';
        $act = 'form';
    }
}


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

$edit = null;

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

    if ($editId > 0) {
        $stmt = $mysqli->prepare("
            SELECT *
            FROM surat_ahli_waris
            WHERE id = ?
            LIMIT 1
        ");

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

            $result = $stmt->get_result();

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

            $stmt->close();
        }

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


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

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


/* ================= DATA WARGA ================= */

$warga = $mysqli->query("
    SELECT
        id,
        nama_lengkap,
        nik,
        tempat_lahir,
        tanggal_lahir,
        jenis_kelamin,
        agama,
        pekerjaan,
        dusun,
        desa,
        kecamatan,
        kabupaten
    FROM infografis
    ORDER BY nama_lengkap ASC
");


/* ================= DAFTAR SURAT ================= */

$list = $mysqli->query("
    SELECT
        s.*,
        i.nama_lengkap,
        i.nik
    FROM surat_ahli_waris s
    JOIN infografis i
        ON s.warga_id = i.id
    ORDER BY s.id DESC
");

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


/* ================= TANGGAL INDONESIA ================= */

$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'
];

$tanggalHariIni = date('j')
    .' '
    .$bulanIndonesia[(int)date('n')]
    .' '
    .date('Y');


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

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

$msgText = [
    'saved'    => 'Surat keterangan ahli waris berhasil dibuat.',
    'updated'  => 'Surat keterangan ahli waris berhasil diperbarui.',
    'deleted'  => 'Surat keterangan ahli waris berhasil dihapus.',
    'notfound' => 'Data surat keterangan ahli waris tidak ditemukan.',
    'error'    => 'Terjadi kesalahan saat memproses data.'
][$msgKey] ?? '';

$msgType = in_array($msgKey, ['notfound', 'error'], true)
    ? 'error'
    : 'success';


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

$isEdit = !empty($edit);

$nomorValue = $_POST['nomor_surat']
    ?? $edit['nomor_surat']
    ?? $nomorSuratOtomatis;

$wargaValue = (int)(
    $_POST['warga_id']
    ?? $edit['warga_id']
    ?? 0
);

$tanggalMeninggalValue = $_POST['tanggal_meninggal']
    ?? $edit['tanggal_meninggal']
    ?? '';

$nomorAktaValue = $_POST['nomor_akta_kematian']
    ?? $edit['nomor_akta_kematian']
    ?? '';

$pasanganValue = $_POST['pasangan']
    ?? $edit['pasangan']
    ?? '';

$jumlahAnakValue = (int)(
    $_POST['jumlah_anak']
    ?? $edit['jumlah_anak']
    ?? 0
);

$ahliWarisValue = $_POST['ahli_waris']
    ?? $edit['ahli_waris']
    ?? '';

$saksiValue = $_POST['saksi']
    ?? $edit['saksi']
    ?? '';

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 {
    --waris-green-950: #002818;
    --waris-green-900: #003d22;
    --waris-green-800: #005530;
    --waris-green-700: #047a3d;
    --waris-green-600: #09a04f;
    --waris-green-500: #15c46a;
    --waris-green-400: #35e085;
    --waris-green-100: #dcfaee;
    --waris-green-50: #edfff5;

    --waris-blue-500: #2080e8;
    --waris-yellow-500: #f5b400;
    --waris-orange-500: #f26b1d;

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

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

@keyframes waris-pulse-ring {
    0% {
        box-shadow: 0 0 0 0 rgba(9, 160, 79, .45);
    }

    70% {
        box-shadow: 0 0 0 12px rgba(9, 160, 79, 0);
    }

    100% {
        box-shadow: 0 0 0 0 rgba(9, 160, 79, 0);
    }
}

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.waris-page {
    padding: 26px;
}


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

.waris-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;

    background: linear-gradient(
        135deg,
        var(--waris-green-950),
        var(--waris-green-800),
        var(--waris-green-900)
    );
    background-size: 200% 100%;

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

    animation: waris-gradient-shift 8s ease infinite;
}

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

.waris-header::before {
    width: 200px;
    height: 200px;
    top: -60px;
    right: -50px;

    background: radial-gradient(
        circle,
        rgba(21, 196, 106, .20),
        transparent 70%
    );

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

.waris-header::after {
    width: 120px;
    height: 120px;
    bottom: -30px;
    left: 30%;

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

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

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

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

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

    color: var(--waris-green-400);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .10em;
    text-transform: uppercase;
}

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.waris-header h2 {
    margin: 0;

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

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

    color: var(--waris-green-400);
    font-size: 25px;
    vertical-align: middle;

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

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

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

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

    animation: waris-pulse-ring 2s ease infinite;
}

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

.waris-date {
    padding: 10px 16px;

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

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

.waris-date i {
    color: var(--waris-green-400);
    font-size: 18px;

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


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

.waris-panel {
    overflow: hidden;

    background: var(--waris-surface);
    border: 1px solid rgba(210, 232, 220, .85);
    border-radius: var(--waris-radius);
    box-shadow: var(--waris-shadow);
}

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

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

.waris-panel-icon {
    width: 42px;
    height: 42px;

    display: grid;
    place-items: center;

    color: #ffffff;
    background: linear-gradient(
        135deg,
        var(--waris-green-500),
        var(--waris-green-800)
    );

    border-radius: 13px;
    box-shadow: 0 4px 12px rgba(9, 160, 79, .28);
    font-size: 20px;
}

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

    color: var(--waris-ink);
    font-size: 16px;
    font-weight: 800;
}

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

    color: var(--waris-muted);
    font-size: 12px;
    font-weight: 600;
}

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


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

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

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

    color: var(--waris-green-800);
    background: var(--waris-green-50);
    border: 1px solid var(--waris-green-100);
    border-radius: 14px;

    box-shadow: var(--waris-shadow);
    font-size: 14px;
    font-weight: 800;
}

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


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

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

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

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

.waris-btn-light {
    color: #ffffff;
    background: rgba(255, 255, 255, .12);
    border: 1px solid rgba(255, 255, 255, .18);

    backdrop-filter: blur(8px);
}

.waris-btn-print {
    color: #ffffff;
    background: linear-gradient(
        135deg,
        #60b4ff,
        var(--waris-blue-500)
    );
}

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

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

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

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

    border-radius: 10px;
    box-shadow: none;
    font-size: 12px;
}


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

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

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

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

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

    color: var(--waris-ink);
    background: #f8fffb;
    border: 1px solid var(--waris-line);
    border-radius: 14px;
    outline: none;

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

    transition: .2s ease;
}

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

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

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

    transform: translateY(-50%);
}

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

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

    color: var(--waris-green-800);
    background: var(--waris-green-50);
    border: 1px solid var(--waris-green-100);
    border-radius: 999px;

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


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

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

    background: #ffffff;
    border: 1px solid var(--waris-line);
    border-radius: 16px;
}

.waris-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

    border-bottom: 1px solid #edf7f1;
    vertical-align: middle;
}

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

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

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

.waris-number {
    display: inline-flex;
    align-items: center;
    gap: 7px;

    color: var(--waris-green-900);
    font-weight: 800;
    white-space: nowrap;
}

.waris-number i {
    color: var(--waris-green-600);
}

.waris-user {
    display: flex;
    align-items: center;
    gap: 10px;
}

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

    display: grid;
    place-items: center;

    color: #ffffff;
    background: linear-gradient(
        135deg,
        var(--waris-green-500),
        var(--waris-green-800)
    );

    border-radius: 14px;
    box-shadow: 0 8px 16px rgba(9, 160, 79, .20);
    font-weight: 800;
}

.waris-name {
    color: var(--waris-ink);
    font-weight: 800;
}

.waris-nik {
    margin-top: 2px;

    color: var(--waris-muted);
    font-size: 12px;
}

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

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

    color: var(--waris-blue-500);
    background: #eef8ff;
    border-radius: 999px;

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

.waris-child-badge {
    padding: 7px 10px;

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

    color: var(--waris-green-800);
    background: var(--waris-green-50);
    border: 1px solid var(--waris-green-100);
    border-radius: 999px;

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

.waris-actions {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 7px;
}

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

.waris-empty {
    padding: 34px !important;

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

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

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

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


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

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

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

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

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

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

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

    color: var(--waris-ink);
    background: #f8fffb;
    border: 1px solid var(--waris-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;
}

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

.waris-input[readonly] {
    color: var(--waris-green-900);
    background: var(--waris-green-50);
    cursor: not-allowed;
}

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

.waris-help {
    margin: 0;

    color: var(--waris-muted);
    font-size: 11px;
    font-weight: 600;
}

.waris-section-title {
    grid-column: 1 / -1;

    margin-top: 2px;
    padding: 12px 14px;

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

    color: var(--waris-green-900);
    background: var(--waris-green-50);
    border: 1px solid var(--waris-green-100);
    border-radius: 13px;

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

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

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

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

    margin-top: 4px;
}


/* ================= SELECT2 ================= */

.waris-field .select2-container {
    width: 100% !important;
}

.waris-field .select2-container .select2-selection--single {
    height: 44px;

    background: #f8fffb;
    border: 1px solid var(--waris-line);
    border-radius: 13px;
}

.waris-field
.select2-container
.select2-selection--single
.select2-selection__rendered {
    padding-left: 13px;
    padding-right: 38px;

    color: var(--waris-ink);
    font-size: 14px;
    font-weight: 600;
    line-height: 42px;
}

.waris-field
.select2-container
.select2-selection--single
.select2-selection__arrow {
    height: 42px;
    right: 8px;
}

.waris-field
.select2-container--default.select2-container--focus
.select2-selection--single,
.waris-field
.select2-container--default.select2-container--open
.select2-selection--single {
    background: #ffffff;
    border-color: var(--waris-green-500);
    box-shadow: 0 0 0 4px rgba(21, 196, 106, .13);
}


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

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

    .waris-header {
        padding: 20px;
    }

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

    .waris-date,
    .waris-btn-light {
        width: 100%;
        justify-content: center;
    }

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

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

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

    .waris-field-full,
    .waris-section-title,
    .waris-form-actions {
        grid-column: 1;
    }

    .waris-actions {
        min-width: 245px;
    }
}
</style>


<div class="waris-page">

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

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

        <div class="waris-header">
            <div class="waris-header-left">
                <p class="waris-eyebrow">
                    <i class="ri-group-2-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-parent-fill waris-title-icon"></i>
                    Surat Keterangan Ahli Waris
                </h2>

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

                    Kelola surat ahli waris Desa Mambu —
                    <?= esc($tanggalHariIni) ?>
                </p>
            </div>

            <div class="waris-header-actions">
                <span class="waris-date">
                    <i class="ri-time-fill"></i>

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

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

                <a
                    class="waris-btn waris-btn-light"
                    href="surat_ahli_waris.php?a=form"
                >
                    <i class="ri-add-circle-fill"></i>
                    Buat Surat
                </a>
            </div>
        </div>


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

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


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

                    <div>
                        <h3>Daftar Surat Ahli Waris</h3>

                        <p>
                            Data surat keterangan ahli waris yang sudah dibuat.
                        </p>
                    </div>
                </div>

                <div class="waris-stat">
                    <i class="ri-file-list-3-fill"></i>
                    <?= (int)$totalSurat ?> Surat
                </div>
            </div>

            <div class="waris-panel-body">
                <div class="waris-toolbar">
                    <div class="waris-search">
                        <i class="ri-search-line"></i>

                        <input
                            type="text"
                            id="searchSuratWaris"
                            placeholder="Cari nomor surat, nama, NIK, tanggal, atau pasangan..."
                        >
                    </div>
                </div>

                <div class="waris-table-wrap">
                    <table class="waris-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nomor Surat</th>
                                <th>Nama Almarhum</th>
                                <th>Tanggal Meninggal</th>
                                <th>Jumlah Anak</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

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

                                        Belum ada surat keterangan ahli waris.
                                        Klik tombol
                                        <strong>Buat Surat</strong>
                                        untuk menambahkan data baru.
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                <?php while ($r = $list->fetch_assoc()): ?>
                                    <tr class="waris-data-row">
                                        <td>
                                            <?= $no++ ?>
                                        </td>

                                        <td>
                                            <span class="waris-number">
                                                <i class="ri-file-paper-2-fill"></i>

                                                <?= esc($r['nomor_surat']) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <div class="waris-user">
                                                <div class="waris-avatar">
                                                    <?= esc(
                                                        strtoupper(
                                                            substr(
                                                                $r['nama_lengkap'],
                                                                0,
                                                                1
                                                            )
                                                        )
                                                    ) ?>
                                                </div>

                                                <div>
                                                    <div class="waris-name">
                                                        <?= esc($r['nama_lengkap']) ?>
                                                    </div>

                                                    <div class="waris-nik">
                                                        NIK:
                                                        <?= esc($r['nik'] ?? '-') ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

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

                                                <?= esc(
                                                    format_tanggal_indo_waris(
                                                        $r['tanggal_meninggal'],
                                                        $bulanIndonesia
                                                    )
                                                ) ?>
                                            </span>
                                        </td>

                                        <td>
                                            <span class="waris-child-badge">
                                                <i class="ri-group-fill"></i>

                                                <?= (int)$r['jumlah_anak'] ?>
                                                Anak
                                            </span>
                                        </td>

                                        <td>
                                            <div class="waris-actions">
                                                <a
                                                    class="waris-btn waris-btn-small waris-btn-print"
                                                    target="_blank"
                                                    rel="noopener"
                                                    href="surat_ahli_waris_print.php?id=<?= (int)$r['id'] ?>"
                                                >
                                                    <i class="ri-printer-fill"></i>
                                                    Print
                                                </a>

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

                                                <form
                                                    method="post"
                                                    action="surat_ahli_waris.php?a=delete"
                                                    class="waris-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus surat ahli waris ini? Data yang dihapus tidak dapat dikembalikan.');"
                                                >
                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$r['id'] ?>"
                                                    >

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


    <?php else: ?>

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

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

                    <?= $isEdit
                        ? 'Edit Dokumen Ahli Waris'
                        : 'Buat Dokumen Ahli Waris' ?>
                </p>

                <h2>
                    <i class="ri-parent-fill waris-title-icon"></i>

                    <?= $isEdit
                        ? 'Edit Surat Keterangan Ahli Waris'
                        : 'Buat Surat Keterangan Ahli Waris' ?>
                </h2>

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

                    <?= $isEdit
                        ? 'Perbarui data surat ahli waris yang sudah dibuat.'
                        : 'Lengkapi data almarhum, ahli waris, dan saksi.' ?>
                </p>
            </div>

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


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


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

                    <div>
                        <h3>
                            <?= $isEdit
                                ? 'Edit Data Surat'
                                : 'Form Surat Ahli Waris' ?>
                        </h3>

                        <p>
                            <?= $isEdit
                                ? 'Ubah data dengan teliti sebelum menyimpan.'
                                : 'Pilih almarhum lalu lengkapi data ahli waris.' ?>
                        </p>
                    </div>
                </div>
            </div>

            <div class="waris-panel-body">
                <form
                    method="post"
                    action="surat_ahli_waris.php?a=save"
                    class="waris-form"
                >
                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)($edit['id'] ?? 0) ?>"
                    >

                    <div class="waris-field">
                        <label for="nomorSurat">
                            Nomor Surat
                            <span class="waris-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="nomorSurat"
                            name="nomor_surat"
                            value="<?= esc($nomorValue) ?>"
                            required
                        >
                    </div>

                    <div class="waris-field">
                        <label for="wargaId">
                            Pilih Almarhum
                            <span class="waris-required">*</span>
                        </label>

                        <select
                            name="warga_id"
                            id="wargaId"
                            class="waris-input select2"
                            required
                        >
                            <option
                                value=""
                                data-nama=""
                                data-nik=""
                                data-ttl=""
                                data-jk=""
                                data-agama=""
                                data-pekerjaan=""
                                data-alamat=""
                            >
                                -- Pilih Almarhum --
                            </option>

                            <?php if ($warga): ?>
                                <?php while ($w = $warga->fetch_assoc()): ?>
                                    <?php
                                        $tempatLahir = trim(
                                            $w['tempat_lahir'] ?? ''
                                        );

                                        $tanggalLahir = format_tanggal_waris(
                                            $w['tanggal_lahir'] ?? ''
                                        );

                                        $ttl = $tempatLahir !== ''
                                            ? $tempatLahir.', '.$tanggalLahir
                                            : $tanggalLahir;

                                        $alamatParts = [];

                                        if (!empty($w['dusun'])) {
                                            $alamatParts[] = $w['dusun'];
                                        }

                                        if (!empty($w['desa'])) {
                                            $alamatParts[] = 'Desa '.$w['desa'];
                                        }

                                        if (!empty($w['kecamatan'])) {
                                            $alamatParts[] = 'Kec. '.$w['kecamatan'];
                                        }

                                        if (!empty($w['kabupaten'])) {
                                            $alamatParts[] = 'Kab. '.$w['kabupaten'];
                                        }

                                        $alamat = implode(', ', $alamatParts);
                                    ?>

                                    <option
                                        value="<?= (int)$w['id'] ?>"
                                        data-nama="<?= esc($w['nama_lengkap'] ?? '') ?>"
                                        data-nik="<?= esc($w['nik'] ?? '') ?>"
                                        data-ttl="<?= esc($ttl) ?>"
                                        data-jk="<?= esc($w['jenis_kelamin'] ?? '') ?>"
                                        data-agama="<?= esc($w['agama'] ?? '') ?>"
                                        data-pekerjaan="<?= esc($w['pekerjaan'] ?? '') ?>"
                                        data-alamat="<?= esc($alamat) ?>"
                                        <?= $wargaValue === (int)$w['id']
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        <?= esc($w['nama_lengkap']) ?>
                                        -
                                        <?= esc($w['nik']) ?>
                                    </option>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </select>
                    </div>


                    <div class="waris-section-title">
                        <i class="ri-user-search-fill"></i>
                        Data Almarhum dari Data Penduduk
                    </div>

                    <div class="waris-field">
                        <label for="namaAlmarhum">
                            Nama Lengkap
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="namaAlmarhum"
                            readonly
                        >
                    </div>

                    <div class="waris-field">
                        <label for="nikAlmarhum">
                            NIK
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="nikAlmarhum"
                            readonly
                        >
                    </div>

                    <div class="waris-field">
                        <label for="ttlAlmarhum">
                            Tempat / Tanggal Lahir
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="ttlAlmarhum"
                            readonly
                        >
                    </div>

                    <div class="waris-field">
                        <label for="jkAlmarhum">
                            Jenis Kelamin
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="jkAlmarhum"
                            readonly
                        >
                    </div>

                    <div class="waris-field">
                        <label for="agamaAlmarhum">
                            Agama
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="agamaAlmarhum"
                            readonly
                        >
                    </div>

                    <div class="waris-field">
                        <label for="pekerjaanAlmarhum">
                            Pekerjaan
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="pekerjaanAlmarhum"
                            readonly
                        >
                    </div>

                    <div class="waris-field waris-field-full">
                        <label for="alamatAlmarhum">
                            Alamat
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="alamatAlmarhum"
                            readonly
                        >
                    </div>


                    <div class="waris-section-title">
                        <i class="ri-file-info-fill"></i>
                        Data Kematian dan Keluarga
                    </div>

                    <div class="waris-field">
                        <label for="tanggalMeninggal">
                            Tanggal Meninggal
                            <span class="waris-required">*</span>
                        </label>

                        <input
                            type="date"
                            class="waris-input"
                            id="tanggalMeninggal"
                            name="tanggal_meninggal"
                            value="<?= esc($tanggalMeninggalValue) ?>"
                            required
                        >
                    </div>

                    <div class="waris-field">
                        <label for="nomorAktaKematian">
                            Nomor Akta Kematian
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="nomorAktaKematian"
                            name="nomor_akta_kematian"
                            value="<?= esc($nomorAktaValue) ?>"
                            placeholder="Contoh: 7605-KM-01012026-0001"
                        >
                    </div>

                    <div class="waris-field">
                        <label for="pasangan">
                            Nama Pasangan
                        </label>

                        <input
                            type="text"
                            class="waris-input"
                            id="pasangan"
                            name="pasangan"
                            value="<?= esc($pasanganValue) ?>"
                            placeholder="Nama suami atau istri"
                        >
                    </div>

                    <div class="waris-field">
                        <label for="jumlahAnak">
                            Jumlah Anak
                        </label>

                        <input
                            type="number"
                            class="waris-input"
                            id="jumlahAnak"
                            name="jumlah_anak"
                            value="<?= (int)$jumlahAnakValue ?>"
                            min="0"
                            step="1"
                        >
                    </div>


                    <div class="waris-section-title">
                        <i class="ri-group-fill"></i>
                        Daftar Ahli Waris dan Saksi
                    </div>

                    <div class="waris-field waris-field-full">
                        <label for="ahliWaris">
                            Daftar Ahli Waris
                            <span class="waris-required">*</span>
                        </label>

                        <textarea
                            class="waris-input"
                            id="ahliWaris"
                            name="ahli_waris"
                            rows="6"
                            placeholder="Contoh:&#10;1. Ahmad - Anak Kandung&#10;2. Fatimah - Anak Kandung&#10;3. Aminah - Istri"
                            required
                        ><?= esc($ahliWarisValue) ?></textarea>

                        <p class="waris-help">
                            Tulis satu ahli waris dalam satu baris.
                        </p>
                    </div>

                    <div class="waris-field waris-field-full">
                        <label for="saksi">
                            Saksi-Saksi
                            <span class="waris-required">*</span>
                        </label>

                        <textarea
                            class="waris-input"
                            id="saksi"
                            name="saksi"
                            rows="4"
                            placeholder="Contoh:&#10;1. Muhammad Ali&#10;2. Abdullah"
                            required
                        ><?= esc($saksiValue) ?></textarea>

                        <p class="waris-help">
                            Tulis satu nama saksi dalam satu baris.
                        </p>
                    </div>

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

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

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

    <?php endif; ?>

</div>


<script>
(() => {
    const wargaSelect = document.getElementById('wargaId');

    const isiDataAlmarhum = () => {
        if (!wargaSelect) {
            return;
        }

        const option = wargaSelect.options[wargaSelect.selectedIndex];

        const data = option
            ? option.dataset
            : {};

        const fields = {
            namaAlmarhum: data.nama || '',
            nikAlmarhum: data.nik || '',
            ttlAlmarhum: data.ttl || '',
            jkAlmarhum: data.jk || '',
            agamaAlmarhum: data.agama || '',
            pekerjaanAlmarhum: data.pekerjaan || '',
            alamatAlmarhum: data.alamat || ''
        };

        Object.entries(fields).forEach(([id, value]) => {
            const element = document.getElementById(id);

            if (element) {
                element.value = value;
            }
        });
    };

    if (wargaSelect) {
        wargaSelect.addEventListener('change', isiDataAlmarhum);

        isiDataAlmarhum();

        if (window.jQuery) {
            window.jQuery(wargaSelect).on(
                'select2:select select2:clear',
                isiDataAlmarhum
            );
        }
    }


    const searchInput = document.getElementById('searchSuratWaris');

    if (searchInput) {
        searchInput.addEventListener('input', function () {
            const keyword = this.value
                .toLowerCase()
                .trim();

            document
                .querySelectorAll('.waris-data-row')
                .forEach((row) => {
                    const rowText = row.innerText.toLowerCase();

                    row.style.display = rowText.includes(keyword)
                        ? ''
                        : 'none';
                });
        });
    }


    const clockElement = document.getElementById('warisLiveClock');

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

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