<?php
include 'auth_check.php';
include '../config/koneksi.php';
include '../config/functions.php';

$page_title = "Kelola Profil Desa";

// Inisialisasi variabel untuk menghindari undefined variable error
$message = "";
$message_type = "";
$data = [];

// Ambil data profil
if (isset($koneksi) && $koneksi) {
    $query = mysqli_query($koneksi, "SELECT * FROM profil_desa LIMIT 1");
    if ($query) {
        $data = mysqli_fetch_assoc($query);
    }
}

// Jika data kosong, inisialisasi array default
if (!$data || !is_array($data)) {
    $data = [
        'nama_desa' => '', 
        'deskripsi' => '', 
        'sejarah' => '', 
        'visi' => '', 
        'misi' => '',
        'alamat' => '', 
        'email' => '', 
        'telepon' => '', 
        'logo' => ''
    ];
}

if (isset($_POST['simpan'])) {
    $nama_desa = cleanInput($_POST['nama_desa']);
    $deskripsi = cleanInput($_POST['deskripsi']);
    $sejarah   = cleanInput($_POST['sejarah']);
    $visi      = cleanInput($_POST['visi']);
    $misi      = cleanInput($_POST['misi']);
    $alamat    = cleanInput($_POST['alamat']);
    $email     = cleanInput($_POST['email']);
    $telepon   = cleanInput($_POST['telepon']);
    $id_admin  = $_SESSION['id_admin'];

    // Validasi Input Sederhana
    if (empty($nama_desa) || empty($deskripsi)) {
        $message = "Nama Desa dan Deskripsi wajib diisi.";
        $message_type = "error";
    } else {
        // Upload Logo
        $logo = isset($data['logo']) ? $data['logo'] : '';
        if (isset($_FILES['logo']['name']) && $_FILES['logo']['name']) {
            $upload_result = uploadImage($_FILES['logo'], "../assets/img/");
            if ($upload_result !== "no_file") {
                if (strpos($upload_result, ' ') !== false) {
                     $message = $upload_result;
                     $message_type = "error";
                } else {
                     $logo = $upload_result;
                     // Hapus logo lama
                     if (!empty($data['logo']) && file_exists("../assets/img/" . $data['logo'])) {
                         unlink("../assets/img/" . $data['logo']);
                     }
                }
            }
        }
    }

    if ($message == "") {
        // Cek insert atau update
        $cek_ada = 0;
        $q_cek = mysqli_query($koneksi, "SELECT * FROM profil_desa");
        if ($q_cek) {
            $cek_ada = mysqli_num_rows($q_cek);
        }

        if ($cek_ada > 0) {
            $query_update = "UPDATE profil_desa SET 
                nama_desa = '$nama_desa',
                deskripsi = '$deskripsi',
                sejarah = '$sejarah',
                visi = '$visi',
                misi = '$misi',
                alamat = '$alamat',
                email = '$email',
                telepon = '$telepon',
                logo = '$logo',
                id_admin = '$id_admin'
            ";
            if (mysqli_query($koneksi, $query_update)) {
                $message = "Profil desa berhasil diperbarui!";
                $message_type = "success";
                // Refresh data
                $data = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM profil_desa LIMIT 1"));
            } else {
                $message = "Gagal mengupdate profil: " . mysqli_error($koneksi);
                $message_type = "error";
            }
        } else {
            $query_insert = "INSERT INTO profil_desa (nama_desa, deskripsi, sejarah, visi, misi, alamat, email, telepon, logo, id_admin) VALUES ('$nama_desa', '$deskripsi', '$sejarah', '$visi', '$misi', '$alamat', '$email', '$telepon', '$logo', '$id_admin')";
            if (mysqli_query($koneksi, $query_insert)) {
                $message = "Profil desa berhasil dibuat!";
                $message_type = "success";
                $data = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM profil_desa LIMIT 1"));
            } else {
                $message = "Gagal membuat profil: " . mysqli_error($koneksi);
                $message_type = "error";
            }
        }
    }
}

// 1. Upload Slider - REMOVED
// 2. Hapus Slider - REMOVED
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title; ?> - Admin Dashboard</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .admin-container { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background-color: var(--primary-color); color: var(--white); display: flex; flex-direction: column; }
        .sidebar-header { padding: 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-menu { list-style: none; padding: 20px 0; flex: 1; }
        .sidebar-menu li a { display: block; padding: 15px 20px; color: #ecf0f1; text-decoration: none; transition: background 0.3s; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background-color: var(--accent-color); }
        .sidebar-menu li a i { width: 25px; }
        .main-content { flex: 1; background-color: #f4f6f9; padding: 30px; }
        
        .card-form { background: var(--white); padding: 30px; border-radius: 10px; box-shadow: var(--shadow); }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: bold; color: var(--primary-color); }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 1rem; }
        textarea.form-control { resize: vertical; min-height: 100px; }
        .btn-save { background-color: var(--accent-color); color: white; padding: 10px 25px; border: none; border-radius: 5px; cursor: pointer; }
        .alert { padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .alert-success { background-color: #d4edda; color: #155724; }
        .alert-error { background-color: #f8d7da; color: #721c24; }
        .preview-logo { max-width: 150px; margin-top: 10px; border-radius: 5px; border: 1px solid #ddd; padding: 5px; }
    </style>
</head>

<body>

<div class="admin-container">
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>Admin Panel</h3>
        </div>
        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
            <li><a href="kelola_profil.php" class="active"><i class="fas fa-info-circle"></i> Profil Desa</a></li>
            <li><a href="kelola_perangkat.php"><i class="fas fa-users-cog"></i> Perangkat Desa</a></li>
            <li><a href="kelola_potensi.php"><i class="fas fa-landmark"></i> Potensi Desa</a></li>
            <li><a href="kelola_berita.php"><i class="fas fa-newspaper"></i> Berita</a></li>
            <li><a href="kelola_galeri.php"><i class="fas fa-images"></i> Galeri</a></li>
            <li><a href="kelola_slider.php"><i class="fas fa-desktop"></i> Kelola Slider</a></li>
            <li><a href="pengaturan_akun.php"><i class="fas fa-user-cog"></i> Pengaturan Akun</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="card-form">
            <h2 style="margin-bottom: 20px;">Kelola Profil Desa</h2>

            <?php if (!empty($message)): ?>
                <div class="alert <?= ($message_type == 'success') ? 'alert-success' : 'alert-error'; ?>">
                    <?= $message; ?>
                </div>
            <?php endif; ?>

            <form action="" method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Nama Desa</label>
                    <input type="text" name="nama_desa" class="form-control" value="<?= htmlspecialchars((string)$data['nama_desa']); ?>" required>
                </div>

                <div class="form-group">
                    <label>Deskripsi Singkat (Wilayah)</label>
                    <textarea name="deskripsi" class="form-control" rows="3"><?= htmlspecialchars((string)$data['deskripsi']); ?></textarea>
                </div>

                <div class="form-group">
                    <label>Sejarah Desa</label>
                    <textarea name="sejarah" class="form-control" rows="5"><?= htmlspecialchars((string)$data['sejarah']); ?></textarea>
                </div>

                <div class="form-group" style="display: flex; gap: 20px;">
                    <div style="flex: 1;">
                        <label>Visi</label>
                        <textarea name="visi" class="form-control" rows="4"><?= htmlspecialchars((string)$data['visi']); ?></textarea>
                    </div>
                    <div style="flex: 1;">
                        <label>Misi</label>
                        <textarea name="misi" class="form-control" rows="4"><?= htmlspecialchars((string)$data['misi']); ?></textarea>
                    </div>
                </div>

                <div class="form-group">
                    <label>Alamat Kantor</label>
                    <textarea name="alamat" class="form-control" rows="2"><?= htmlspecialchars((string)$data['alamat']); ?></textarea>
                </div>

                <div class="form-group" style="display: flex; gap: 20px;">
                    <div style="flex: 1;">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control" value="<?= htmlspecialchars((string)$data['email']); ?>">
                    </div>
                    <div style="flex: 1;">
                        <label>Telepon / WA</label>
                        <input type="text" name="telepon" class="form-control" value="<?= htmlspecialchars((string)$data['telepon']); ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label>Logo Desa</label>
                    <input type="file" name="logo" class="form-control">
                    <?php if (!empty($data['logo'])): ?>
                        <img src="../assets/img/<?= $data['logo']; ?>" class="preview-logo" alt="Logo Saat Ini">
                    <?php endif; ?>
                </div>

                <button type="submit" name="simpan" class="btn-save"><i class="fas fa-save"></i> Simpan Perubahan</button>
            </form>
        </div>
    </div>
</div>

</body>
</html>
