<?php

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

/*
|--------------------------------------------------------------------------
| EDIT DATA PENDUDUK
|--------------------------------------------------------------------------
| Mengambil data berdasarkan id_penduduk.
|--------------------------------------------------------------------------
*/

// =====================================================
// CEK ID
// =====================================================

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: data_penduduk.php");
    exit;
}

$id_penduduk = (int) $_GET['id'];


// =====================================================
// AMBIL DATA PENDUDUK
// =====================================================

$query = mysqli_query(
    $conn,
    "SELECT *
     FROM penduduk
     WHERE id_penduduk = $id_penduduk
     LIMIT 1"
);

if (!$query || mysqli_num_rows($query) === 0) {
    echo "<script>
            alert('Data penduduk tidak ditemukan.');
            window.location.href='data_penduduk.php';
          </script>";
    exit;
}

$data = mysqli_fetch_assoc($query);


// =====================================================
// PROSES UPDATE
// =====================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $nama_lengkap       = trim($_POST['nama_lengkap'] ?? '');
    $nik                = trim($_POST['nik'] ?? '');
    $jenis_kelamin      = $_POST['jenis_kelamin'] ?? '';
    $desa               = trim($_POST['desa'] ?? '');
    $dusun              = trim($_POST['dusun'] ?? '');
    $rt                 = trim($_POST['rt'] ?? '');
    $rw                 = trim($_POST['rw'] ?? '');
    $status_perkawinan  = $_POST['status_perkawinan'] ?? '';
    $pendidikan         = trim($_POST['pendidikan'] ?? '');
    $agama              = trim($_POST['agama'] ?? '');
    $pekerjaan          = trim($_POST['pekerjaan'] ?? '');
    $tanggal_lahir      = $_POST['tanggal_lahir'] ?? '';

    // =================================================
    // VALIDASI
    // =================================================

    if (
        $nama_lengkap === '' ||
        $nik === '' ||
        $jenis_kelamin === '' ||
        $desa === '' ||
        $dusun === '' ||
        $status_perkawinan === ''
    ) {

        $error = "Mohon lengkapi semua data yang wajib diisi.";

    } else {

        // =============================================
        // CEK NIK DUPLIKAT
        // =============================================

        $nik_safe = mysqli_real_escape_string($conn, $nik);

        $cek_nik = mysqli_query(
            $conn,
            "SELECT id_penduduk
             FROM penduduk
             WHERE nik = '$nik_safe'
             AND id_penduduk != $id_penduduk
             LIMIT 1"
        );

        if (mysqli_num_rows($cek_nik) > 0) {

            $error = "NIK tersebut sudah digunakan oleh penduduk lain.";

        } else {

            // =============================================
            // ESCAPE DATA
            // =============================================

            $nama_lengkap      = mysqli_real_escape_string($conn, $nama_lengkap);
            $jenis_kelamin     = mysqli_real_escape_string($conn, $jenis_kelamin);
            $desa              = mysqli_real_escape_string($conn, $desa);
            $dusun             = mysqli_real_escape_string($conn, $dusun);
            $rt                = mysqli_real_escape_string($conn, $rt);
            $rw                = mysqli_real_escape_string($conn, $rw);
            $status_perkawinan = mysqli_real_escape_string($conn, $status_perkawinan);
            $pendidikan        = mysqli_real_escape_string($conn, $pendidikan);
            $agama             = mysqli_real_escape_string($conn, $agama);
            $pekerjaan         = mysqli_real_escape_string($conn, $pekerjaan);

            if ($tanggal_lahir !== '') {
                $tanggal_lahir = mysqli_real_escape_string($conn, $tanggal_lahir);
                $tanggal_sql = "'$tanggal_lahir'";
            } else {
                $tanggal_sql = "NULL";
            }

            // =============================================
            // FOTO
            // =============================================

            $nama_foto_baru = $data['pas_foto'];

            if (
                isset($_FILES['pas_foto']) &&
                $_FILES['pas_foto']['error'] !== UPLOAD_ERR_NO_FILE
            ) {

                if ($_FILES['pas_foto']['error'] === UPLOAD_ERR_OK) {

                    $tmp_name = $_FILES['pas_foto']['tmp_name'];
                    $nama_asli = $_FILES['pas_foto']['name'];

                    $extension = strtolower(
                        pathinfo($nama_asli, PATHINFO_EXTENSION)
                    );

                    $allowed = ['jpg', 'jpeg', 'png', 'webp'];

                    if (!in_array($extension, $allowed)) {

                        $error = "Format foto harus JPG, JPEG, PNG, atau WEBP.";

                    } elseif ($_FILES['pas_foto']['size'] > 2 * 1024 * 1024) {

                        $error = "Ukuran foto maksimal 2 MB.";

                    } else {

                        $folder_upload = __DIR__ . '/../uploads/';

                        if (!is_dir($folder_upload)) {
                            mkdir($folder_upload, 0777, true);
                        }

                        $nama_foto_baru =
                            'penduduk_' .
                            time() .
                            '_' .
                            uniqid() .
                            '.' .
                            $extension;

                        $tujuan = $folder_upload . $nama_foto_baru;

                        if (!move_uploaded_file($tmp_name, $tujuan)) {

                            $error = "Foto gagal diupload.";

                        } else {

                            // Hapus foto lama jika ada
                            if (!empty($data['pas_foto'])) {

                                $foto_lama =
                                    $folder_upload . $data['pas_foto'];

                                if (file_exists($foto_lama)) {
                                    unlink($foto_lama);
                                }
                            }
                        }
                    }

                } else {

                    $error = "Terjadi kesalahan saat mengupload foto.";
                }
            }


            // =============================================
            // UPDATE DATABASE
            // =============================================

            if (!isset($error)) {

                $query_update = mysqli_query(
                    $conn,
                    "UPDATE penduduk SET

                        pas_foto = '" . mysqli_real_escape_string($conn, $nama_foto_baru) . "',
                        nama_lengkap = '$nama_lengkap',
                        nik = '$nik_safe',
                        jenis_kelamin = '$jenis_kelamin',
                        desa = '$desa',
                        dusun = '$dusun',
                        rt = '$rt',
                        rw = '$rw',
                        status_perkawinan = '$status_perkawinan',
                        pendidikan = '$pendidikan',
                        agama = '$agama',
                        pekerjaan = '$pekerjaan',
                        tanggal_lahir = $tanggal_sql

                     WHERE id_penduduk = $id_penduduk"
                );

                if ($query_update) {

                    echo "<script>
                            alert('Data penduduk berhasil diperbarui.');
                            window.location.href='data_penduduk.php';
                          </script>";
                    exit;

                } else {

                    $error = "Data gagal diperbarui: " . mysqli_error($conn);
                }
            }
        }
    }


    // =================================================
    // UPDATE DATA TAMPILAN FORM
    // =================================================

    $data['nama_lengkap']      = $_POST['nama_lengkap'] ?? $data['nama_lengkap'];
    $data['nik']               = $_POST['nik'] ?? $data['nik'];
    $data['jenis_kelamin']     = $_POST['jenis_kelamin'] ?? $data['jenis_kelamin'];
    $data['desa']              = $_POST['desa'] ?? $data['desa'];
    $data['dusun']             = $_POST['dusun'] ?? $data['dusun'];
    $data['rt']                = $_POST['rt'] ?? $data['rt'];
    $data['rw']                = $_POST['rw'] ?? $data['rw'];
    $data['status_perkawinan'] = $_POST['status_perkawinan'] ?? $data['status_perkawinan'];
    $data['pendidikan']        = $_POST['pendidikan'] ?? $data['pendidikan'];
    $data['agama']             = $_POST['agama'] ?? $data['agama'];
    $data['pekerjaan']         = $_POST['pekerjaan'] ?? $data['pekerjaan'];
    $data['tanggal_lahir']     = $_POST['tanggal_lahir'] ?? $data['tanggal_lahir'];
}

?>

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

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

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

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

</head>

<body>

<div class="page-container">

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

    <div class="page-header">

        <div class="header-left">

            <div class="header-icon">
                ✏️
            </div>

            <div>

                <h1>Edit Data Penduduk</h1>

                <p>
                    Perbarui informasi data penduduk Desa Oelomin.
                </p>

            </div>

        </div>

        <a
            href="data_penduduk.php"
            class="btn-back"
        >
            ← Kembali
        </a>

    </div>


    <!-- =====================================================
         ERROR
    ====================================================== -->

    <?php if (isset($error)): ?>

        <div class="alert-error">
            ⚠️
            <?= htmlspecialchars($error); ?>
        </div>

    <?php endif; ?>


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

    <form
        action=""
        method="POST"
        enctype="multipart/form-data"
        class="form-card"
    >

        <!-- ================================================
             INFORMASI PRIBADI
        ================================================= -->

        <div class="section-title">

            <span>👤</span>

            <div>
                <h2>Informasi Pribadi</h2>
                <p>Data identitas penduduk.</p>
            </div>

        </div>


        <div class="form-grid">

            <!-- Nama -->
            <div class="form-group full">

                <label>
                    Nama Lengkap
                    <span>*</span>
                </label>

                <input
                    type="text"
                    name="nama_lengkap"
                    value="<?= htmlspecialchars($data['nama_lengkap']); ?>"
                    placeholder="Masukkan nama lengkap"
                    required
                >

            </div>


            <!-- NIK -->
            <div class="form-group">

                <label>
                    NIK
                    <span>*</span>
                </label>

                <input
                    type="text"
                    name="nik"
                    value="<?= htmlspecialchars($data['nik']); ?>"
                    placeholder="Masukkan NIK"
                    maxlength="20"
                    required
                >

            </div>


            <!-- Jenis Kelamin -->
            <div class="form-group">

                <label>
                    Jenis Kelamin
                    <span>*</span>
                </label>

                <select
                    name="jenis_kelamin"
                    required
                >

                    <option value="">
                        Pilih jenis kelamin
                    </option>

                    <option
                        value="Laki-laki"
                        <?= $data['jenis_kelamin'] === 'Laki-laki' ? 'selected' : ''; ?>
                    >
                        Laki-laki
                    </option>

                    <option
                        value="Perempuan"
                        <?= $data['jenis_kelamin'] === 'Perempuan' ? 'selected' : ''; ?>
                    >
                        Perempuan
                    </option>

                </select>

            </div>


            <!-- Tanggal Lahir -->
            <div class="form-group">

                <label>
                    Tanggal Lahir
                </label>

                <input
                    type="date"
                    name="tanggal_lahir"
                    value="<?= htmlspecialchars($data['tanggal_lahir'] ?? ''); ?>"
                >

            </div>


            <!-- Status Perkawinan -->
            <div class="form-group">

                <label>
                    Status Perkawinan
                    <span>*</span>
                </label>

                <select
                    name="status_perkawinan"
                    required
                >

                    <option value="">
                        Pilih status perkawinan
                    </option>

                    <option
                        value="Belum Kawin"
                        <?= $data['status_perkawinan'] === 'Belum Kawin' ? 'selected' : ''; ?>
                    >
                        Belum Kawin
                    </option>

                    <option
                        value="Kawin"
                        <?= $data['status_perkawinan'] === 'Kawin' ? 'selected' : ''; ?>
                    >
                        Kawin
                    </option>

                    <option
                        value="Cerai Hidup"
                        <?= $data['status_perkawinan'] === 'Cerai Hidup' ? 'selected' : ''; ?>
                    >
                        Cerai Hidup
                    </option>

                    <option
                        value="Cerai Mati"
                        <?= $data['status_perkawinan'] === 'Cerai Mati' ? 'selected' : ''; ?>
                    >
                        Cerai Mati
                    </option>

                </select>

            </div>

        </div>


        <!-- =================================================
             FOTO
        ================================================== -->

        <div class="photo-section">

            <div class="section-title">

                <span>📷</span>

                <div>

                    <h2>Foto Penduduk</h2>

                    <p>
                        Kosongkan jika tidak ingin mengganti foto.
                    </p>

                </div>

            </div>


            <div class="photo-content">

                <div class="current-photo">

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

                        <img
                            src="../uploads/<?= htmlspecialchars($data['pas_foto']); ?>"
                            alt="Foto Penduduk"
                            id="previewPhoto"
                            onerror="showDefaultPhoto()"
                        >

                        <div
                            class="photo-placeholder"
                            id="defaultPhoto"
                            style="display:none;"
                        >
                            👤
                        </div>

                    <?php else: ?>

                        <div
                            class="photo-placeholder"
                            id="defaultPhoto"
                        >
                            👤
                        </div>

                        <img
                            id="previewPhoto"
                            style="display:none;"
                            alt="Preview Foto"
                        >

                    <?php endif; ?>

                </div>


                <div class="upload-area">

                    <label
                        for="pas_foto"
                        class="upload-label"
                    >
                        📁 Pilih Foto Baru
                    </label>

                    <input
                        type="file"
                        name="pas_foto"
                        id="pas_foto"
                        accept=".jpg,.jpeg,.png,.webp"
                        onchange="previewImage(event)"
                    >

                    <p>
                        Format JPG, JPEG, PNG atau WEBP.
                        Maksimal 2 MB.
                    </p>

                </div>

            </div>

        </div>


        <!-- =================================================
             ALAMAT
        ================================================== -->

        <div class="section-title">

            <span>🏠</span>

            <div>

                <h2>Alamat</h2>

                <p>
                    Informasi tempat tinggal penduduk.
                </p>

            </div>

        </div>


        <div class="form-grid">

            <!-- Desa -->
            <div class="form-group">

                <label>
                    Desa
                    <span>*</span>
                </label>

                <input
                    type="text"
                    name="desa"
                    value="<?= htmlspecialchars($data['desa'] ?? ''); ?>"
                    placeholder="Nama desa"
                    required
                >

            </div>


            <!-- Dusun -->
            <div class="form-group">

                <label>
                    Dusun
                    <span>*</span>
                </label>

                <input
                    type="text"
                    name="dusun"
                    value="<?= htmlspecialchars($data['dusun'] ?? ''); ?>"
                    placeholder="Nama dusun"
                    required
                >

            </div>


            <!-- RT -->
            <div class="form-group small-field">

                <label>
                    RT
                </label>

                <input
                    type="text"
                    name="rt"
                    value="<?= htmlspecialchars($data['rt'] ?? ''); ?>"
                    placeholder="RT"
                    maxlength="5"
                >

            </div>


            <!-- RW -->
            <div class="form-group small-field">

                <label>
                    RW
                </label>

                <input
                    type="text"
                    name="rw"
                    value="<?= htmlspecialchars($data['rw'] ?? ''); ?>"
                    placeholder="RW"
                    maxlength="5"
                >

            </div>

        </div>


        <!-- =================================================
             DATA LAINNYA
        ================================================== -->

        <div class="section-title">

            <span>📋</span>

            <div>

                <h2>Data Lainnya</h2>

                <p>
                    Informasi pendidikan, agama dan pekerjaan.
                </p>

            </div>

        </div>


        <div class="form-grid">

            <!-- Pendidikan -->
            <div class="form-group">

                <label>
                    Pendidikan
                </label>

                <input
                    type="text"
                    name="pendidikan"
                    value="<?= htmlspecialchars($data['pendidikan'] ?? ''); ?>"
                    placeholder="Contoh: SMA"
                >

            </div>


            <!-- Agama -->
            <div class="form-group">

                <label>
                    Agama
                </label>

                <input
                    type="text"
                    name="agama"
                    value="<?= htmlspecialchars($data['agama'] ?? ''); ?>"
                    placeholder="Contoh: Kristen"
                >

            </div>


            <!-- Pekerjaan -->
            <div class="form-group full">

                <label>
                    Pekerjaan
                </label>

                <input
                    type="text"
                    name="pekerjaan"
                    value="<?= htmlspecialchars($data['pekerjaan'] ?? ''); ?>"
                    placeholder="Contoh: Petani"
                >

            </div>

        </div>


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

        <div class="form-actions">

            <a
                href="data_penduduk.php"
                class="btn-cancel"
            >
                Batal
            </a>

            <button
                type="submit"
                class="btn-save"
            >
                💾 Simpan Perubahan
            </button>

        </div>

    </form>

</div>


<script>

function previewImage(event) {

    const input = event.target;
    const preview = document.getElementById('previewPhoto');
    const defaultPhoto = document.getElementById('defaultPhoto');

    if (input.files && input.files[0]) {

        const file = input.files[0];

        if (file.size > 2 * 1024 * 1024) {

            alert('Ukuran foto maksimal 2 MB.');

            input.value = '';

            return;
        }

        const reader = new FileReader();

        reader.onload = function(e) {

            preview.src = e.target.result;
            preview.style.display = 'block';

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

        };

        reader.readAsDataURL(file);
    }
}


function showDefaultPhoto() {

    const preview = document.getElementById('previewPhoto');
    const defaultPhoto = document.getElementById('defaultPhoto');

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

    if (defaultPhoto) {
        defaultPhoto.style.display = 'flex';
    }
}

</script>

</body>

</html>