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

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

/* =========================
   DATA UMUM
========================= */

$bulan = [
    1=>'Januari','Februari','Maret','April','Mei','Juni',
    'Juli','Agustus','September','Oktober','November','Desember'
];

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

function nomor_penghasilan_ortu_baru($mysqli) {
    $last = $mysqli->query("
        SELECT id FROM surat_penghasilan_ortu
        ORDER BY id DESC
        LIMIT 1
    ")->fetch_assoc();

    $urut = $last ? ((int)$last['id'] + 1) : 1;

    return "031/".$urut."/Ds.M/".date('m')."/".date('Y');
}

function tanggal_indo_penghasilan_ortu($tanggal, $bulan) {
    if (!$tanggal) return '-';

    $time = strtotime($tanggal);
    return date('j', $time).' '.$bulan[(int)date('n', $time)].' '.date('Y', $time);
}

function status_kepala_keluarga_penghasilan_ortu($status) {
    $status = strtolower(trim(str_replace('_', ' ', (string)$status)));
    $status = preg_replace('/\s+/', ' ', $status);

    return in_array($status, ['kepala keluarga', 'kk', 'ayah'], true);
}


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

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

    if ($id > 0) {
        $stmt = $mysqli->prepare("DELETE FROM surat_penghasilan_ortu WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
    }

    header("Location: surat_penghasilan_ortu.php?msg=deleted");
    exit;
}


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

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);
    $pekerjaan_ortu    = trim($_POST['pekerjaan_ortu'] ?? '');
    $penghasilan_ortu  = (int)preg_replace('/\D/', '', $_POST['penghasilan_ortu'] ?? '0');
    $alasan_surat      = trim($_POST['alasan_surat'] ?? '');
    $tanggal_surat     = trim($_POST['tanggal_surat'] ?? '');
    $waktu_ttd         = date('Y-m-d H:i:s');

    if ($nomor_surat === '') {
        $nomor_surat = nomor_penghasilan_ortu_baru($mysqli);
    }

    if ($tanggal_surat === '') {
        $tanggal_surat = date('Y-m-d');
    }

    if ($id > 0) {
        $qr_kode = '';

        $stmt = $mysqli->prepare("SELECT qr_kode FROM surat_penghasilan_ortu WHERE id=? LIMIT 1");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res && $row = $res->fetch_assoc()) {
            $qr_kode = $row['qr_kode'];
        }

        if ($qr_kode === '') {
            $qr_kode = 'SKPO-'.time().'-'.rand(100, 999);
        }

        $qr_hash = hash('sha256', $qr_kode.$nomor_surat);

        $stmt = $mysqli->prepare("
            UPDATE surat_penghasilan_ortu
            SET nomor_surat=?, warga_id=?, pekerjaan_ortu=?, penghasilan_ortu=?,
                alasan_surat=?, tanggal_surat=?, waktu_ttd=?, qr_kode=?, qr_hash=?
            WHERE id=?
        ");

        $stmt->bind_param(
            "sisisssssi",
            $nomor_surat,
            $warga_id,
            $pekerjaan_ortu,
            $penghasilan_ortu,
            $alasan_surat,
            $tanggal_surat,
            $waktu_ttd,
            $qr_kode,
            $qr_hash,
            $id
        );

        $stmt->execute();

        header("Location: surat_penghasilan_ortu.php?msg=updated");
        exit;
    }

    $qr_kode = 'SKPO-'.time().'-'.rand(100, 999);
    $qr_hash = hash('sha256', $qr_kode.$nomor_surat);

    $stmt = $mysqli->prepare("
        INSERT INTO surat_penghasilan_ortu
        (nomor_surat, warga_id, pekerjaan_ortu, penghasilan_ortu,
         alasan_surat, tanggal_surat, waktu_ttd, qr_kode, qr_hash)
        VALUES (?,?,?,?,?,?,?,?,?)
    ");

    $stmt->bind_param(
        "sisisssss",
        $nomor_surat,
        $warga_id,
        $pekerjaan_ortu,
        $penghasilan_ortu,
        $alasan_surat,
        $tanggal_surat,
        $waktu_ttd,
        $qr_kode,
        $qr_hash
    );

    $stmt->execute();

    header("Location: surat_penghasilan_ortu.php?msg=saved");
    exit;
}


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

$edit = null;
$nama_ortu_value = '';

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

    if ($edit_id > 0) {
        $stmt = $mysqli->prepare("SELECT * FROM surat_penghasilan_ortu WHERE id=? LIMIT 1");
        $stmt->bind_param('i', $edit_id);
        $stmt->execute();
        $res = $stmt->get_result();

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

        if ($edit) {
            $stmt = $mysqli->prepare("
                SELECT nama_lengkap, pekerjaan, status_dalam_keluarga, nomor_kk
                FROM infografis
                WHERE id=?
                LIMIT 1
            ");
            $stmt->bind_param('i', $edit['warga_id']);
            $stmt->execute();
            $resW = $stmt->get_result();
            $wEdit = $resW ? $resW->fetch_assoc() : null;

            if ($wEdit) {
                if (status_kepala_keluarga_penghasilan_ortu($wEdit['status_dalam_keluarga'])) {
                    $nama_ortu_value = $wEdit['nama_lengkap'];
                } elseif (!empty($wEdit['nomor_kk'])) {
                    $stmt = $mysqli->prepare("
                        SELECT nama_lengkap, pekerjaan
                        FROM infografis
                        WHERE nomor_kk=?
                        ORDER BY CASE
                            WHEN LOWER(REPLACE(TRIM(COALESCE(status_dalam_keluarga, '')), '_', ' ')) = 'kepala keluarga' THEN 1
                            WHEN LOWER(REPLACE(TRIM(COALESCE(status_dalam_keluarga, '')), '_', ' ')) = 'kk' THEN 2
                            WHEN LOWER(REPLACE(TRIM(COALESCE(status_dalam_keluarga, '')), '_', ' ')) = 'ayah' THEN 3
                            WHEN LOWER(REPLACE(TRIM(COALESCE(status_dalam_keluarga, '')), '_', ' ')) = 'ibu' THEN 4
                            ELSE 5
                        END,
                        tanggal_lahir IS NULL,
                        tanggal_lahir ASC,
                        id ASC
                        LIMIT 1
                    ");
                    $stmt->bind_param('s', $wEdit['nomor_kk']);
                    $stmt->execute();
                    $resOrtu = $stmt->get_result();

                    if ($resOrtu && $ortu = $resOrtu->fetch_assoc()) {
                        $nama_ortu_value = $ortu['nama_lengkap'];
                    }
                }
            }
        }
    }
}


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

$warga = $mysqli->query("
    SELECT id, nama_lengkap, nik, nomor_kk, status_dalam_keluarga, pekerjaan
    FROM infografis
    ORDER BY nama_lengkap ASC
");


/* =========================
   DATA SURAT
========================= */

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

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

$msgKey = $_GET['msg'] ?? '';
$msgText = [
    'saved'   => 'Surat penghasilan orang tua berhasil dibuat.',
    'updated' => 'Surat penghasilan orang tua berhasil diperbarui.',
    'deleted' => 'Surat penghasilan orang tua berhasil dihapus.'
][$msgKey] ?? '';

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">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet">

<style>
:root {
    --green-950: #002818;
    --green-900: #003d22;
    --green-800: #005530;
    --green-700: #047a3d;
    --green-600: #09a04f;
    --green-500: #15c46a;
    --green-400: #35e085;
    --green-100: #dcfaee;
    --green-50:  #edfff5;
    --blue-500:  #2080e8;
    --yellow-500:#f5b400;
    --orange-500:#f26b1d;
    --ink:       #0f1c16;
    --muted:     #5e6e67;
    --line:      #daeae1;
    --surface:   #ffffff;
    --page:      #f3faf6;
    --shadow:    0 8px 28px rgba(10,40,25,.10);
    --shadow-hover: 0 18px 48px rgba(10,40,25,.18);
    --radius:    16px;
}

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

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

* {
    box-sizing: border-box;
}

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

.ortu-page {
    padding: 26px;
}

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

.ortu-header {
    position: relative;
    overflow: hidden;
    padding: 26px 30px;
    margin-bottom: 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    background: linear-gradient(135deg, var(--green-950), var(--green-800), var(--green-900));
    background-size: 200% 100%;
    animation: gradient-shift 8s ease infinite;
    border-radius: var(--radius);
    box-shadow: 0 14px 40px rgba(0,60,30,.28);
}

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

.ortu-header::before {
    width: 200px;
    height: 200px;
    top: -60px;
    right: -50px;
    background: radial-gradient(circle, rgba(21,196,106,.20), transparent 70%);
    animation: float-y 7s ease-in-out infinite;
}

.ortu-header::after {
    width: 120px;
    height: 120px;
    bottom: -30px;
    left: 30%;
    background: radial-gradient(circle, rgba(245,180,0,.12), transparent 70%);
    animation: float-y 5s ease-in-out infinite reverse;
}

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

.ortu-eyebrow {
    margin: 0 0 8px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: var(--green-400);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .10em;
    text-transform: uppercase;
}

.ortu-eyebrow::before {
    content: '';
    width: 22px;
    height: 2px;
    background: linear-gradient(90deg, var(--green-400), var(--green-500));
    border-radius: 2px;
}

.ortu-header h2 {
    margin: 0;
    font-size: clamp(20px, 3vw, 26px);
    font-weight: 800;
    letter-spacing: -.03em;
    color: #fff;
    line-height: 1.2;
}

.ortu-desc {
    margin-top: 10px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: rgba(255,255,255,.75);
    font-size: 12px;
    font-weight: 600;
}

.live-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--green-400);
    flex-shrink: 0;
    animation: pulse-ring 2s ease infinite;
}

.ortu-date {
    display: inline-flex;
    align-items: center;
    gap: 9px;
    padding: 10px 16px;
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.18);
    border-radius: 12px;
    color: #fff;
    font-size: 13px;
    font-weight: 700;
    backdrop-filter: blur(8px);
    margin-right: 8px;
}

.ortu-date i {
    font-size: 18px;
    color: var(--green-400);
    filter: drop-shadow(0 0 6px rgba(53,224,133,.4));
}

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

.ortu-panel {
    background: var(--surface);
    border: 1px solid rgba(210,232,220,.85);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
}

.ortu-panel-head {
    padding: 18px 20px;
    border-bottom: 1px solid var(--line);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 14px;
    flex-wrap: wrap;
    background:
        radial-gradient(circle at top right, rgba(21,196,106,.08), transparent 34%),
        #fff;
}

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

.ortu-panel-icon {
    width: 42px;
    height: 42px;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--green-500), var(--green-800));
    border-radius: 13px;
    font-size: 20px;
    box-shadow: 0 4px 12px rgba(9,160,79,.28);
}

.ortu-panel-title h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 800;
    color: var(--ink);
}

.ortu-panel-title p {
    margin: 3px 0 0;
    color: var(--muted);
    font-size: 12px;
    font-weight: 600;
}

.ortu-body {
    padding: 20px;
}

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

.ortu-page .alert {
    margin-bottom: 16px;
    padding: 13px 15px;
    border-radius: 14px;
    background: var(--green-50);
    color: var(--green-800);
    border: 1px solid var(--green-100);
    font-size: 14px;
    font-weight: 800;
    box-shadow: var(--shadow);
    display: flex;
    align-items: center;
    gap: 9px;
}

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

.ortu-page .btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    padding: 10px 15px;
    border-radius: 12px;
    border: none;
    cursor: pointer;
    text-decoration: none;
    font-size: 13px;
    font-weight: 800;
    line-height: 1;
    transition: transform .2s ease, box-shadow .2s ease, filter .2s ease;
    box-shadow: 0 8px 18px rgba(10,40,25,.12);
}

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

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

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

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

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

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

.ortu-page .btn-light {
    color: #fff;
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.18);
    backdrop-filter: blur(8px);
}

.ortu-page .btn-small {
    font-size: 12px;
    padding: 8px 11px;
    border-radius: 10px;
    box-shadow: none;
}

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

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

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

.search-box input {
    width: 100%;
    padding: 12px 14px 12px 42px;
    border-radius: 14px;
    border: 1px solid var(--line);
    background: #f8fffb;
    outline: none;
    transition: .2s;
    color: var(--ink);
    font-weight: 600;
}

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

.search-box i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--green-700);
    font-size: 18px;
}

.stat-pill {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 10px 14px;
    border-radius: 999px;
    background: var(--green-50);
    color: var(--green-800);
    font-size: 13px;
    font-weight: 800;
    border: 1px solid var(--green-100);
}

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

.table-wrap {
    overflow-x: auto;
    border: 1px solid var(--line);
    border-radius: 16px;
    background: #fff;
}

.ortu-page .table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 14px;
}

.ortu-page .table th {
    background: linear-gradient(180deg, var(--green-50), #f8fffb);
    padding: 14px 13px;
    text-align: left;
    color: var(--green-900);
    border-bottom: 1px solid var(--line);
    white-space: nowrap;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: .04em;
}

.ortu-page .table td {
    padding: 14px 13px;
    border-bottom: 1px solid #edf7f1;
    vertical-align: middle;
}

.ortu-page .table tr:last-child td {
    border-bottom: none;
}

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

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

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

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 14px;
    display: grid;
    place-items: center;
    color: #fff;
    font-weight: 800;
    background: linear-gradient(135deg, var(--green-500), var(--green-800));
    box-shadow: 0 8px 16px rgba(9,160,79,.20);
}

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

.name-sub {
    margin-top: 2px;
    font-size: 12px;
    color: var(--muted);
}

.nomor-surat {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    font-weight: 800;
    color: var(--green-900);
}

.nomor-surat i {
    color: var(--green-600);
}

.money-badge {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 8px 11px;
    border-radius: 999px;
    background: var(--green-50);
    color: var(--green-800);
    font-weight: 800;
    border: 1px solid var(--green-100);
    font-size: 12px;
}

.badge-date {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 10px;
    border-radius: 999px;
    background: #eef8ff;
    color: var(--blue-500);
    font-weight: 800;
    font-size: 12px;
}

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

.actions form {
    margin: 0;
}

.empty {
    text-align: center;
    padding: 34px !important;
    color: var(--muted);
    background: #fbfffd;
    font-weight: 600;
}

.empty i {
    display: block;
    margin-bottom: 8px;
    font-size: 34px;
    color: var(--green-600);
}

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

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

.form-section {
    grid-column: 1 / -1;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 4px;
    padding: 12px 14px;
    border-radius: 14px;
    background: var(--green-50);
    color: var(--green-900);
    font-weight: 800;
    border: 1px solid var(--green-100);
}

.form-section i {
    width: 30px;
    height: 30px;
    border-radius: 10px;
    display: grid;
    place-items: center;
    color: #fff;
    background: linear-gradient(135deg, var(--green-500), var(--green-800));
}

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

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

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

.field-note {
    min-height: 18px;
    color: var(--muted);
    font-size: 12px;
    font-weight: 600;
}

.field-note.is-loading { color: var(--blue-500); }
.field-note.is-success { color: var(--green-700); }
.field-note.is-warning { color: var(--orange-500); }

.warga-search {
    position: relative;
}

.warga-search > i {
    position: absolute;
    top: 50%;
    left: 13px;
    color: var(--green-700);
    font-size: 18px;
    pointer-events: none;
    transform: translateY(-50%);
}

.warga-search-input {
    padding-left: 42px !important;
    padding-right: 44px !important;
}

.warga-search-clear {
    position: absolute;
    top: 50%;
    right: 8px;
    width: 30px;
    height: 30px;
    display: none;
    place-items: center;
    padding: 0;
    border: 0;
    border-radius: 9px;
    color: var(--muted);
    background: transparent;
    cursor: pointer;
    transform: translateY(-50%);
    transition: color .2s ease, background-color .2s ease, transform .2s ease;
}

.warga-search-clear.is-visible { display: grid; }

.warga-search-clear:hover {
    color: var(--green-800);
    background: var(--green-50);
}

.warga-search-clear:active {
    transform: translateY(-50%) scale(.96);
}

.warga-search-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    color: var(--muted);
    font-size: 11px;
    font-weight: 600;
}

.warga-result-count {
    color: var(--green-800);
    font-weight: 800;
}

.warga-search-empty {
    padding: 10px 12px;
    color: var(--orange-500);
    background: #fff8f2;
    border: 1px solid #ffe0ca;
    border-radius: 10px;
    font-size: 12px;
    font-weight: 700;
}

.warga-list {
    min-height: 224px;
    padding: 6px !important;
    overflow-y: auto;
}

.warga-list option {
    padding: 9px 10px;
    border-radius: 7px;
}

.warga-list option:checked {
    color: #fff;
    background: var(--green-700) linear-gradient(0deg, var(--green-700), var(--green-700));
}

.ortu-page .input {
    width: 100%;
    padding: 12px 13px;
    border-radius: 13px;
    border: 1px solid var(--line);
    background: #f8fffb;
    outline: none;
    transition: .2s;
    color: var(--ink);
    font-family: inherit;
    font-weight: 600;
}

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

.ortu-page .input[readonly] {
    color: #4b5f55;
    background: #f1faf5;
}

textarea.input {
    resize: vertical;
}

.form-actions {
    grid-column: 1 / -1;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 4px;
}

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

.ortu-page .select2-container {
    width: 100% !important;
}

.ortu-page .select2-container--default .select2-selection--single {
    height: 46px;
    border-radius: 13px;
    border: 1px solid var(--line);
    background: #f8fffb;
}

.ortu-page .select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 46px;
    padding-left: 13px;
    color: var(--ink);
    font-weight: 600;
}

.ortu-page .select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 46px;
    right: 8px;
}

.ortu-page .select2-container--default.select2-container--focus .select2-selection--single {
    border-color: var(--green-500);
    box-shadow: 0 0 0 4px rgba(21,196,106,.13);
}

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

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

    .ortu-header {
        padding: 20px;
    }

    .ortu-header-actions {
        width: 100%;
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }

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

    .toolbar {
        align-items: stretch;
    }

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

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

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


<div class="ortu-page">

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

        <div class="ortu-header">
            <div class="ortu-header-left">
                <p class="ortu-eyebrow">
                    <i class="ri-parent-fill"></i>
                    Layanan Surat Desa
                </p>

                <h2>
                    <i class="ri-money-dollar-circle-fill" style="font-size:24px;vertical-align:middle;margin-right:8px;color:var(--green-400);filter:drop-shadow(0 0 8px rgba(53,224,133,.5))"></i>
                    Surat Keterangan Penghasilan Orang Tua
                </h2>

                <p class="ortu-desc">
                    <span class="live-dot"></span>
                    Kelola surat penghasilan orang tua warga Desa Mambu — <?= esc($tanggalHariIni) ?>
                </p>
            </div>

            <div class="ortu-header-actions">
                <span class="ortu-date">
                    <i class="ri-time-fill"></i>
                    <span id="liveClock">--:--:--</span>
                    <span style="color:rgba(255,255,255,.55)">WITA</span>
                </span>

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

        <?php if ($msgText): ?>
            <div class="alert">
                <i class="ri-checkbox-circle-fill"></i>
                <?= esc($msgText) ?>
            </div>
        <?php endif; ?>

        <div class="ortu-panel">
            <div class="ortu-panel-head">
                <div class="ortu-panel-title">
                    <div class="ortu-panel-icon">
                        <i class="ri-folder-user-fill"></i>
                    </div>
                    <div>
                        <h3>Daftar Surat Penghasilan Orang Tua</h3>
                        <p>Data surat yang sudah dibuat dan siap dicetak.</p>
                    </div>
                </div>

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

            <div class="ortu-body">
                <div class="toolbar">
                    <div class="search-box">
                        <i class="ri-search-line"></i>
                        <input type="text" id="searchSurat" placeholder="Cari nama, NIK, nomor surat, pekerjaan, penghasilan, atau tanggal...">
                    </div>
                </div>

                <div class="table-wrap">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nomor Surat</th>
                                <th>Nama Warga</th>
                                <th>Pekerjaan Ortu</th>
                                <th>Penghasilan</th>
                                <th>Tanggal</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($total_surat === 0): ?>
                                <tr>
                                    <td colspan="7" class="empty">
                                        <i class="ri-inbox-2-fill"></i>
                                        Belum ada surat penghasilan orang tua. Klik tombol <b>Buat Surat</b> untuk menambahkan data baru.
                                    </td>
                                </tr>
                            <?php endif; ?>

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

                                    <td>
                                        <span class="nomor-surat">
                                            <i class="ri-file-paper-2-fill"></i>
                                            <?= esc($r['nomor_surat']) ?>
                                        </span>
                                    </td>

                                    <td>
                                        <div class="user-cell">
                                            <div class="avatar">
                                                <?= esc(strtoupper(substr($r['nama_lengkap'], 0, 1))) ?>
                                            </div>
                                            <div>
                                                <div class="name-main"><?= esc($r['nama_lengkap']) ?></div>
                                                <div class="name-sub">NIK: <?= esc($r['nik'] ?? '-') ?></div>
                                            </div>
                                        </div>
                                    </td>

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

                                    <td>
                                        <span class="money-badge">
                                            <i class="ri-wallet-3-fill"></i>
                                            Rp <?= number_format((float)$r['penghasilan_ortu'], 0, ',', '.') ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="badge-date">
                                            <i class="ri-calendar-check-fill"></i>
                                            <?= esc(tanggal_indo_penghasilan_ortu($r['tanggal_surat'], $bulan)) ?>
                                        </span>
                                    </td>

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

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

                                            <form method="post"
                                                  action="surat_penghasilan_ortu.php?a=delete"
                                                  onsubmit="return confirm('Yakin ingin menghapus surat penghasilan orang tua ini? Data yang dihapus tidak bisa dikembalikan.');">
                                                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                                <button type="submit" class="btn btn-small btn-delete">
                                                    <i class="ri-delete-bin-6-fill"></i>
                                                    Hapus
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>


    <?php else: ?>

        <?php
            $is_edit = !empty($edit);

            $nomor_value      = $edit['nomor_surat'] ?? nomor_penghasilan_ortu_baru($mysqli);
            $tanggal_value    = $edit['tanggal_surat'] ?? date('Y-m-d');
            $pekerjaan_value  = $edit['pekerjaan_ortu'] ?? '';
            $penghasilan_value= $edit['penghasilan_ortu'] ?? '';
            $alasan_value     = $edit['alasan_surat'] ?? '';
        ?>

        <div class="ortu-header">
            <div class="ortu-header-left">
                <p class="ortu-eyebrow">
                    <i class="<?= $is_edit ? 'ri-edit-2-fill' : 'ri-add-box-fill' ?>"></i>
                    <?= $is_edit ? 'Edit Dokumen Surat' : 'Buat Dokumen Surat' ?>
                </p>

                <h2>
                    <i class="ri-file-edit-fill" style="font-size:24px;vertical-align:middle;margin-right:8px;color:var(--green-400);filter:drop-shadow(0 0 8px rgba(53,224,133,.5))"></i>
                    <?= $is_edit ? 'Edit Surat Penghasilan Orang Tua' : 'Buat Surat Penghasilan Orang Tua' ?>
                </h2>

                <p class="ortu-desc">
                    <span class="live-dot"></span>
                    <?= $is_edit ? 'Perbarui data surat penghasilan orang tua yang sudah dibuat.' : 'Lengkapi data warga dan informasi penghasilan orang tua.' ?>
                </p>
            </div>

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

        <?php if ($msgText): ?>
            <div class="alert">
                <i class="ri-checkbox-circle-fill"></i>
                <?= esc($msgText) ?>
            </div>
        <?php endif; ?>

        <div class="ortu-panel">
            <div class="ortu-panel-head">
                <div class="ortu-panel-title">
                    <div class="ortu-panel-icon">
                        <i class="ri-money-dollar-circle-fill"></i>
                    </div>
                    <div>
                        <h3>Form Surat Penghasilan Orang Tua</h3>
                        <p><?= $is_edit ? 'Ubah data dengan teliti sebelum menyimpan.' : 'Nama dan pekerjaan orang tua akan diisi otomatis dari data KK.' ?></p>
                    </div>
                </div>
            </div>

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

                    <div class="field">
                        <label>Nomor Surat</label>
                        <input class="input" name="nomor_surat" value="<?= esc($nomor_value) ?>" required>
                    </div>

                    <div class="field">
                        <label>Tanggal Surat</label>
                        <input class="input" type="date" name="tanggal_surat" value="<?= esc($tanggal_value) ?>" required>
                    </div>

                    <div class="form-section">
                        <i class="ri-user-location-fill"></i>
                        Data Warga
                    </div>

                    <div class="field full">
                        <label>Pilih Warga</label>
                        <div class="warga-search">
                            <i class="ri-search-line" aria-hidden="true"></i>
                            <input
                                class="input warga-search-input"
                                type="search"
                                id="warga_search"
                                placeholder="Cari nama atau NIK warga..."
                                autocomplete="off"
                                aria-label="Cari nama atau NIK warga">
                            <button class="warga-search-clear" type="button" id="warga_search_clear" aria-label="Hapus pencarian">
                                <i class="ri-close-line" aria-hidden="true"></i>
                            </button>
                        </div>
                        <div class="warga-search-meta">
                            <span>Ketik nama atau NIK, lalu pilih warga.</span>
                            <span class="warga-result-count" id="warga_result_count"><?= (int)$warga->num_rows ?> warga</span>
                        </div>
                        <div class="warga-search-empty" id="warga_search_empty" hidden>
                            Warga tidak ditemukan. Periksa kembali nama atau NIK yang dicari.
                        </div>
                        <select class="input warga-list" name="warga_id" id="warga_id" size="7" required>
                            <option value="">-- Pilih Warga --</option>

                            <?php while ($w = $warga->fetch_assoc()): ?>
                                <option
                                    value="<?= (int)$w['id'] ?>"
                                    data-nama="<?= esc($w['nama_lengkap']) ?>"
                                    data-pekerjaan="<?= esc($w['pekerjaan']) ?>"
                                    data-status="<?= esc($w['status_dalam_keluarga']) ?>"
                                    data-nomor-kk="<?= esc($w['nomor_kk']) ?>"
                                    <?= ((int)($edit['warga_id'] ?? 0) === (int)$w['id']) ? 'selected' : '' ?>>
                                    <?= esc($w['nama_lengkap']) ?> | <?= esc($w['nik']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                        <small class="field-note" id="warga_feedback">Pilih warga untuk menampilkan data orang tua.</small>
                    </div>

                    <div class="form-section">
                        <i class="ri-parent-fill"></i>
                        Data Orang Tua
                    </div>

                    <div class="field">
                        <label>Nama Orang Tua</label>
                        <input class="input" id="nama_ortu" value="<?= esc($nama_ortu_value) ?>" readonly>
                    </div>

                    <div class="field">
                        <label>Pekerjaan Orang Tua</label>
                        <input class="input" name="pekerjaan_ortu" id="pekerjaan_ortu" value="<?= esc($pekerjaan_value) ?>" required>
                    </div>

                    <div class="field">
                        <label>Penghasilan Orang Tua</label>
                        <input class="input" type="number" name="penghasilan_ortu" value="<?= esc($penghasilan_value) ?>" placeholder="Contoh: 1500000" required>
                    </div>

                    <div class="field full">
                        <label>Alasan Pembuatan Surat</label>
                        <textarea class="input" name="alasan_surat" rows="4" placeholder="Contoh: Untuk keperluan administrasi pendidikan / beasiswa / kampus" required><?= esc($alasan_value) ?></textarea>
                    </div>

                    <div class="form-actions">
                        <button class="btn btn-primary" type="submit">
                            <i class="ri-save-3-fill"></i>
                            <?= $is_edit ? 'Perbarui Surat' : 'Simpan Surat' ?>
                        </button>

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

    <?php endif; ?>

</div>


<script>
document.addEventListener('DOMContentLoaded', function () {
    const wargaSelect   = document.getElementById('warga_id');
    const wargaSearch   = document.getElementById('warga_search');
    const wargaClear    = document.getElementById('warga_search_clear');
    const wargaCount    = document.getElementById('warga_result_count');
    const wargaEmpty    = document.getElementById('warga_search_empty');
    const namaOrtu      = document.getElementById('nama_ortu');
    const pekerjaanOrtu = document.getElementById('pekerjaan_ortu');
    const wargaFeedback = document.getElementById('warga_feedback');

    const wargaOptions = wargaSelect
        ? Array.from(wargaSelect.options).filter(function (option) { return option.value; })
        : [];

    function normalisasiPencarian(value) {
        return (value || '')
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .trim();
    }

    function filterWarga() {
        const keyword = normalisasiPencarian(wargaSearch ? wargaSearch.value : '');
        let jumlahHasil = 0;

        wargaOptions.forEach(function (option) {
            const dataCari = normalisasiPencarian(
                option.textContent + ' ' + (option.getAttribute('data-nomor-kk') || '')
            );
            const cocok = !keyword || dataCari.includes(keyword);

            option.hidden = !cocok;
            option.style.display = cocok ? '' : 'none';
            jumlahHasil += cocok ? 1 : 0;
        });

        if (wargaCount) {
            wargaCount.textContent = jumlahHasil + ' warga';
        }

        if (wargaClear) {
            wargaClear.classList.toggle('is-visible', Boolean(keyword));
        }

        if (wargaEmpty) {
            wargaEmpty.hidden = jumlahHasil !== 0;
        }
    }

    if (wargaSearch) {
        wargaSearch.addEventListener('input', filterWarga);
        wargaSearch.addEventListener('keydown', function (event) {
            if (event.key === 'ArrowDown') {
                event.preventDefault();
                wargaSelect?.focus();
            }

            if (event.key === 'Enter') {
                const hasilPertama = wargaOptions.find(function (option) { return !option.hidden; });

                if (hasilPertama && wargaSelect) {
                    event.preventDefault();
                    wargaSelect.value = hasilPertama.value;
                    wargaSelect.dispatchEvent(new Event('change', { bubbles: true }));
                    wargaSelect.focus();
                }
            }
        });
    }

    if (wargaClear) {
        wargaClear.addEventListener('click', function () {
            wargaSearch.value = '';
            filterWarga();
            wargaSearch.focus();
        });
    }

    function isiDataOrangTua(nama, pekerjaan, pesan, statusPesan) {
        if (namaOrtu) namaOrtu.value = nama || '';
        if (pekerjaanOrtu) pekerjaanOrtu.value = pekerjaan || '';

        if (wargaFeedback) {
            wargaFeedback.textContent = pesan || '';
            wargaFeedback.className = 'field-note' + (statusPesan ? ' ' + statusPesan : '');
        }
    }

    if (wargaSelect) wargaSelect.addEventListener('change', function () {
        const opt = this.options[this.selectedIndex];
        if (!opt || !this.value) {
            isiDataOrangTua('', '', 'Pilih warga untuk menampilkan data orang tua.', '');
            return;
        }

        const status    = (opt.getAttribute('data-status') || '')
            .trim()
            .toLowerCase()
            .replace(/_/g, ' ')
            .replace(/\s+/g, ' ');
        const nama      = opt.getAttribute('data-nama') || '';
        const pekerjaan = opt.getAttribute('data-pekerjaan') || '';
        const nomorKK   = opt.getAttribute('data-nomor-kk') || '';
        const wargaId   = this.value;

        // Tampilkan data warga segera; hasil pencarian KK akan menggantikannya.
        isiDataOrangTua(nama, pekerjaan, 'Data warga berhasil ditampilkan.', 'is-success');

        if (['kepala keluarga', 'kk', 'ayah'].includes(status)) {
            isiDataOrangTua(nama, pekerjaan, 'Warga ini tercatat sebagai kepala keluarga/orang tua.', 'is-success');
            return;
        }

        if (nomorKK) {
            if (wargaFeedback) {
                wargaFeedback.textContent = 'Mencari data orang tua berdasarkan nomor KK...';
                wargaFeedback.className = 'field-note is-loading';
            }

            fetch('get_orang_tua_by_kk.php?nomor_kk=' + encodeURIComponent(nomorKK))
                .then(res => {
                    if (!res.ok) {
                        throw new Error('HTTP ' + res.status);
                    }

                    return res.json();
                })
                .then(data => {
                    // Abaikan respons lama jika pengguna sudah memilih warga lain.
                    if (wargaSelect.value !== wargaId) return;

                    if (data.status === 'success') {
                        isiDataOrangTua(
                            data.nama_ortu || nama,
                            data.pekerjaan_ortu || pekerjaan,
                            'Data orang tua berhasil ditemukan dari KK.',
                            'is-success'
                        );
                    } else {
                        isiDataOrangTua(
                            nama,
                            pekerjaan,
                            data.message || 'Data orang tua tidak ditemukan; menggunakan data warga.',
                            'is-warning'
                        );
                    }
                })
                .catch(() => {
                    if (wargaSelect.value !== wargaId) return;
                    isiDataOrangTua(
                        nama,
                        pekerjaan,
                        'Gagal mengambil data KK; menggunakan data warga.',
                        'is-warning'
                    );
                });
        } else {
            isiDataOrangTua(
                nama,
                pekerjaan,
                'Nomor KK belum tersedia; menggunakan data warga.',
                'is-warning'
            );
        }
    });

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

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

            document.querySelectorAll('.data-row').forEach(function (row) {
                row.style.display = row.innerText.toLowerCase().includes(keyword) ? '' : 'none';
            });
        });
    }

    const clockEl = document.getElementById('liveClock');

    const tick = () => {
        if (!clockEl) return;

        clockEl.textContent = new Intl.DateTimeFormat('id-ID', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false,
            timeZone: 'Asia/Makassar'
        }).format(new Date()).replaceAll(':', '.');
    };

    tick();
    setInterval(tick, 1000);
});
</script>

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