<?php

require_once __DIR__ . '/../config/koneksi.php';

/*
|--------------------------------------------------------------------------
| DATA PENDUDUK
|--------------------------------------------------------------------------
| Data diambil langsung dari tabel penduduk.
|--------------------------------------------------------------------------
*/

// Total penduduk
$query_total = mysqli_query(
    $conn,
    "SELECT COUNT(*) AS total FROM penduduk"
);

$data_total = mysqli_fetch_assoc($query_total);
$total_penduduk = (int) $data_total['total'];


// Total laki-laki
$query_laki = mysqli_query(
    $conn,
    "SELECT COUNT(*) AS total
     FROM penduduk
     WHERE jenis_kelamin = 'Laki-laki'"
);

$data_laki = mysqli_fetch_assoc($query_laki);
$total_laki = (int) $data_laki['total'];


// Total perempuan
$query_perempuan = mysqli_query(
    $conn,
    "SELECT COUNT(*) AS total
     FROM penduduk
     WHERE jenis_kelamin = 'Perempuan'"
);

$data_perempuan = mysqli_fetch_assoc($query_perempuan);
$total_perempuan = (int) $data_perempuan['total'];


// Ambil semua data penduduk
$query_penduduk = mysqli_query(
    $conn,
    "SELECT
        id_penduduk,
        pas_foto,
        nama_lengkap,
        nik,
        jenis_kelamin,
        desa,
        dusun,
        rt,
        rw,
        status_perkawinan,
        pendidikan,
        agama,
        pekerjaan,
        tanggal_lahir
     FROM penduduk
     ORDER BY nama_lengkap ASC"
);

?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Data Penduduk | Desa Oelomin</title>

    <link rel="stylesheet" href="../assets/css/data_penduduk.css">
</head>

<body>

<div class="page-container">

    <!-- =====================================================
     HEADER
    ====================================================== -->

    <div class="page-header">

        <div class="header-left">

            <!-- Tombol Kembali -->
            <a href="dashboard.php" class="btn-back" title="Kembali ke Dashboard">
                ← Dashboard
            </a>

            <div class="header-icon">
                📊
            </div>

            <div class="header-title">

                <h1>Data Penduduk</h1>

                <p>
                    Kelola dan pantau data penduduk Desa Oelomin
                    secara terpusat.
                </p>

            </div>

        </div>


        <!-- Tombol Tambah -->
        <a href="tambah_penduduk.php" class="btn-add">

            <span>＋</span>

            Tambah Penduduk

        </a>

    </div>


    <!-- =====================================================
         STATISTIK
    ====================================================== -->
    <div class="stat-grid">

        <!-- Total -->
        <div class="stat-card total">

            <div class="stat-icon">
                👥
            </div>

            <div class="stat-content">
                <span>Total Penduduk</span>
                <strong><?= number_format($total_penduduk); ?></strong>
                <small>Orang</small>
            </div>

        </div>


        <!-- Laki-laki -->
        <div class="stat-card male">

            <div class="stat-icon">
                👨
            </div>

            <div class="stat-content">
                <span>Laki-laki</span>
                <strong><?= number_format($total_laki); ?></strong>
                <small>Orang</small>
            </div>

        </div>


        <!-- Perempuan -->
        <div class="stat-card female">

            <div class="stat-icon">
                👩
            </div>

            <div class="stat-content">
                <span>Perempuan</span>
                <strong><?= number_format($total_perempuan); ?></strong>
                <small>Orang</small>
            </div>

        </div>

    </div>


    <!-- =====================================================
         DAFTAR PENDUDUK
    ====================================================== -->
    <div class="content-card">

        <div class="content-header">

            <div>
                <h2>Daftar Penduduk</h2>
                <p>
                    Seluruh data penduduk yang tersimpan dalam sistem.
                </p>
            </div>

            <div class="data-info">
                <span class="data-count">
                    <?= number_format($total_penduduk); ?>
                </span>
                Data
            </div>

        </div>


        <!-- =================================================
             SEARCH DAN FILTER
        ================================================== -->
        <div class="toolbar">

            <div class="search-box">

                <span class="search-icon">🔍</span>

                <input
                    type="text"
                    id="searchInput"
                    placeholder="Cari nama, NIK, dusun, pekerjaan..."
                    onkeyup="filterTable()"
                >

            </div>


            <div class="filter-box">

                <select id="genderFilter" onchange="filterTable()">

                    <option value="">Semua Jenis Kelamin</option>

                    <option value="Laki-laki">
                        Laki-laki
                    </option>

                    <option value="Perempuan">
                        Perempuan
                    </option>

                </select>

            </div>

        </div>


        <!-- =================================================
             TABLE
        ================================================== -->
        <div class="table-wrapper">

            <table id="pendudukTable">

                <thead>

                    <tr>

                        <th width="55">No</th>

                        <th width="80">Foto</th>

                        <th>NIK</th>

                        <th>Nama Lengkap</th>

                        <th>Jenis Kelamin</th>

                        <th>Desa</th>

                        <th>Dusun</th>

                        <th>RT</th>

                        <th>RW</th>

                        <th>Status Perkawinan</th>

                        <th>Pendidikan</th>

                        <th>Agama</th>

                        <th>Pekerjaan</th>

                        <th>Tanggal Lahir</th>

                        <th width="150">Aksi</th>

                    </tr>

                </thead>


                <tbody>

                <?php if (mysqli_num_rows($query_penduduk) > 0): ?>

                    <?php $no = 1; ?>

                    <?php while ($row = mysqli_fetch_assoc($query_penduduk)): ?>

                        <tr>

                            <!-- Nomor -->
                            <td class="number-cell">
                                <?= $no++; ?>
                            </td>


                            <!-- Foto -->
                            <td>

                                <?php if (!empty($row['pas_foto'])): ?>

                                    <img
                                        src="../uploads/<?= htmlspecialchars($row['pas_foto']); ?>"
                                        alt="Foto <?= htmlspecialchars($row['nama_lengkap']); ?>"
                                        class="profile-photo"
                                        onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
                                    >

                                    <div
                                        class="default-photo"
                                        style="display:none;"
                                    >
                                        👤
                                    </div>

                                <?php else: ?>

                                    <div class="default-photo">
                                        👤
                                    </div>

                                <?php endif; ?>

                            </td>


                            <!-- NIK -->
                            <td>
                                <span class="nik">
                                    <?= htmlspecialchars($row['nik']); ?>
                                </span>
                            </td>


                            <!-- Nama -->
                            <td>

                                <div class="name-cell">

                                    <strong>
                                        <?= htmlspecialchars($row['nama_lengkap']); ?>
                                    </strong>

                                </div>

                            </td>


                            <!-- Jenis Kelamin -->
                            <td>

                                <?php if ($row['jenis_kelamin'] === 'Laki-laki'): ?>

                                    <span class="badge badge-male">
                                        👨 Laki-laki
                                    </span>

                                <?php else: ?>

                                    <span class="badge badge-female">
                                        👩 Perempuan
                                    </span>

                                <?php endif; ?>

                            </td>


                            <!-- Desa -->
                            <td>
                                <?= htmlspecialchars($row['desa'] ?? '-'); ?>
                            </td>


                            <!-- Dusun -->
                            <td>
                                <?= htmlspecialchars($row['dusun'] ?? '-'); ?>
                            </td>


                            <!-- RT -->
                            <td>
                                <?= htmlspecialchars($row['rt'] ?? '-'); ?>
                            </td>


                            <!-- RW -->
                            <td>
                                <?= htmlspecialchars($row['rw'] ?? '-'); ?>
                            </td>


                            <!-- Status Perkawinan -->
                            <td>

                                <span class="status-badge">

                                    <?= htmlspecialchars(
                                        $row['status_perkawinan'] ?? '-'
                                    ); ?>

                                </span>

                            </td>


                            <!-- Pendidikan -->
                            <td>
                                <?= htmlspecialchars($row['pendidikan'] ?? '-'); ?>
                            </td>


                            <!-- Agama -->
                            <td>
                                <?= htmlspecialchars($row['agama'] ?? '-'); ?>
                            </td>


                            <!-- Pekerjaan -->
                            <td>
                                <?= htmlspecialchars($row['pekerjaan'] ?? '-'); ?>
                            </td>


                            <!-- Tanggal Lahir -->
                            <td>

                                <?php

                                if (!empty($row['tanggal_lahir'])) {

                                    echo date(
                                        'd-m-Y',
                                        strtotime($row['tanggal_lahir'])
                                    );

                                } else {

                                    echo '-';

                                }

                                ?>

                            </td>


                            <!-- Aksi -->
                            <td>

                                <div class="action-buttons">

                                    <a
                                        href="edit_penduduk.php?id=<?= $row['id_penduduk']; ?>"
                                        class="btn-edit"
                                    >
                                        ✏ Edit
                                    </a>


                                    <a
                                        href="hapus_penduduk.php?id=<?= $row['id_penduduk']; ?>"
                                        class="btn-delete"
                                        onclick="return confirm('Apakah Anda yakin ingin menghapus data <?= htmlspecialchars($row['nama_lengkap']); ?>?');"
                                    >
                                        🗑 Hapus
                                    </a>

                                </div>

                            </td>

                        </tr>

                    <?php endwhile; ?>

                <?php else: ?>

                    <tr id="emptyRow">

                        <td colspan="15">

                            <div class="empty-state">

                            <div class="empty-icon">
                                👥
                            </div>

                            <h3>Belum Ada Data Penduduk</h3>

                            <p>
                                Belum ada data penduduk yang tersimpan dalam sistem.
                                Silakan gunakan tombol <strong>Tambah Penduduk</strong>
                                di bagian atas untuk menambahkan data.
                            </p>

                        </div>

                        </td>

                    </tr>

                <?php endif; ?>

                </tbody>

            </table>

        </div>


        <!-- Tidak ditemukan -->
        <div
            id="noResult"
            class="no-result"
            style="display:none;"
        >
            🔎 Tidak ada data penduduk yang sesuai dengan pencarian.
        </div>

    </div>

</div>


<!-- =====================================================
     JAVASCRIPT PENCARIAN
====================================================== -->

<script>

function filterTable() {

    const searchInput =
        document.getElementById("searchInput")
        .value
        .toLowerCase();

    const genderFilter =
        document.getElementById("genderFilter")
        .value
        .toLowerCase();

    const table =
        document.getElementById("pendudukTable");

    const rows =
        table.querySelectorAll("tbody tr");

    let found = 0;

    rows.forEach(function(row) {

        if (row.id === "emptyRow") {
            return;
        }

        const text =
            row.innerText.toLowerCase();

        const gender =
            row.cells[4]
            ? row.cells[4].innerText.toLowerCase()
            : "";

        const matchSearch =
            text.includes(searchInput);

        const matchGender =
            genderFilter === ""
            || gender.includes(genderFilter);

        if (matchSearch && matchGender) {

            row.style.display = "";
            found++;

        } else {

            row.style.display = "none";

        }

    });


    const noResult =
        document.getElementById("noResult");

    if (found === 0 && rows.length > 0) {

        noResult.style.display = "block";

    } else {

        noResult.style.display = "none";

    }

}

</script>

</body>
</html>