<?php

include "session.php";
include "../config/koneksi.php";


// ==========================================
// AMBIL ID ADMIN
// ==========================================

$id_admin = isset($_GET['id'])
    ? (int) $_GET['id']
    : 0;

if ($id_admin <= 0) {
    header("Location: data_admin.php");
    exit;
}


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

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

    $nama_lengkap = mysqli_real_escape_string(
        $conn,
        $_POST['nama_lengkap']
    );

    $tempat_lahir = mysqli_real_escape_string(
        $conn,
        $_POST['tempat_lahir']
    );

    $tanggal_lahir = !empty($_POST['tanggal_lahir'])
        ? $_POST['tanggal_lahir']
        : NULL;

    $jenis_kelamin = mysqli_real_escape_string(
        $conn,
        $_POST['jenis_kelamin']
    );

    $alamat = mysqli_real_escape_string(
        $conn,
        $_POST['alamat']
    );

    $no_hp = mysqli_real_escape_string(
        $conn,
        $_POST['no_hp']
    );

    $email = mysqli_real_escape_string(
        $conn,
        $_POST['email']
    );

    $jabatan = mysqli_real_escape_string(
        $conn,
        $_POST['jabatan']
    );


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

    $nama_foto = $_POST['foto_lama'] ?? '';

    if (
        isset($_FILES['foto']) &&
        $_FILES['foto']['error'] === 0
    ) {

        $folder = "../assets/img/admin/";

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


        $nama_asli = $_FILES['foto']['name'];

        $tmp = $_FILES['foto']['tmp_name'];

        $ukuran = $_FILES['foto']['size'];


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


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


        if (
            in_array($ext, $allowed) &&
            $ukuran <= 2 * 1024 * 1024
        ) {

            $nama_foto =
                'admin_' .
                $id_admin .
                '_' .
                time() .
                '.' .
                $ext;


            move_uploaded_file(
                $tmp,
                $folder . $nama_foto
            );
        }
    }


    // ==========================================
    // CEK PROFIL SUDAH ADA ATAU BELUM
    // ==========================================

    $cek = mysqli_query(
        $conn,
        "SELECT id_profil, foto
         FROM profil_admin
         WHERE id_admin = $id_admin
         LIMIT 1"
    );

    $profil = mysqli_fetch_assoc($cek);


    // ==========================================
    // UPDATE
    // ==========================================

    if ($profil) {

        $sql = "UPDATE profil_admin SET

                nama_lengkap = '$nama_lengkap',
                tempat_lahir = '$tempat_lahir',
                tanggal_lahir = " .
                ($tanggal_lahir
                    ? "'$tanggal_lahir'"
                    : "NULL") . ",
                jenis_kelamin = '$jenis_kelamin',
                alamat = '$alamat',
                no_hp = '$no_hp',
                email = '$email',
                jabatan = '$jabatan',
                foto = '$nama_foto'

                WHERE id_admin = $id_admin";


    } else {

        // ======================================
        // INSERT
        // ======================================

        $sql = "INSERT INTO profil_admin (

                    id_admin,
                    nama_lengkap,
                    foto,
                    tempat_lahir,
                    tanggal_lahir,
                    jenis_kelamin,
                    alamat,
                    no_hp,
                    email,
                    jabatan

                ) VALUES (

                    $id_admin,
                    '$nama_lengkap',
                    '$nama_foto',
                    '$tempat_lahir',
                    " .
                    ($tanggal_lahir
                        ? "'$tanggal_lahir'"
                        : "NULL") . ",
                    '$jenis_kelamin',
                    '$alamat',
                    '$no_hp',
                    '$email',
                    '$jabatan'

                )";
    }


    if (mysqli_query($conn, $sql)) {

        header(
            "Location: data_admin.php?success=1"
        );

        exit;

    } else {

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


// ==========================================
// AMBIL DATA LAMA
// ==========================================

$query = mysqli_query(
    $conn,

    "SELECT
        a.id_admin,
        a.nama,
        a.username,
        a.level,

        p.*

     FROM admin a

     LEFT JOIN profil_admin p
        ON a.id_admin = p.id_admin

     WHERE a.id_admin = $id_admin

     LIMIT 1"
);


$data = mysqli_fetch_assoc($query);


if (!$data) {

    echo "Data admin tidak ditemukan.";

    exit;
}

?>

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

<head>

    <meta charset="UTF-8">

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

    <title>Edit Profil Admin</title>

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

    <link rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">

</head>


<body>

<div class="wrapper">


    <!-- SIDEBAR -->

    <div class="sidebar">

        <div class="logo">

            <img
                src="../assets/img/logo-desa.png"
                alt="Logo Desa Oelomin"
            >

            <h2>DESA OELOMIN</h2>

        </div>


        <ul>

            <li>

                <a href="dashboard.php">

                    <i class="fa-solid fa-house"></i>

                    Dashboard

                </a>

            </li>


            <li>

                <a href="profil_admin.php">

                    <i class="fa-solid fa-landmark"></i>

                    Profil Desa

                </a>

            </li>


            <li>

                <a href="produk_admin.php">

                    <i class="fa-solid fa-store"></i>

                    Produk Lokal

                </a>

            </li>


            <li>

                <a href="berita_admin.php">

                    <i class="fa-solid fa-newspaper"></i>

                    Berita

                </a>

            </li>


            <li>

                <a href="kelola_surat.php">

                    <i class="fa-solid fa-envelope"></i>

                    Pelayanan Surat

                </a>

            </li>


            <li>

                <a href="data_demografi.php">

                    <i class="fa-solid fa-users"></i>

                    Manajemen Data

                </a>

            </li>


            <li class="active">

                <a href="data_admin.php">

                    <i class="fa-solid fa-user-shield"></i>

                    Data Admin

                </a>

            </li>


            <li>

                <a href="../logout.php">

                    <i class="fa-solid fa-right-from-bracket"></i>

                    Logout

                </a>

            </li>

        </ul>

    </div>



    <!-- CONTENT -->

    <div class="content">


        <!-- TOPBAR -->

        <div class="topbar">

            <div class="search-box">

                <input
                    type="text"
                    placeholder="Search..."
                >

                <button>

                    <i class="fa-solid fa-magnifying-glass"></i>

                </button>

            </div>


            <div class="admin-info">

                <i class="fa-solid fa-user"></i>

                <?= htmlspecialchars(
                    $_SESSION['nama'] ?? 'Admin'
                ); ?>

            </div>

        </div>



        <!-- FORM -->

        <div class="profil-admin-container">


            <div class="profil-header">

                <div>

                    <h1>Edit Profil Admin</h1>

                    <p>
                        Perbarui biodata pengelola sistem.
                    </p>

                </div>


                <a
                    href="data_admin.php"
                    class="btn-kembali"
                >

                    <i class="fa-solid fa-arrow-left"></i>

                    Kembali

                </a>

            </div>



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

                <div class="info-admin">

                    <i class="fa-solid fa-triangle-exclamation"></i>

                    <p>
                        <?= htmlspecialchars($error); ?>
                    </p>

                </div>

            <?php endif; ?>



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


                <!-- FOTO -->

                <div class="form-foto">

                    <div class="preview-foto">

                        <?php if (
                            !empty($data['foto']) &&
                            file_exists(
                                "../assets/img/admin/" .
                                $data['foto']
                            )
                        ) : ?>

                            <img
                                src="../assets/img/admin/<?= htmlspecialchars($data['foto']); ?>"
                                alt="Foto Admin"
                            >

                        <?php else : ?>

                            <div class="foto-default">

                                <i class="fa-solid fa-user"></i>

                            </div>

                        <?php endif; ?>

                    </div>


                    <div>

                        <label class="label-form">

                            Foto Pengelola

                        </label>

                        <input
                            type="file"
                            name="foto"
                            accept=".jpg,.jpeg,.png,.webp"
                        >

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

                    </div>

                </div>



                <!-- NAMA -->

                <div class="form-grid">

                    <div class="form-group">

                        <label>
                            Nama Lengkap
                        </label>

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

                    </div>


                    <div class="form-group">

                        <label>
                            Jabatan
                        </label>

                        <input
                            type="text"
                            name="jabatan"
                            value="<?= htmlspecialchars(
                                $data['jabatan'] ?? ''
                            ); ?>"
                            placeholder="Administrator Sistem"
                        >

                    </div>


                    <!-- TEMPAT LAHIR -->

                    <div class="form-group">

                        <label>
                            Tempat Lahir
                        </label>

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

                    </div>


                    <!-- TANGGAL LAHIR -->

                    <div class="form-group">

                        <label>
                            Tanggal Lahir
                        </label>

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

                    </div>


                    <!-- JENIS KELAMIN -->

                    <div class="form-group">

                        <label>
                            Jenis Kelamin
                        </label>

                        <select name="jenis_kelamin">

                            <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>


                    <!-- NOMOR HP -->

                    <div class="form-group">

                        <label>
                            Nomor HP
                        </label>

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

                    </div>


                    <!-- EMAIL -->

                    <div class="form-group">

                        <label>
                            Email
                        </label>

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

                    </div>


                    <!-- USERNAME -->

                    <div class="form-group">

                        <label>
                            Username
                        </label>

                        <input
                            type="text"
                            value="<?= htmlspecialchars(
                                $data['username']
                            ); ?>"
                            disabled
                        >

                        <small>
                            Username digunakan untuk login.
                        </small>

                    </div>


                    <!-- LEVEL -->

                    <div class="form-group">

                        <label>
                            Level
                        </label>

                        <input
                            type="text"
                            value="<?= htmlspecialchars(
                                $data['level']
                            ); ?>"
                            disabled
                        >

                    </div>


                    <!-- ALAMAT -->

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

                        <label>
                            Alamat
                        </label>

                        <textarea
                            name="alamat"
                            rows="3"
                        ><?= htmlspecialchars(
                            $data['alamat'] ?? ''
                        ); ?></textarea>

                    </div>

                </div>



                <!-- FOTO LAMA -->

                <input
                    type="hidden"
                    name="foto_lama"
                    value="<?= htmlspecialchars(
                        $data['foto'] ?? ''
                    ); ?>"
                >



                <!-- TOMBOL -->

                <div class="form-actions">

                    <a
                        href="data_admin.php"
                        class="btn-batal"
                    >

                        Batal

                    </a>


                    <button
                        type="submit"
                        name="simpan"
                        class="btn-simpan"
                    >

                        <i class="fa-solid fa-floppy-disk"></i>

                        Simpan Profil

                    </button>

                </div>


            </form>

        </div>

    </div>

</div>

</body>

</html>