<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.php';
require_once __DIR__ . '/../../functions/csrf.php';

$db = getDB();
$uploadDir = __DIR__ . '/../../assets/uploads/profil/';
$uploadUrl = BASE_URL . '/assets/uploads/profil/';

// Ambil data profil
$profil = $db->query("SELECT * FROM profil_posyandu WHERE id = 1")->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Token CSRF tidak valid.');
        header('Location: ' . BASE_URL . '/admin/profil/');
        exit;
    }

    $nama_posyandu = trim($_POST['nama_posyandu'] ?? '');
    $deskripsi = trim($_POST['deskripsi'] ?? '');
    $alamat = trim($_POST['alamat'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $telepon = trim($_POST['telepon'] ?? '');

    // Validasi upload
    $allowed = ['jpg', 'jpeg', 'png', 'webp'];
    $maxSize = 2 * 1024 * 1024; // 2MB

    function uploadGambar($field, $uploadDir, $allowed, $maxSize) {
        if (!isset($_FILES[$field]) || $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE) {
            return null;
        }
        $file = $_FILES[$field];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['error' => 'Gagal upload file.'];
        }
        if ($file['size'] > $maxSize) {
            return ['error' => 'Ukuran file maksimal 2MB.'];
        }
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            return ['error' => 'Format file tidak diizinkan. Gunakan JPG, PNG, atau WEBP.'];
        }
        $filename = $field . '_' . time() . '.' . $ext;
        if (!move_uploaded_file($file['tmp_name'], $uploadDir . $filename)) {
            return ['error' => 'Gagal menyimpan file.'];
        }
        return ['success' => $filename];
    }

    $logoFile = uploadGambar('logo', $uploadDir, $allowed, $maxSize);
    $foto1File = uploadGambar('foto_1', $uploadDir, $allowed, $maxSize);
    $foto2File = uploadGambar('foto_2', $uploadDir, $allowed, $maxSize);
    $foto3File = uploadGambar('foto_3', $uploadDir, $allowed, $maxSize);

    // Cek error
    foreach ([$logoFile, $foto1File, $foto2File, $foto3File] as $f) {
        if (isset($f['error'])) {
            setFlash('error', $f['error']);
            header('Location: ' . BASE_URL . '/admin/profil/');
            exit;
        }
    }

    // Update database
    $sql = "UPDATE profil_posyandu SET nama_posyandu = ?, deskripsi = ?, alamat = ?, email = ?, telepon = ?";
    $params = [$nama_posyandu, $deskripsi, $alamat, $email, $telepon];

    if (isset($logoFile['success'])) {
        $sql .= ", logo = ?";
        $params[] = $logoFile['success'];
    }
    if (isset($foto1File['success'])) {
        $sql .= ", foto_1 = ?";
        $params[] = $foto1File['success'];
    }
    if (isset($foto2File['success'])) {
        $sql .= ", foto_2 = ?";
        $params[] = $foto2File['success'];
    }
    if (isset($foto3File['success'])) {
        $sql .= ", foto_3 = ?";
        $params[] = $foto3File['success'];
    }

    $sql .= " WHERE id = 1";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);

    setFlash('success', 'Profil berhasil diperbarui.');
    header('Location: ' . BASE_URL . '/admin/profil/');
    exit;
}

require_once '../../includes/header_admin.php';
?>

<div class="mb-8">
    <h1 class="text-2xl font-bold text-gray-800">Profil Website</h1>
    <p class="text-gray-500">Kelola identitas posyandu, logo, dan foto carousel.</p>
</div>

<form method="POST" enctype="multipart/form-data" class="w-full space-y-8">
    <?= csrfField() ?>

    <!-- Informasi Dasar -->
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
        <h3 class="text-lg font-bold text-gray-800 mb-4 flex items-center gap-2">
            <i class="fas fa-info-circle text-primary"></i> Informasi Dasar
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Nama Posyandu</label>
                <input type="text" name="nama_posyandu" value="<?= escape($profil['nama_posyandu'] ?? '') ?>" required
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-gray-50 focus:bg-white transition-colors">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Telepon</label>
                <input type="text" name="telepon" value="<?= escape($profil['telepon'] ?? '') ?>"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-gray-50 focus:bg-white transition-colors">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input type="email" name="email" value="<?= escape($profil['email'] ?? '') ?>"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-gray-50 focus:bg-white transition-colors">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Alamat</label>
                <input type="text" name="alamat" value="<?= escape($profil['alamat'] ?? '') ?>"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-gray-50 focus:bg-white transition-colors">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Deskripsi Singkat</label>
                <textarea name="deskripsi" rows="3"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-gray-50 focus:bg-white transition-colors"><?= escape($profil['deskripsi'] ?? '') ?></textarea>
            </div>
        </div>
    </div>

    <!-- Logo -->
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
        <h3 class="text-lg font-bold text-gray-800 mb-4 flex items-center gap-2">
            <i class="fas fa-image text-accent"></i> Logo Posyandu
        </h3>
        <div class="flex items-center gap-6">
            <?php if (!empty($profil['logo'])): ?>
                <div class="w-20 h-20 rounded-xl overflow-hidden border border-gray-200 shadow-sm">
                    <img src="<?= $uploadUrl . escape($profil['logo']) ?>" class="w-full h-full object-cover">
                </div>
            <?php else: ?>
                <div class="w-20 h-20 rounded-xl bg-gray-100 flex items-center justify-center border border-gray-200">
                    <i class="fas fa-image text-gray-300 text-2xl"></i>
                </div>
            <?php endif; ?>
            <div class="flex-1">
                <input type="file" name="logo" accept="image/jpeg,image/png,image/webp"
                    class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-primary-dark transition-colors cursor-pointer">
                <p class="text-xs text-gray-400 mt-2">JPG, PNG, WEBP. Maksimal 2MB.</p>
            </div>
        </div>
    </div>

    <!-- Foto Carousel -->
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
        <h3 class="text-lg font-bold text-gray-800 mb-4 flex items-center gap-2">
            <i class="fas fa-images text-secondary"></i> Foto Carousel (Maks. 3)
        </h3>
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
            <?php for ($i = 1; $i <= 3; $i++): $field = 'foto_' . $i; ?>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Foto <?= $i ?></label>
                    <?php if (!empty($profil[$field])): ?>
                        <div class="w-full h-40 rounded-xl overflow-hidden border border-gray-200 shadow-sm mb-3">
                            <img src="<?= $uploadUrl . escape($profil[$field]) ?>" class="w-full h-full object-cover">
                        </div>
                    <?php else: ?>
                        <div class="w-full h-40 rounded-xl bg-gray-50 flex flex-col items-center justify-center border border-gray-200 border-dashed mb-3">
                            <i class="fas fa-image text-gray-300 text-3xl mb-2"></i>
                            <span class="text-xs text-gray-400">Belum ada foto</span>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="<?= $field ?>" accept="image/jpeg,image/png,image/webp"
                        class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-primary-dark transition-colors cursor-pointer">
                </div>
            <?php endfor; ?>
        </div>
        <p class="text-xs text-gray-400 mt-4">Foto ini akan ditampilkan di carousel bagian atas halaman beranda. Format JPG, PNG, WEBP. Maksimal 2MB per foto.</p>
    </div>

    <!-- Tombol -->
    <div class="flex items-center gap-4">
        <button type="submit" class="px-8 py-3 bg-primary hover:bg-primary-dark text-white font-bold rounded-xl shadow-lg shadow-primary/30 transition-all hover:-translate-y-0.5">
            <i class="fas fa-save mr-2"></i> Simpan
        </button>
        <a href="<?= BASE_URL ?>/" target="_blank" class="px-6 py-3 bg-white border border-gray-200 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition-colors">
            <i class="fas fa-external-link-alt mr-2"></i> Web
        </a>
    </div>
</form>

<?php require_once '../../includes/footer_admin.php'; ?>
