<?php
session_start();

require_once "../config/koneksi.php";

/* =====================================================
   AMBIL DATA PROFIL DESA
   Tabel : profil_desa
   ===================================================== */

$query_profil = mysqli_query(
    $conn,
    "SELECT * FROM profil_desa LIMIT 1"
);

$profil = $query_profil
    ? mysqli_fetch_assoc($query_profil)
    : null;

$sejarah       = $profil['sejarah'] ?? '';
$visi          = $profil['visi'] ?? '';
$misi          = $profil['misi'] ?? '';
$struktur      = $profil['struktur'] ?? '';
$data_penduduk = $profil['data_penduduk'] ?? '';

/* =====================================================
   PROSES SIMPAN
   ===================================================== */

if (isset($_POST['simpan'])) {

    $sejarah = trim($_POST['sejarah'] ?? '');
    $visi    = trim($_POST['visi'] ?? '');
    $misi    = trim($_POST['misi'] ?? '');

    /*
     * Data penduduk sekarang merupakan
     * kolom TEXT di tabel profil_desa
     */
    $data_penduduk = trim($_POST['data_penduduk'] ?? '');

    /* =================================================
       UPLOAD STRUKTUR PEMERINTAHAN
       ================================================= */

    $nama_file = $struktur;

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

        if ($_FILES['struktur']['error'] !== UPLOAD_ERR_OK) {
            echo "<script>
                    alert('Gagal mengunggah file struktur pemerintahan.');
                    history.back();
                  </script>";
            exit;
        }

        $file = $_FILES['struktur'];

        $nama_asli = $file['name'];
        $tmp       = $file['tmp_name'];
        $ukuran    = $file['size'];

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

        $format_diizinkan = ['jpg', 'jpeg', 'png'];

        if ($ukuran > 2 * 1024 * 1024) {
            echo "<script>
                    alert('Ukuran file maksimal 2 MB.');
                    history.back();
                  </script>";
            exit;
        }

        if (!in_array($ext, $format_diizinkan, true)) {
            echo "<script>
                    alert('Format file harus JPG, JPEG, atau PNG.');
                    history.back();
                  </script>";
            exit;
        }

        $folder_upload = "../assets/uploads/struktur/";

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

        $nama_file =
            'struktur_' .
            time() .
            '_' .
            uniqid() .
            '.' .
            $ext;

        if (!move_uploaded_file(
            $tmp,
            $folder_upload . $nama_file
        )) {

            echo "<script>
                    alert('File struktur gagal disimpan.');
                    history.back();
                  </script>";
            exit;
        }
    }

    /* =================================================
       CEK DATA PROFIL DESA
       ================================================= */

    $cek_profil = mysqli_query(
        $conn,
        "SELECT id_profil FROM profil_desa LIMIT 1"
    );

    $profil_tersedia =
        $cek_profil &&
        mysqli_fetch_assoc($cek_profil);

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

    if ($profil_tersedia) {

        $stmt = mysqli_prepare(
            $conn,
            "UPDATE profil_desa
             SET sejarah = ?,
                 visi = ?,
                 misi = ?,
                 struktur = ?,
                 data_penduduk = ?
             LIMIT 1"
        );

        if (!$stmt) {
            die(
                "Prepare gagal: " .
                mysqli_error($conn)
            );
        }

        mysqli_stmt_bind_param(
            $stmt,
            "sssss",
            $sejarah,
            $visi,
            $misi,
            $nama_file,
            $data_penduduk
        );

        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

    } else {

        /* =================================================
           INSERT
           ================================================= */

        $stmt = mysqli_prepare(
            $conn,
            "INSERT INTO profil_desa
             (
                sejarah,
                visi,
                misi,
                struktur,
                data_penduduk
             )
             VALUES (?, ?, ?, ?, ?)"
        );

        if (!$stmt) {
            die(
                "Prepare gagal: " .
                mysqli_error($conn)
            );
        }

        mysqli_stmt_bind_param(
            $stmt,
            "sssss",
            $sejarah,
            $visi,
            $misi,
            $nama_file,
            $data_penduduk
        );

        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
    }

    echo "
    <script>
        alert('Profil Desa berhasil diperbarui');
        window.location.href='profil_admin.php';
    </script>
    ";

    exit;
}
?>
<!DOCTYPE html>
<html lang="id">

<head>

    <meta charset="UTF-8">

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

    <title>Kelola Profil Desa</title>

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

</head>


<body>

<div class="page-container">


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

    <header class="page-header">

        <a
            href="dashboard.php"
            class="btn-dashboard"
        >
            ← Dashboard
        </a>

        <h1>
            🏠 Kelola Profil Desa
        </h1>

    </header>



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

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


        <!-- =================================================
             SEJARAH
             ================================================= -->

        <section class="profile-section">

            <h2>
                📜 Sejarah Desa
            </h2>

            <p class="section-description">
                Masukkan sejarah singkat Desa Oelomin.
            </p>

            <textarea
                name="sejarah"
                id="sejarah"
                class="form-textarea sejarah-textarea"
                placeholder="Masukkan sejarah singkat Desa Oelomin..."
            ><?= htmlspecialchars($sejarah) ?></textarea>

        </section>



        <!-- =================================================
             VISI
             ================================================= -->

        <section class="profile-section">

            <h2>
                🎯 Visi Desa
            </h2>

            <p class="section-description">
                Tuliskan visi pembangunan Desa Oelomin.
            </p>

            <textarea
                name="visi"
                id="visi"
                class="form-textarea visi-textarea"
                placeholder="Masukkan visi desa..."
            ><?= htmlspecialchars($visi) ?></textarea>

        </section>



        <!-- =================================================
             MISI
             ================================================= -->

        <section class="profile-section">

            <h2>
                🚀 Misi Desa
            </h2>

            <p class="section-description">
                Masukkan poin-poin misi desa.
            </p>

            <textarea
                name="misi"
                id="misi"
                class="form-textarea misi-textarea"
                placeholder="Masukkan misi desa..."
            ><?= htmlspecialchars($misi) ?></textarea>


            <div class="format-tools">

                <button
                    type="button"
                    class="btn-format"
                    onclick="nomorOtomatis()"
                >
                    🔢 Nomor Otomatis
                </button>

            </div>

        </section>



        <!-- =================================================
             STRUKTUR PEMERINTAHAN
             ================================================= -->

        <section class="profile-section">

            <h2>
                👥 Struktur Pemerintahan
            </h2>

            <p class="section-description">
                Upload gambar struktur organisasi Pemerintah Desa Oelomin.
            </p>

            <div class="upload-box">

                <input
                    type="file"
                    name="struktur"
                    id="struktur"
                    accept=".jpg,.jpeg,.png"
                >

            </div>


            <div class="upload-info">

                <div>
                    ✓ Format : JPG, JPEG, PNG
                </div>

                <div>
                    ✓ Maksimal ukuran file 2 MB
                </div>

            </div>


            <!-- PREVIEW -->

            <div
                id="strukturPreview"
                class="image-preview"
            >

                <?php if (!empty($struktur)): ?>

                    <img
                        src="../assets/uploads/struktur/<?= htmlspecialchars($struktur) ?>"
                        alt="Struktur Pemerintahan Desa"
                    >

                <?php else: ?>

                    <div class="preview-placeholder">
                        📷 Belum ada gambar struktur pemerintahan
                    </div>

                <?php endif; ?>

            </div>

        </section>

        <!-- =================================================
             SIMPAN
             ================================================= -->

        <div class="form-submit">

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

        </div>


    </form>


</div>

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

<script>


/* =====================================================
   NOMOR OTOMATIS MISI
   ===================================================== */

const textareaMisi =
    document.getElementById('misi');


function nomorOtomatis() {

    if (!textareaMisi) {
        return;
    }

    let lines =
        textareaMisi.value.split('\n');

    let nomor = 0;


    lines =
        lines.map(function(line) {

            /* Hapus nomor atau bullet lama */

            line =
                line.replace(
                    /^\s*(?:\d+[\.\)]|[-•*])\s*/,
                    ''
                );


            /* Baris kosong */

            if (line.trim() === '') {

                return '';

            }


            nomor++;

            return nomor + '. ' + line.trim();

        });


    textareaMisi.value =
        lines.join('\n');

}



/* =====================================================
   PREVIEW STRUKTUR
   ===================================================== */

const inputStruktur =
    document.getElementById('struktur');

const previewStruktur =
    document.getElementById('strukturPreview');


if (inputStruktur) {

    inputStruktur.addEventListener(
        'change',
        function() {

            const file =
                this.files[0];


            if (!file) {
                return;
            }


            /* CEK UKURAN */

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

                alert(
                    'Ukuran file maksimal 2 MB'
                );

                this.value = '';

                return;
            }


            /* CEK FORMAT */

            const format =
                file.name
                    .split('.')
                    .pop()
                    .toLowerCase();


            if (
                ![
                    'jpg',
                    'jpeg',
                    'png'
                ].includes(format)
            ) {

                alert(
                    'Format file harus JPG, JPEG, atau PNG'
                );

                this.value = '';

                return;
            }


            /* PREVIEW */

            const reader =
                new FileReader();


            reader.onload =
                function(e) {

                    previewStruktur.innerHTML = `

                        <img
                            src="${e.target.result}"
                            alt="Preview Struktur Pemerintahan"
                        >

                    `;

                };


            reader.readAsDataURL(file);

        }
    );

}

</script>


</body>

</html>