<?php

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

$error = '';
$success = '';

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

    // =====================================================
    // AMBIL DATA FORM
    // =====================================================

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

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

    if ($nama_lengkap === '') {
        $error = 'Nama lengkap wajib diisi.';
    } elseif ($nik === '') {
        $error = 'NIK wajib diisi.';
    } elseif (!preg_match('/^[0-9]+$/', $nik)) {
        $error = 'NIK hanya boleh berisi angka.';
    } elseif ($jenis_kelamin === '') {
        $error = 'Jenis kelamin wajib dipilih.';
    } elseif ($desa === '') {
        $error = 'Desa wajib diisi.';
    } elseif ($status_perkawinan === '') {
        $error = 'Status perkawinan wajib dipilih.';
    } else {

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

        $cek = mysqli_prepare(
            $conn,
            "SELECT id_penduduk FROM penduduk WHERE nik = ? LIMIT 1"
        );

        mysqli_stmt_bind_param($cek, "s", $nik);
        mysqli_stmt_execute($cek);
        mysqli_stmt_store_result($cek);

        if (mysqli_stmt_num_rows($cek) > 0) {

            $error = 'NIK tersebut sudah terdaftar.';

        } else {

            // =================================================
            // UPLOAD FOTO
            // =================================================

            $nama_foto = null;

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

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

                    $error = 'Foto gagal diunggah.';

                } else {

                    $file_tmp  = $_FILES['pas_foto']['tmp_name'];
                    $file_name = $_FILES['pas_foto']['name'];
                    $file_size = $_FILES['pas_foto']['size'];

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

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

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

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

                    } elseif ($file_size > 2 * 1024 * 1024) {

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

                    } else {

                        // Folder uploads berada di portal-desa/uploads
                        $upload_dir = __DIR__ . '/../uploads/';

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

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

                        $tujuan = $upload_dir . $nama_foto;

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

                            $error = 'Foto gagal disimpan ke folder uploads.';
                            $nama_foto = null;
                        }
                    }
                }
            }

            // =================================================
            // SIMPAN DATA
            // =================================================

            if ($error === '') {

                $sql = "INSERT INTO penduduk (
                            pas_foto,
                            nama_lengkap,
                            nik,
                            jenis_kelamin,
                            desa,
                            dusun,
                            rt,
                            rw,
                            status_perkawinan,
                            pendidikan,
                            agama,
                            pekerjaan,
                            tanggal_lahir
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

                $stmt = mysqli_prepare($conn, $sql);

                mysqli_stmt_bind_param(
                    $stmt,
                    "sssssssssssss",
                    $nama_foto,
                    $nama_lengkap,
                    $nik,
                    $jenis_kelamin,
                    $desa,
                    $dusun,
                    $rt,
                    $rw,
                    $status_perkawinan,
                    $pendidikan,
                    $agama,
                    $pekerjaan,
                    $tanggal_lahir
                );

                if (mysqli_stmt_execute($stmt)) {

                    header("Location: data_penduduk.php?status=success");
                    exit;

                } else {

                    // Hapus foto jika database gagal menyimpan
                    if (
                        !empty($nama_foto) &&
                        file_exists(__DIR__ . '/../uploads/' . $nama_foto)
                    ) {
                        unlink(__DIR__ . '/../uploads/' . $nama_foto);
                    }

                    $error = 'Data penduduk gagal disimpan: ' . mysqli_error($conn);
                }

                mysqli_stmt_close($stmt);
            }
        }

        mysqli_stmt_close($cek);
    }
}

?>

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

<head>

    <meta charset="UTF-8">

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

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

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

</head>

<body>

<div class="page-container">

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

    <div class="page-header">

        <div class="header-left">

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

            <div>

                <h1>Tambah Data Penduduk</h1>

                <p>
                    Tambahkan data penduduk Desa Oelomin
                    ke dalam sistem.
                </p>

            </div>

        </div>

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

    </div>


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

    <?php if ($error !== ''): ?>

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

    <?php endif; ?>


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

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

        <div class="form-title">

            <div class="title-icon">
                📝
            </div>

            <div>

                <h2>Form Data Penduduk</h2>

                <p>
                    Isi data penduduk dengan lengkap dan benar.
                </p>

            </div>

        </div>


        <!-- =================================================
             DATA IDENTITAS
        ================================================== -->

        <div class="section-title">

            <span>👤</span>

            <div>
                <h3>Data Identitas</h3>
                <p>Informasi dasar penduduk</p>
            </div>

        </div>


        <div class="form-grid">

            <!-- Foto -->

            <div class="form-group full-width">

                <label for="pas_foto">
                    Pas Foto
                </label>

                <div class="photo-upload">

                    <div class="photo-preview" id="photoPreview">
                        👤
                    </div>

                    <div class="photo-info">

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

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

                    </div>

                </div>

            </div>


            <!-- Nama -->

            <div class="form-group">

                <label for="nama_lengkap">
                    Nama Lengkap
                    <span>*</span>
                </label>

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

            </div>


            <!-- NIK -->

            <div class="form-group">

                <label for="nik">
                    NIK
                    <span>*</span>
                </label>

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

                <small>
                    Masukkan NIK sesuai dokumen kependudukan.
                </small>

            </div>


            <!-- Jenis Kelamin -->

            <div class="form-group">

                <label for="jenis_kelamin">
                    Jenis Kelamin
                    <span>*</span>
                </label>

                <select
                    id="jenis_kelamin"
                    name="jenis_kelamin"
                    required
                >

                    <option value="">
                        -- Pilih Jenis Kelamin --
                    </option>

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

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

                </select>

            </div>


            <!-- Tanggal Lahir -->

            <div class="form-group">

                <label for="tanggal_lahir">
                    Tanggal Lahir
                </label>

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

            </div>

        </div>


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

        <div class="section-title">

            <span>🏠</span>

            <div>
                <h3>Data Wilayah</h3>
                <p>Informasi tempat tinggal penduduk</p>
            </div>

        </div>


        <div class="form-grid">

            <!-- Desa -->

            <div class="form-group">

                <label for="desa">
                    Desa
                    <span>*</span>
                </label>

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

            </div>


            <!-- Dusun -->

            <div class="form-group">

                <label for="dusun">
                    Dusun
                </label>

                <input
                    type="text"
                    id="dusun"
                    name="dusun"
                    value="<?= htmlspecialchars($_POST['dusun'] ?? ''); ?>"
                    placeholder="Contoh: Dusun I"
                >

            </div>


            <!-- RT -->

            <div class="form-group">

                <label for="rt">
                    RT
                </label>

                <input
                    type="text"
                    id="rt"
                    name="rt"
                    value="<?= htmlspecialchars($_POST['rt'] ?? ''); ?>"
                    placeholder="Contoh: 001"
                    maxlength="5"
                >

            </div>


            <!-- RW -->

            <div class="form-group">

                <label for="rw">
                    RW
                </label>

                <input
                    type="text"
                    id="rw"
                    name="rw"
                    value="<?= htmlspecialchars($_POST['rw'] ?? ''); ?>"
                    placeholder="Contoh: 001"
                    maxlength="5"
                >

            </div>

        </div>


        <!-- =================================================
             DATA KEPENDUDUKAN
        ================================================== -->

        <div class="section-title">

            <span>📋</span>

            <div>
                <h3>Data Kependudukan</h3>
                <p>Informasi tambahan penduduk</p>
            </div>

        </div>


        <div class="form-grid">

            <!-- Status Perkawinan -->

            <div class="form-group">

                <label for="status_perkawinan">
                    Status Perkawinan
                    <span>*</span>
                </label>

                <select
                    id="status_perkawinan"
                    name="status_perkawinan"
                    required
                >

                    <option value="">
                        -- Pilih Status --
                    </option>

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

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

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

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

                </select>

            </div>


            <!-- Pendidikan -->

            <div class="form-group">

                <label for="pendidikan">
                    Pendidikan
                </label>

                <select
                    id="pendidikan"
                    name="pendidikan"
                >

                    <option value="">
                        -- Pilih Pendidikan --
                    </option>

                    <?php
                    $pendidikan_list = [
                        'Tidak/Belum Sekolah',
                        'SD',
                        'SMP',
                        'SMA',
                        'Diploma',
                        'S1',
                        'S2',
                        'S3'
                    ];
                    ?>

                    <?php foreach ($pendidikan_list as $item): ?>

                        <option
                            value="<?= htmlspecialchars($item); ?>"
                            <?= (($_POST['pendidikan'] ?? '') === $item) ? 'selected' : ''; ?>
                        >
                            <?= htmlspecialchars($item); ?>
                        </option>

                    <?php endforeach; ?>

                </select>

            </div>


            <!-- Agama -->

            <div class="form-group">

                <label for="agama">
                    Agama
                </label>

                <select
                    id="agama"
                    name="agama"
                >

                    <option value="">
                        -- Pilih Agama --
                    </option>

                    <?php
                    $agama_list = [
                        'Kristen',
                        'Katolik',
                        'Islam',
                        'Hindu',
                        'Buddha',
                        'Konghucu'
                    ];
                    ?>

                    <?php foreach ($agama_list as $item): ?>

                        <option
                            value="<?= htmlspecialchars($item); ?>"
                            <?= (($_POST['agama'] ?? '') === $item) ? 'selected' : ''; ?>
                        >
                            <?= htmlspecialchars($item); ?>
                        </option>

                    <?php endforeach; ?>

                </select>

            </div>


            <!-- Pekerjaan -->

            <div class="form-group">

                <label for="pekerjaan">
                    Pekerjaan
                </label>

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

            </div>

        </div>


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

        <div class="form-footer">

            <p>
                <span>*</span>
                Wajib diisi
            </p>

            <div class="footer-buttons">

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

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

            </div>

        </div>

    </form>

</div>


<script>

function previewPhoto(input) {

    const preview =
        document.getElementById('photoPreview');

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

            preview.innerHTML = '👤';

            return;
        }

        const reader = new FileReader();

        reader.onload = function(e) {

            preview.innerHTML =
                '<img src="' +
                e.target.result +
                '" alt="Preview Foto">';

        };

        reader.readAsDataURL(file);

    } else {

        preview.innerHTML = '👤';

    }

}

</script>

</body>
</html>