<?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 ringkas_teks_pembagian_waris($teks, $batas = 70)
{
    $teks = trim(preg_replace('/\s+/', ' ', (string)$teks));

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

    if (function_exists('mb_strimwidth')) {
        return mb_strimwidth($teks, 0, $batas, '...');
    }

    return strlen($teks) > $batas
        ? substr($teks, 0, $batas).'...'
        : $teks;
}


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

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

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

    $mysqli->begin_transaction();

    try {
        $detailStmt = $mysqli->prepare("
            DELETE FROM surat_pembagian_waris_ahli
            WHERE surat_id = ?
        ");

        if (!$detailStmt) {
            throw new RuntimeException($mysqli->error);
        }

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

        if (!$detailStmt->execute()) {
            throw new RuntimeException($detailStmt->error);
        }

        $detailStmt->close();

        $parentStmt = $mysqli->prepare("
            DELETE FROM surat_pembagian_waris
            WHERE id = ?
        ");

        if (!$parentStmt) {
            throw new RuntimeException($mysqli->error);
        }

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

        if (!$parentStmt->execute()) {
            throw new RuntimeException($parentStmt->error);
        }

        $terhapus = $parentStmt->affected_rows > 0;

        $parentStmt->close();

        $mysqli->commit();

        header(
            'Location: surat_pembagian_waris.php?msg='
            .($terhapus ? 'deleted' : 'notfound')
        );
        exit;
    } catch (Throwable $e) {
        $mysqli->rollback();

        header('Location: surat_pembagian_waris.php?msg=error');
        exit;
    }
}


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

$errorText = '';

if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id              = (int)($_POST['id'] ?? 0);
    $nama_alm        = trim($_POST['nama_alm'] ?? '');
    $desa            = trim($_POST['desa'] ?? '');
    $kecamatan       = trim($_POST['kecamatan'] ?? '');
    $kabupaten       = trim($_POST['kabupaten'] ?? '');
    $objek_waris     = trim(
        $_POST['objek_waris']
        ?? $_POST['obyek_waris']
        ?? ''
    );
    $dusun           = trim($_POST['dusun'] ?? '');
    $luas            = trim($_POST['luas'] ?? '');
    $no_hak_milik    = trim($_POST['no_hak_milik'] ?? '');
    $batas_utara     = trim($_POST['utara'] ?? '');
    $batas_timur     = trim($_POST['timur'] ?? '');
    $batas_selatan   = trim($_POST['selatan'] ?? '');
    $batas_barat     = trim($_POST['barat'] ?? '');

    $ahliInput = $_POST['ahli'] ?? [];

    if (!is_array($ahliInput)) {
        $ahliInput = [];
    }

    $jumlahAhliTerisi = 0;

    foreach ($ahliInput as $ahli) {
        if (
            is_array($ahli) &&
            trim($ahli['nama'] ?? '') !== ''
        ) {
            $jumlahAhliTerisi++;
        }
    }

    if ($nama_alm === '') {
        $errorText = 'Nama almarhum wajib diisi.';
        $act = 'form';
    } elseif ($jumlahAhliTerisi === 0) {
        $errorText = 'Isi minimal satu orang ahli waris.';
        $act = 'form';
    } else {
        $mysqli->begin_transaction();

        try {
            if ($id > 0) {

                /* ===== PASTIKAN DATA EDIT TERSEDIA ===== */

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

                if (!$cekStmt) {
                    throw new RuntimeException($mysqli->error);
                }

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

                if (!$cekStmt->execute()) {
                    throw new RuntimeException($cekStmt->error);
                }

                $cekResult = $cekStmt->get_result();
                $dataAda = $cekResult && $cekResult->num_rows > 0;

                $cekStmt->close();

                if (!$dataAda) {
                    throw new RuntimeException(
                        'Data surat pembagian waris tidak ditemukan.'
                    );
                }


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

                $stmt = $mysqli->prepare("
                    UPDATE surat_pembagian_waris
                    SET
                        nama_alm = ?,
                        desa = ?,
                        kecamatan = ?,
                        kabupaten = ?,
                        objek_waris = ?,
                        dusun = ?,
                        luas = ?,
                        no_hak_milik = ?,
                        batas_utara = ?,
                        batas_timur = ?,
                        batas_selatan = ?,
                        batas_barat = ?
                    WHERE id = ?
                ");

                if (!$stmt) {
                    throw new RuntimeException($mysqli->error);
                }

                $stmt->bind_param(
                    'ssssssssssssi',
                    $nama_alm,
                    $desa,
                    $kecamatan,
                    $kabupaten,
                    $objek_waris,
                    $dusun,
                    $luas,
                    $no_hak_milik,
                    $batas_utara,
                    $batas_timur,
                    $batas_selatan,
                    $batas_barat,
                    $id
                );

                if (!$stmt->execute()) {
                    throw new RuntimeException($stmt->error);
                }

                $stmt->close();

                $suratId = $id;


                /* ===== HAPUS RINCIAN LAMA ===== */

                $hapusDetailStmt = $mysqli->prepare("
                    DELETE FROM surat_pembagian_waris_ahli
                    WHERE surat_id = ?
                ");

                if (!$hapusDetailStmt) {
                    throw new RuntimeException($mysqli->error);
                }

                $hapusDetailStmt->bind_param('i', $suratId);

                if (!$hapusDetailStmt->execute()) {
                    throw new RuntimeException($hapusDetailStmt->error);
                }

                $hapusDetailStmt->close();
            } else {

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

                $stmt = $mysqli->prepare("
                    INSERT INTO surat_pembagian_waris
                    (
                        nama_alm,
                        desa,
                        kecamatan,
                        kabupaten,
                        objek_waris,
                        dusun,
                        luas,
                        no_hak_milik,
                        batas_utara,
                        batas_timur,
                        batas_selatan,
                        batas_barat
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");

                if (!$stmt) {
                    throw new RuntimeException($mysqli->error);
                }

                $stmt->bind_param(
                    'ssssssssssss',
                    $nama_alm,
                    $desa,
                    $kecamatan,
                    $kabupaten,
                    $objek_waris,
                    $dusun,
                    $luas,
                    $no_hak_milik,
                    $batas_utara,
                    $batas_timur,
                    $batas_selatan,
                    $batas_barat
                );

                if (!$stmt->execute()) {
                    throw new RuntimeException($stmt->error);
                }

                $suratId = (int)$stmt->insert_id;

                $stmt->close();
            }


            /* ===== SIMPAN RINCIAN AHLI WARIS ===== */

            $detailStmt = $mysqli->prepare("
                INSERT INTO surat_pembagian_waris_ahli
                (
                    surat_id,
                    nama,
                    umur,
                    pekerjaan,
                    nik,
                    alamat
                )
                VALUES (?, ?, ?, ?, ?, ?)
            ");

            if (!$detailStmt) {
                throw new RuntimeException($mysqli->error);
            }

            $namaAhli = '';
            $umurAhli = 0;
            $pekerjaanAhli = '';
            $nikAhli = '';
            $alamatAhli = '';

            $detailStmt->bind_param(
                'isisss',
                $suratId,
                $namaAhli,
                $umurAhli,
                $pekerjaanAhli,
                $nikAhli,
                $alamatAhli
            );

            $ahliDisimpan = 0;

            foreach ($ahliInput as $ahli) {
                if (!is_array($ahli)) {
                    continue;
                }

                $namaAhli = trim($ahli['nama'] ?? '');

                if ($namaAhli === '') {
                    continue;
                }

                $umurAhli = max(
                    0,
                    (int)($ahli['umur'] ?? 0)
                );

                $pekerjaanAhli = trim(
                    $ahli['pekerjaan'] ?? ''
                );

                $nikAhli = trim(
                    $ahli['nik'] ?? ''
                );

                $alamatAhli = trim(
                    $ahli['alamat'] ?? ''
                );

                if (!$detailStmt->execute()) {
                    throw new RuntimeException($detailStmt->error);
                }

                $ahliDisimpan++;
            }

            $detailStmt->close();

            if ($ahliDisimpan === 0) {
                throw new RuntimeException(
                    'Minimal satu ahli waris harus diisi.'
                );
            }

            $mysqli->commit();

            header(
                'Location: surat_pembagian_waris.php?msg='
                .($id > 0 ? 'updated' : 'saved')
            );
            exit;
        } catch (Throwable $e) {
            $mysqli->rollback();

            error_log(
                '[surat_pembagian_waris] Gagal menyimpan data: '
                .$e->getMessage()
            );

            $errorText = $id > 0
                ? 'Surat pembagian waris gagal diperbarui. Silakan coba kembali.'
                : 'Surat pembagian waris gagal disimpan. Silakan coba kembali.';

            $act = 'form';
        }
    }
}


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

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


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

$edit = null;
$editAhli = [];

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

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

        $detailStmt = $mysqli->prepare("
            SELECT
                id,
                nama,
                umur,
                pekerjaan,
                nik,
                alamat
            FROM surat_pembagian_waris_ahli
            WHERE surat_id = ?
            ORDER BY id ASC
            LIMIT 10
        ");

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

            $detailResult = $detailStmt->get_result();

            if ($detailResult) {
                while ($detail = $detailResult->fetch_assoc()) {
                    $editAhli[] = $detail;
                }
            }

            $detailStmt->close();
        }
    }
}


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

$list = $mysqli->query("
    SELECT
        s.*,
        (
            SELECT COUNT(*)
            FROM surat_pembagian_waris_ahli a
            WHERE a.surat_id = s.id
        ) AS jumlah_ahli,
        (
            SELECT GROUP_CONCAT(a.nama SEPARATOR ' ')
            FROM surat_pembagian_waris_ahli a
            WHERE a.surat_id = s.id
        ) AS nama_ahli
    FROM surat_pembagian_waris s
    ORDER BY s.id DESC
");

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


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

$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 pernyataan pembagian waris berhasil dibuat.',
    'updated' => 'Surat pernyataan pembagian waris berhasil diperbarui.',
    'deleted' => 'Surat pernyataan pembagian waris berhasil dihapus.',
    'notfound' => 'Data surat pembagian waris tidak ditemukan.',
    'error' => 'Terjadi kesalahan saat memproses data.'
][$msgKey] ?? '';

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


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

$isEdit = !empty($edit);

$namaAlmarhumValue = $_POST['nama_alm']
    ?? $edit['nama_alm']
    ?? '';

$desaValue = $_POST['desa']
    ?? $edit['desa']
    ?? '';

$kecamatanValue = $_POST['kecamatan']
    ?? $edit['kecamatan']
    ?? '';

$kabupatenValue = $_POST['kabupaten']
    ?? $edit['kabupaten']
    ?? '';

$obyekWarisValue = $_POST['objek_waris']
    ?? $_POST['obyek_waris']
    ?? $edit['objek_waris']
    ?? '';

$dusunValue = $_POST['dusun']
    ?? $edit['dusun']
    ?? '';

$luasValue = $_POST['luas']
    ?? $edit['luas']
    ?? '';

$noHakMilikValue = $_POST['no_hak_milik']
    ?? $edit['no_hak_milik']
    ?? '';

$utaraValue = $_POST['utara']
    ?? $edit['batas_utara']
    ?? '';

$timurValue = $_POST['timur']
    ?? $edit['batas_timur']
    ?? '';

$selatanValue = $_POST['selatan']
    ?? $edit['batas_selatan']
    ?? '';

$baratValue = $_POST['barat']
    ?? $edit['batas_barat']
    ?? '';


/* ================= NILAI FORM AHLI WARIS ================= */

$ahliSumber = [];

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['ahli']) &&
    is_array($_POST['ahli'])
) {
    $ahliSumber = array_values($_POST['ahli']);
} elseif ($editAhli) {
    $ahliSumber = array_values($editAhli);
}

$ahliForm = [];

for ($i = 0; $i < 10; $i++) {
    $baris = $ahliSumber[$i] ?? [];

    if (!is_array($baris)) {
        $baris = [];
    }

    $ahliForm[$i] = [
        'nama' => $baris['nama'] ?? '',
        'umur' => $baris['umur'] ?? '',
        'pekerjaan' => $baris['pekerjaan'] ?? '',
        'nik' => $baris['nik'] ?? '',
        'alamat' => $baris['alamat'] ?? ''
    ];
}

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

    --pwaris-blue-500: #2080e8;
    --pwaris-yellow-500: #f5b400;
    --pwaris-orange-500: #f26b1d;
    --pwaris-purple-500: #9448d6;

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

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

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

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

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

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

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

* {
    box-sizing: border-box;
}

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

.pwaris-page {
    padding: 26px;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    width: 22px;
    height: 2px;

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

    border-radius: 2px;
}

.pwaris-header h2 {
    margin: 0;

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

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

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

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

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

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

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

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

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

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

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

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


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

.pwaris-panel {
    overflow: hidden;

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

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

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

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

    display: grid;
    place-items: center;

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

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

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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

    backdrop-filter: blur(8px);
}

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

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

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

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

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

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


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

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

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

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

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

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

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

    transition: .2s ease;
}

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

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

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

    transform: translateY(-50%);
}

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

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

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

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


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

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

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

.pwaris-table {
    width: 100%;

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

    font-size: 14px;
}

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

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

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

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

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

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

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

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

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

.pwaris-person {
    display: flex;
    align-items: center;
    gap: 10px;
}

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

    display: grid;
    place-items: center;

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

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

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

.pwaris-location {
    margin-top: 3px;

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

.pwaris-object {
    max-width: 340px;

    color: var(--pwaris-ink);
    font-weight: 600;
    line-height: 1.5;
}

.pwaris-heir-badge {
    padding: 7px 10px;

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

    color: var(--pwaris-purple-500);
    background: #f8efff;
    border-radius: 999px;

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

    margin-top: 4px;
    padding: 13px 15px;

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

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

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

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

.pwaris-help {
    margin: 0;

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

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

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

    margin-top: 4px;
}


/* ================= AHLI WARIS ================= */

.pwaris-heirs {
    grid-column: 1 / -1;

    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16px;
}

.pwaris-heir-card {
    overflow: hidden;

    background: #ffffff;
    border: 1px solid var(--pwaris-line);
    border-radius: 15px;
    box-shadow: 0 6px 18px rgba(10, 40, 25, .06);
}

.pwaris-heir-head {
    padding: 12px 14px;

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

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

    border-bottom: 1px solid var(--pwaris-line);
    font-size: 13px;
    font-weight: 800;
}

.pwaris-heir-number {
    width: 28px;
    height: 28px;

    display: grid;
    place-items: center;

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

    border-radius: 9px;
    font-size: 12px;
}

.pwaris-clear-heir {
    padding: 7px 9px;

    color: var(--pwaris-orange-500);
    background: #fff5ed;
    border: 1px solid #ffe0cb;
    border-radius: 9px;
    cursor: pointer;

    font-family: inherit;
    font-size: 11px;
    font-weight: 800;
}

.pwaris-heir-body {
    padding: 14px;

    display: grid;
    grid-template-columns: 1fr 120px;
    gap: 12px;
}

.pwaris-heir-body .pwaris-field-full {
    grid-column: 1 / -1;
}


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

@media (max-width: 900px) {
    .pwaris-heirs {
        grid-template-columns: 1fr;
    }
}

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

    .pwaris-header {
        padding: 20px;
    }

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

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

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

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

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

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

    .pwaris-heir-body {
        grid-template-columns: 1fr;
    }

    .pwaris-heir-body .pwaris-field-full {
        grid-column: 1;
    }

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


<div class="pwaris-page">

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

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

        <div class="pwaris-header">
            <div class="pwaris-header-left">
                <p class="pwaris-eyebrow">
                    <i class="ri-scales-3-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-team-fill pwaris-title-icon"></i>
                    Surat Pernyataan Pembagian Waris
                </h2>

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

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

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

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

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

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


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

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


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

                    <div>
                        <h3>Daftar Pembagian Waris</h3>

                        <p>
                            Data surat pernyataan pembagian waris yang sudah dibuat.
                        </p>
                    </div>
                </div>

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

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

                        <input
                            type="text"
                            id="searchPembagianWaris"
                            placeholder="Cari almarhum, ahli waris, objek, desa, atau nomor hak milik..."
                        >
                    </div>
                </div>

                <div class="pwaris-table-wrap">
                    <table class="pwaris-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama Almarhum</th>
                                <th>Objek Waris</th>
                                <th>Ahli Waris</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

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

                                        Belum ada surat pembagian 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()): ?>
                                    <?php
                                        $lokasi = array_filter([
                                            $r['dusun'] ?? '',
                                            $r['desa'] ?? '',
                                            $r['kecamatan'] ?? '',
                                            $r['kabupaten'] ?? ''
                                        ]);

                                        $searchText = implode(' ', [
                                            $r['nama_alm'] ?? '',
                                            $r['desa'] ?? '',
                                            $r['kecamatan'] ?? '',
                                            $r['kabupaten'] ?? '',
                                            $r['objek_waris'] ?? '',
                                            $r['dusun'] ?? '',
                                            $r['luas'] ?? '',
                                            $r['no_hak_milik'] ?? '',
                                            $r['nama_ahli'] ?? ''
                                        ]);
                                    ?>

                                    <tr
                                        class="pwaris-data-row"
                                        data-search="<?= esc(strtolower($searchText)) ?>"
                                    >
                                        <td>
                                            <?= $no++ ?>
                                        </td>

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

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

                                                    <div class="pwaris-location">
                                                        <i class="ri-map-pin-2-fill"></i>

                                                        <?= esc(
                                                            $lokasi
                                                                ? implode(', ', $lokasi)
                                                                : '-'
                                                        ) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>

                                        <td>
                                            <div class="pwaris-object">
                                                <?= esc(
                                                    ringkas_teks_pembagian_waris(
                                                        $r['objek_waris'] ?? ''
                                                    )
                                                ) ?>

                                                <?php if (!empty($r['luas'])): ?>
                                                    <div class="pwaris-location">
                                                        Luas:
                                                        <?= esc($r['luas']) ?>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (!empty($r['no_hak_milik'])): ?>
                                                    <div class="pwaris-location">
                                                        No. Hak Milik:
                                                        <?= esc($r['no_hak_milik']) ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </td>

                                        <td>
                                            <span class="pwaris-heir-badge">
                                                <i class="ri-group-fill"></i>

                                                <?= (int)$r['jumlah_ahli'] ?>
                                                Orang
                                            </span>
                                        </td>

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

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

                                                <form
                                                    method="post"
                                                    action="surat_pembagian_waris.php?a=delete"
                                                    class="pwaris-delete-form"
                                                    onsubmit="return confirm('Yakin ingin menghapus surat pembagian waris ini? Seluruh data ahli waris di dalamnya juga akan dihapus.');"
                                                >
                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$r['id'] ?>"
                                                    >

                                                    <button
                                                        type="submit"
                                                        class="pwaris-btn pwaris-btn-small pwaris-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="pwaris-header">
            <div class="pwaris-header-left">
                <p class="pwaris-eyebrow">
                    <i class="<?= $isEdit
                        ? 'ri-edit-2-fill'
                        : 'ri-user-add-fill' ?>"></i>

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

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

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

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

                    <?= $isEdit
                        ? 'Perbarui data almarhum, objek, dan ahli waris.'
                        : 'Lengkapi data almarhum, objek waris, dan ahli waris.' ?>
                </p>
            </div>

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


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


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

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

                        <p>
                            <?= $isEdit
                                ? 'Ubah data dengan teliti sebelum menyimpan.'
                                : 'Isi data utama dan maksimal sepuluh ahli waris.' ?>
                        </p>
                    </div>
                </div>
            </div>

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


                    <!-- ===== DATA ALMARHUM ===== -->

                    <div class="pwaris-section-title">
                        <i class="ri-user-heart-fill"></i>
                        Data Almarhum
                    </div>

                    <div class="pwaris-field pwaris-field-full">
                        <label for="namaAlmarhum">
                            Nama Almarhum
                            <span class="pwaris-required">*</span>
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="namaAlmarhum"
                            name="nama_alm"
                            value="<?= esc($namaAlmarhumValue) ?>"
                            placeholder="Masukkan nama lengkap almarhum"
                            required
                        >
                    </div>

                    <div class="pwaris-field">
                        <label for="desa">
                            Desa
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="desa"
                            name="desa"
                            value="<?= esc($desaValue) ?>"
                            placeholder="Contoh: Mambu"
                        >
                    </div>

                    <div class="pwaris-field">
                        <label for="kecamatan">
                            Kecamatan
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="kecamatan"
                            name="kecamatan"
                            value="<?= esc($kecamatanValue) ?>"
                            placeholder="Nama kecamatan"
                        >
                    </div>

                    <div class="pwaris-field pwaris-field-full">
                        <label for="kabupaten">
                            Kabupaten
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="kabupaten"
                            name="kabupaten"
                            value="<?= esc($kabupatenValue) ?>"
                            placeholder="Nama kabupaten"
                        >
                    </div>


                    <!-- ===== OBJEK WARIS ===== -->

                    <div class="pwaris-section-title">
                        <i class="ri-landscape-fill"></i>
                        Objek Waris
                    </div>

                    <div class="pwaris-field pwaris-field-full">
                        <label for="obyekWaris">
                            Keterangan Objek Waris
                        </label>

                        <textarea
                            class="pwaris-input"
                            id="obyekWaris"
                            name="objek_waris"
                            rows="5"
                            placeholder="Jelaskan objek waris yang akan dibagikan..."
                        ><?= esc($obyekWarisValue) ?></textarea>
                    </div>

                    <div class="pwaris-field">
                        <label for="dusun">
                            Dusun / Lokasi Objek
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="dusun"
                            name="dusun"
                            value="<?= esc($dusunValue) ?>"
                            placeholder="Nama dusun"
                        >
                    </div>

                    <div class="pwaris-field">
                        <label for="luas">
                            Luas
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="luas"
                            name="luas"
                            value="<?= esc($luasValue) ?>"
                            placeholder="Contoh: 1.500 m²"
                        >
                    </div>

                    <div class="pwaris-field pwaris-field-full">
                        <label for="noHakMilik">
                            Nomor Hak Milik
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="noHakMilik"
                            name="no_hak_milik"
                            value="<?= esc($noHakMilikValue) ?>"
                            placeholder="Nomor sertifikat atau nomor hak milik"
                        >
                    </div>


                    <!-- ===== BATAS TANAH ===== -->

                    <div class="pwaris-section-title">
                        <i class="ri-map-2-fill"></i>
                        Batas-Batas Tanah
                    </div>

                    <div class="pwaris-field">
                        <label for="batasUtara">
                            Sebelah Utara
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="batasUtara"
                            name="utara"
                            value="<?= esc($utaraValue) ?>"
                            placeholder="Batas sebelah utara"
                        >
                    </div>

                    <div class="pwaris-field">
                        <label for="batasTimur">
                            Sebelah Timur
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="batasTimur"
                            name="timur"
                            value="<?= esc($timurValue) ?>"
                            placeholder="Batas sebelah timur"
                        >
                    </div>

                    <div class="pwaris-field">
                        <label for="batasSelatan">
                            Sebelah Selatan
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="batasSelatan"
                            name="selatan"
                            value="<?= esc($selatanValue) ?>"
                            placeholder="Batas sebelah selatan"
                        >
                    </div>

                    <div class="pwaris-field">
                        <label for="batasBarat">
                            Sebelah Barat
                        </label>

                        <input
                            type="text"
                            class="pwaris-input"
                            id="batasBarat"
                            name="barat"
                            value="<?= esc($baratValue) ?>"
                            placeholder="Batas sebelah barat"
                        >
                    </div>


                    <!-- ===== AHLI WARIS ===== -->

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

                    <div class="pwaris-field pwaris-field-full">
                        <p class="pwaris-help">
                            Isi minimal satu ahli waris. Baris yang nama ahlinya kosong tidak akan disimpan.
                        </p>
                    </div>

                    <div class="pwaris-heirs">
                        <?php for ($i = 0; $i < 10; $i++): ?>
                            <div
                                class="pwaris-heir-card"
                                data-heir-card="<?= $i ?>"
                            >
                                <div class="pwaris-heir-head">
                                    <div style="display:flex;align-items:center;gap:9px">
                                        <span class="pwaris-heir-number">
                                            <?= $i + 1 ?>
                                        </span>

                                        Ahli Waris <?= $i + 1 ?>
                                    </div>

                                    <button
                                        type="button"
                                        class="pwaris-clear-heir"
                                        data-clear-heir="<?= $i ?>"
                                    >
                                        <i class="ri-eraser-fill"></i>
                                        Kosongkan
                                    </button>
                                </div>

                                <div class="pwaris-heir-body">
                                    <div class="pwaris-field pwaris-field-full">
                                        <label for="ahliNama<?= $i ?>">
                                            Nama
                                            <?= $i === 0
                                                ? '<span class="pwaris-required">*</span>'
                                                : '' ?>
                                        </label>

                                        <input
                                            type="text"
                                            class="pwaris-input"
                                            id="ahliNama<?= $i ?>"
                                            name="ahli[<?= $i ?>][nama]"
                                            value="<?= esc($ahliForm[$i]['nama']) ?>"
                                            placeholder="Nama ahli waris"
                                            <?= $i === 0 ? 'required' : '' ?>
                                        >
                                    </div>

                                    <div class="pwaris-field">
                                        <label for="ahliPekerjaan<?= $i ?>">
                                            Pekerjaan
                                        </label>

                                        <input
                                            type="text"
                                            class="pwaris-input"
                                            id="ahliPekerjaan<?= $i ?>"
                                            name="ahli[<?= $i ?>][pekerjaan]"
                                            value="<?= esc($ahliForm[$i]['pekerjaan']) ?>"
                                            placeholder="Pekerjaan"
                                        >
                                    </div>

                                    <div class="pwaris-field">
                                        <label for="ahliUmur<?= $i ?>">
                                            Umur
                                        </label>

                                        <input
                                            type="number"
                                            class="pwaris-input"
                                            id="ahliUmur<?= $i ?>"
                                            name="ahli[<?= $i ?>][umur]"
                                            value="<?= esc($ahliForm[$i]['umur']) ?>"
                                            placeholder="Umur"
                                            min="0"
                                            max="150"
                                        >
                                    </div>

                                    <div class="pwaris-field pwaris-field-full">
                                        <label for="ahliNik<?= $i ?>">
                                            NIK
                                        </label>

                                        <input
                                            type="text"
                                            class="pwaris-input"
                                            id="ahliNik<?= $i ?>"
                                            name="ahli[<?= $i ?>][nik]"
                                            value="<?= esc($ahliForm[$i]['nik']) ?>"
                                            placeholder="Nomor Induk Kependudukan"
                                            inputmode="numeric"
                                        >
                                    </div>

                                    <div class="pwaris-field pwaris-field-full">
                                        <label for="ahliAlamat<?= $i ?>">
                                            Alamat
                                        </label>

                                        <textarea
                                            class="pwaris-input"
                                            id="ahliAlamat<?= $i ?>"
                                            name="ahli[<?= $i ?>][alamat]"
                                            rows="3"
                                            placeholder="Alamat lengkap ahli waris"
                                        ><?= esc($ahliForm[$i]['alamat']) ?></textarea>
                                    </div>
                                </div>
                            </div>
                        <?php endfor; ?>
                    </div>


                    <!-- ===== TOMBOL ===== -->

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

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

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

    <?php endif; ?>

</div>


<script>
(() => {
    /* ================= PENCARIAN ================= */

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

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

            document
                .querySelectorAll('.pwaris-data-row')
                .forEach((row) => {
                    const rowText = (
                        row.dataset.search ||
                        row.innerText ||
                        ''
                    ).toLowerCase();

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


    /* ================= KOSONGKAN AHLI ================= */

    document
        .querySelectorAll('[data-clear-heir]')
        .forEach((button) => {
            button.addEventListener('click', function () {
                const index = this.dataset.clearHeir;

                const card = document.querySelector(
                    '[data-heir-card="' + index + '"]'
                );

                if (!card) {
                    return;
                }

                card
                    .querySelectorAll('input, textarea')
                    .forEach((field) => {
                        field.value = '';
                    });
            });
        });


    /* ================= JAM WITA ================= */

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

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