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

$page_title = "Tambah Perangkat Desa";
$id = "";
$nama = "";
$nip = "";
$jabatan = "";
$urutan = 1;
$foto = "";
$is_edit = false;

// Cek apakah mode edit
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $query = mysqli_query($koneksi, "SELECT * FROM perangkat_desa WHERE id_perangkat = '$id'");
    if (mysqli_num_rows($query) > 0) {
        $data = mysqli_fetch_assoc($query);
        $nama = $data['nama'];
        $nip = $data['nip'];
        $jabatan = $data['jabatan'];
        $urutan = $data['urutan'];
        $foto = $data['foto'];
        $page_title = "Edit Perangkat Desa";
        $is_edit = true;
    } else {
        echo "<script>alert('Data tidak ditemukan!'); window.location='kelola_perangkat.php';</script>";
        exit;
    }
}

// Proses Submit
if (isset($_POST['submit'])) {
    $nama = cleanInput($_POST['nama']);
    $nip = cleanInput($_POST['nip']);
    $jabatan = cleanInput($_POST['jabatan']);
    $urutan = (int)$_POST['urutan'];
    
    // Validasi sederhana
    if (empty($nama) || empty($jabatan)) {
        $error = "Nama dan Jabatan wajib diisi!";
    } else {
        // Upload Foto
        $foto_baru = "";
        
        if ($_FILES['foto']['error'] === 0) {
            $upload = uploadImage($_FILES['foto'], "../uploads/perangkat/");
            
            // Cek apakah upload sukses (nama file tidak mengandung spasi dan bukan pesan error)
            // Asumsi pesan error mengandung spasi atau "no_file"
            // Namun karena uploadImage function kita lihat sebelumnya:
            // Sukses: return filename (uniqid + ext) -> tidak ada spasi
            // Gagal: return "File bukan gambar.", "Ukuran...", dll -> ada spasi
            
            if (strpos($upload, ' ') !== false) {
                 $error = "Gagal upload: " . $upload;
            } else {
                $foto_baru = $upload;
            }
        } elseif ($_FILES['foto']['error'] === 4) {
            // Tidak ada file yg diupload
            if (!$is_edit) {
                 $error = "Foto wajib diupload untuk data baru!";
            }
        } else {
             $error = "Terjadi error saat upload foto.";
        }
        
        if (!isset($error)) {
            if ($is_edit) {
                // Update
                if (!empty($foto_baru)) {
                    // Hapus foto lama jika bukan default
                    if ($foto != 'default.jpg' && file_exists("../uploads/perangkat/" . $foto)) {
                        unlink("../uploads/perangkat/" . $foto);
                    }
                    $q_update = "UPDATE perangkat_desa SET nama='$nama', nip='$nip', jabatan='$jabatan', urutan='$urutan', foto='$foto_baru' WHERE id_perangkat='$id'";
                } else {
                    $q_update = "UPDATE perangkat_desa SET nama='$nama', nip='$nip', jabatan='$jabatan', urutan='$urutan' WHERE id_perangkat='$id'";
                }
                
                if (mysqli_query($koneksi, $q_update)) {
                    echo "<script>alert('Data berhasil diperbarui!'); window.location='kelola_perangkat.php';</script>";
                    exit;
                } else {
                    $error = "Gagal update data: " . mysqli_error($koneksi);
                }
            } else {
                // Insert
                // Jika foto tidak diupload (sudah dicek error di atas, tapi double check)
                if (empty($foto_baru)) {
                     // Harusnya sudah kena validasi di atas "Foto wajib diupload..."
                     // Tapi jika logic lolos, set default atau error
                     $error = "Silahkan upload foto.";
                } else {
                    $id_admin = $_SESSION['id_admin']; // Ambil ID admin dari session
                    $q_insert = "INSERT INTO perangkat_desa (nama, nip, jabatan, urutan, foto, id_admin) VALUES ('$nama', '$nip', '$jabatan', '$urutan', '$foto_baru', '$id_admin')";
                    if (mysqli_query($koneksi, $q_insert)) {
                        echo "<script>alert('Data berhasil ditambahkan!'); window.location='kelola_perangkat.php';</script>";
                        exit;
                    } else {
                         $error = "Gagal tambah data: " . mysqli_error($koneksi);
                    }
                }
            }
        }
    }
}
?>

<!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); max-width: 800px; margin: 0 auto; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #333; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-size: 1rem; }
        .btn-submit { background-color: var(--accent-color); color: white; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1rem; }
        .btn-submit:hover { background-color: #2980b9; }
        .btn-back { background-color: #95a5a6; color: white; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; font-size: 1rem; margin-right: 10px; }
        .alert-error { background-color: #e74c3c; color: white; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .preview-img { max-width: 200px; 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"><i class="fas fa-info-circle"></i> Profil Desa</a></li>
            <li><a href="kelola_perangkat.php" class="active"><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><?= $page_title; ?></h2>
            <hr style="margin-bottom: 20px; border: 0; border-top: 1px solid #eee;">
            
            <?php if (isset($error)): ?>
                <div class="alert-error"><?= $error; ?></div>
            <?php endif; ?>
            
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="nama">Nama Lengkap</label>
                    <input type="text" name="nama" id="nama" class="form-control" value="<?= htmlspecialchars($nama); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="nip">NIP (Opsional)</label>
                    <input type="text" name="nip" id="nip" class="form-control" value="<?= htmlspecialchars($nip); ?>">
                </div>
                
                <div class="form-group">
                    <label for="jabatan">Jabatan</label>
                    <input type="text" name="jabatan" id="jabatan" class="form-control" value="<?= htmlspecialchars($jabatan); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="urutan">Urutan Tampil (Angka)</label>
                    <input type="number" name="urutan" id="urutan" class="form-control" value="<?= $urutan; ?>" required min="1">
                    <small style="color: #777;">Semakin kecil angkanya, semakin di atas posisinya.</small>
                </div>
                
                <div class="form-group">
                    <label for="foto">Foto</label>
                    <input type="file" name="foto" id="foto" class="form-control" accept="image/*" <?= $is_edit ? '' : 'required'; ?>>
                    <?php if ($is_edit && !empty($foto) && file_exists("../uploads/perangkat/" . $foto)): ?>
                        <div style="margin-top: 10px;">
                            <p>Foto Saat Ini:</p>
                            <img src="../uploads/perangkat/<?= $foto; ?>" class="preview-img">
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="form-group" style="margin-top: 30px;">
                    <a href="kelola_perangkat.php" class="btn-back"><i class="fas fa-arrow-left"></i> Kembali</a>
                    <button type="submit" name="submit" class="btn-submit"><i class="fas fa-save"></i> Simpan Data</button>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>
