<?php
// ============================================================
// FILE: admin/pengaturan.php
// Halaman untuk mengelola konten dinamis toko
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo = db();
$success = '';
$error = '';

// Ambil data pengaturan saat ini
$setting = getPengaturanToko();

// Proses form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ========== HERO SECTION ==========
    if (isset($_POST['save_hero'])) {
        updatePengaturanText('hero_title_line1', $_POST['hero_title_line1'] ?? '');
        updatePengaturanText('hero_title_line2', $_POST['hero_title_line2'] ?? '');
        updatePengaturanText('hero_title_line3', $_POST['hero_title_line3'] ?? '');
        updatePengaturanText('hero_subtitle', $_POST['hero_subtitle'] ?? '');
        
        if (isset($_FILES['hero_bg']) && $_FILES['hero_bg']['error'] === UPLOAD_ERR_OK) {
            $bgFile = uploadHeroBackground($_FILES['hero_bg']);
            if ($bgFile) {
                updatePengaturanText('hero_bg', $bgFile);
                $success = 'Background hero berhasil diupload!';
            } else {
                $error = 'Gagal upload background. Pastikan file gambar (jpg/png/webp) max 2MB.';
            }
        }
        
        if (empty($error)) {
            $success = 'Hero section berhasil diperbarui!';
        }
    }
    
    // ========== PROFIL ==========
    if (isset($_POST['save_profil'])) {
        updatePengaturanText('profil_deskripsi', $_POST['profil_deskripsi'] ?? '');
        $success = 'Profil toko berhasil diperbarui!';
    }
    
    // ========== MILESTONES ==========
    if (isset($_POST['save_milestones'])) {
        $milestones = [];
        if (isset($_POST['milestone_tahun']) && is_array($_POST['milestone_tahun'])) {
            for ($i = 0; $i < count($_POST['milestone_tahun']); $i++) {
                if (!empty($_POST['milestone_tahun'][$i]) && !empty($_POST['milestone_judul'][$i])) {
                    $milestones[] = [
                        'tahun' => (int)$_POST['milestone_tahun'][$i],
                        'judul' => $_POST['milestone_judul'][$i],
                        'desc'  => $_POST['milestone_desc'][$i] ?? ''
                    ];
                }
            }
        }
        updatePengaturanJson('milestones', $milestones);
        $success = 'Milestones berhasil diperbarui!';
    }
    
    // ========== LAYANAN ==========
    if (isset($_POST['save_layanan'])) {
        $layanan = [];
        if (isset($_POST['layanan_icon']) && is_array($_POST['layanan_icon'])) {
            for ($i = 0; $i < count($_POST['layanan_icon']); $i++) {
                if (!empty($_POST['layanan_icon'][$i]) && !empty($_POST['layanan_judul'][$i])) {
                    $layanan[] = [
                        'icon'  => $_POST['layanan_icon'][$i],
                        'kelas' => 'icon-' . str_replace('bi-', '', $_POST['layanan_icon'][$i]),
                        'judul' => $_POST['layanan_judul'][$i],
                        'desc'  => $_POST['layanan_desc'][$i] ?? ''
                    ];
                }
            }
        }
        updatePengaturanJson('layanan', $layanan);
        $success = 'Layanan berhasil diperbarui!';
    }
    
    // ========== TRUST ITEMS ==========
    if (isset($_POST['save_trust'])) {
        $trustItems = [];
        if (isset($_POST['trust_icon']) && is_array($_POST['trust_icon'])) {
            for ($i = 0; $i < count($_POST['trust_icon']); $i++) {
                if (!empty($_POST['trust_icon'][$i]) && !empty($_POST['trust_text'][$i])) {
                    $trustItems[] = [
                        'icon' => $_POST['trust_icon'][$i],
                        'text' => $_POST['trust_text'][$i]
                    ];
                }
            }
        }
        updatePengaturanJson('trust_items', $trustItems);
        $success = 'Trust items berhasil diperbarui!';
    }
    
    $setting = getPengaturanToko();
}

$pageTitle = 'Pengaturan Toko';
include __DIR__ . '/admin_layout.php';
?>

<style>
.adm-form-group { margin-bottom: 1.5rem; }
.adm-form-label { font-weight: 600; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.5px; color: #6c757d; margin-bottom: 0.5rem; display: block; }
.adm-preview-img { max-width: 150px; border-radius: 8px; border: 1px solid #dee2e6; padding: 4px; background: #f8f9fa; }
.adm-form-row { display: flex; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; flex-wrap: wrap; }
.adm-form-row input, .adm-form-row textarea { flex: 1; min-width: 150px; }
.adm-remove-btn { background: none; border: none; color: #dc3545; cursor: pointer; font-size: 1.2rem; padding: 0 0.5rem; }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h4 class="mb-0"><i class="bi bi-gear-fill me-2"></i>Pengaturan Toko</h4>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show"><i class="bi bi-check-circle-fill me-2"></i> <?= $success ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show"><i class="bi bi-exclamation-triangle-fill me-2"></i> <?= $error ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<ul class="nav nav-tabs mb-4" id="settingTab" role="tablist">
    <li class="nav-item"><button class="nav-link active" id="hero-tab" data-bs-toggle="tab" data-bs-target="#hero"><i class="bi bi-house-door-fill me-1"></i> Hero</button></li>
    <li class="nav-item"><button class="nav-link" id="profil-tab" data-bs-toggle="tab" data-bs-target="#profil"><i class="bi bi-building me-1"></i> Profil</button></li>
    <li class="nav-item"><button class="nav-link" id="milestones-tab" data-bs-toggle="tab" data-bs-target="#milestones"><i class="bi bi-clock-history me-1"></i> Milestones</button></li>
    <li class="nav-item"><button class="nav-link" id="layanan-tab" data-bs-toggle="tab" data-bs-target="#layanan"><i class="bi bi-star-fill me-1"></i> Layanan</button></li>
    <li class="nav-item"><button class="nav-link" id="trust-tab" data-bs-toggle="tab" data-bs-target="#trust"><i class="bi bi-shield-check me-1"></i> Trust Items</button></li>
</ul>

<div class="tab-content">
    <!-- TAB HERO -->
    <div class="tab-pane fade show active" id="hero">
        <div class="admin-card">
            <div class="admin-card-header"><h5>Hero Section</h5></div>
            <div class="p-4">
                <form method="POST" enctype="multipart/form-data">
                    <div class="adm-form-group">
                        <label class="adm-form-label">Background Hero</label>
                        <?php 
                        $heroBg = $setting['hero_bg'] ?? '';
                        $bgUrl = !empty($heroBg) && file_exists(UPLOAD_PATH . '/pengaturan/' . $heroBg) 
                            ? UPLOAD_URL . '/pengaturan/' . $heroBg 
                            : '';
                        ?>
                        <?php if ($bgUrl): ?>
                            <div class="mb-2">
                                <img src="<?= $bgUrl ?>" class="adm-preview-img" id="heroBgPreview" style="max-width:100%; max-height:200px; border-radius:8px;">
                                <p class="text-success small mt-1"><i class="bi bi-check-circle-fill"></i> Background saat ini aktif</p>
                            </div>
                        <?php else: ?>
                            <div class="mb-2 text-muted">
                                <i class="bi bi-image"></i> Belum ada background. Upload gambar baru.
                            </div>
                        <?php endif; ?>
                        <input type="file" class="form-control" name="hero_bg" accept="image/jpeg,image/png,image/webp" id="heroBgInput" onchange="previewHeroBg(this)">
                        <small class="text-muted">Ukuran maksimal 2MB. Format: JPG, PNG, WebP<br>Rekomendasi ukuran: 1920x1080 pixel</small>
                        <div id="uploadPreview" class="mt-2" style="display:none;">
                            <img id="previewImage" style="max-width:200px; border-radius:8px; border:1px solid #ddd; padding:4px;">
                            <p class="small text-info mt-1"><i class="bi bi-info-circle"></i> Gambar baru akan diupload setelah klik Simpan</p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4"><div class="mb-2"><label class="form-label small fw-bold">Baris 1</label><input type="text" class="form-control" name="hero_title_line1" value="<?= e($setting['hero_title_line1'] ?? 'Kusen & Gypsum') ?>"></div></div>
                        <div class="col-md-4"><div class="mb-2"><label class="form-label small fw-bold">Baris 2 (Warna Highlight)</label><input type="text" class="form-control" name="hero_title_line2" value="<?= e($setting['hero_title_line2'] ?? 'Terbaik') ?>"></div></div>
                        <div class="col-md-4"><div class="mb-2"><label class="form-label small fw-bold">Baris 3</label><input type="text" class="form-control" name="hero_title_line3" value="<?= e($setting['hero_title_line3'] ?? 'untuk Hunian Anda') ?>"></div></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Subtitle</label>
                        <textarea class="form-control" name="hero_subtitle" rows="3"><?= e($setting['hero_subtitle'] ?? '') ?></textarea>
                    </div>
                    <button type="submit" name="save_hero" class="btn btn-primary-brand" onclick="this.innerHTML='<i class=\"bi bi-hourglass-split\"></i> Menyimpan...'; this.disabled=true; this.form.submit();">
                        <i class="bi bi-save"></i> Simpan Hero
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- TAB PROFIL -->
    <div class="tab-pane fade" id="profil">
        <div class="admin-card">
            <div class="admin-card-header"><h5>Profil Toko</h5></div>
            <div class="p-4">
                <form method="POST">
                    <textarea class="form-control mb-3" name="profil_deskripsi" rows="6" placeholder="Deskripsi toko"><?= e($setting['profil_deskripsi'] ?? '') ?></textarea>
                    <button type="submit" name="save_profil" class="btn btn-primary-brand">Simpan Profil</button>
                </form>
            </div>
        </div>
    </div>

    <!-- TAB MILESTONES -->
    <div class="tab-pane fade" id="milestones">
        <div class="admin-card">
            <div class="admin-card-header"><h5>Milestones</h5></div>
            <div class="p-4">
                <form method="POST" id="milestonesForm">
                    <div id="milestonesContainer">
                        <?php 
                        $milestones = $setting['milestones'] ?? [['tahun'=>2005,'judul'=>'Berdiri','desc'=>'Contoh deskripsi']];
                        foreach ($milestones as $idx => $m): ?>
                        <div class="adm-form-row">
                            <input type="number" name="milestone_tahun[]" placeholder="Tahun" value="<?= e($m['tahun']) ?>" style="width:100px">
                            <input type="text" name="milestone_judul[]" placeholder="Judul" value="<?= e($m['judul']) ?>">
                            <input type="text" name="milestone_desc[]" placeholder="Deskripsi" value="<?= e($m['desc']) ?>">
                            <button type="button" class="adm-remove-btn" onclick="this.closest('.adm-form-row').remove()">✖</button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-secondary mt-2" onclick="addMilestone()">+ Tambah Milestone</button>
                    <div class="mt-3"><button type="submit" name="save_milestones" class="btn btn-primary-brand">Simpan Milestones</button></div>
                </form>
            </div>
        </div>
    </div>

    <!-- TAB LAYANAN -->
    <div class="tab-pane fade" id="layanan">
        <div class="admin-card">
            <div class="admin-card-header"><h5>Layanan Unggulan</h5></div>
            <div class="p-4">
                <form method="POST" id="layananForm">
                    <div id="layananContainer">
                        <?php 
                        $layanan = $setting['layanan'] ?? [['icon'=>'bi-star','judul'=>'Contoh','desc'=>'Deskripsi']];
                        foreach ($layanan as $idx => $l): ?>
                        <div class="adm-form-row">
                            <input type="text" name="layanan_icon[]" placeholder="Icon (bi-...)" value="<?= e($l['icon']) ?>" style="width:140px">
                            <input type="text" name="layanan_judul[]" placeholder="Judul" value="<?= e($l['judul']) ?>">
                            <input type="text" name="layanan_desc[]" placeholder="Deskripsi" value="<?= e($l['desc']) ?>">
                            <button type="button" class="adm-remove-btn" onclick="this.closest('.adm-form-row').remove()">✖</button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-secondary mt-2" onclick="addLayanan()">+ Tambah Layanan</button>
                    <div class="mt-3"><button type="submit" name="save_layanan" class="btn btn-primary-brand">Simpan Layanan</button></div>
                </form>
            </div>
        </div>
    </div>

    <!-- TAB TRUST ITEMS -->
    <div class="tab-pane fade" id="trust">
        <div class="admin-card">
            <div class="admin-card-header"><h5>Trust Items</h5></div>
            <div class="p-4">
                <form method="POST" id="trustForm">
                    <div id="trustContainer">
                        <?php 
                        $trust = $setting['trust_items'] ?? [['icon'=>'bi-shield-check','text'=>'Contoh']];
                        foreach ($trust as $idx => $t): ?>
                        <div class="adm-form-row">
                            <input type="text" name="trust_icon[]" placeholder="Icon (bi-...)" value="<?= e($t['icon']) ?>" style="width:140px">
                            <input type="text" name="trust_text[]" placeholder="Teks" value="<?= e($t['text']) ?>">
                            <button type="button" class="adm-remove-btn" onclick="this.closest('.adm-form-row').remove()">✖</button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-secondary mt-2" onclick="addTrust()">+ Tambah Trust Item</button>
                    <div class="mt-3"><button type="submit" name="save_trust" class="btn btn-primary-brand">Simpan Trust Items</button></div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function previewHeroBg(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var previewImg = document.getElementById('heroBgPreview');
            // Jika elemen preview tidak ada, buat dulu
            if (!previewImg) {
                var previewContainer = document.querySelector('#hero .adm-form-group .mb-2');
                if (previewContainer) {
                    previewContainer.innerHTML = '<img id="heroBgPreview" class="adm-preview-img" style="max-width:100%; max-height:200px; border-radius:8px;">';
                    previewImg = document.getElementById('heroBgPreview');
                }
            }
            if (previewImg) {
                previewImg.src = e.target.result;
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
}
function addMilestone() {
    var div = document.createElement('div');
    div.className = 'adm-form-row';
    div.innerHTML = '<input type="number" name="milestone_tahun[]" placeholder="Tahun" style="width:100px"><input type="text" name="milestone_judul[]" placeholder="Judul"><input type="text" name="milestone_desc[]" placeholder="Deskripsi"><button type="button" class="adm-remove-btn" onclick="this.closest(\'.adm-form-row\').remove()">✖</button>';
    document.getElementById('milestonesContainer').appendChild(div);
}
function addLayanan() {
    var div = document.createElement('div');
    div.className = 'adm-form-row';
    div.innerHTML = '<input type="text" name="layanan_icon[]" placeholder="Icon (bi-...)" style="width:140px"><input type="text" name="layanan_judul[]" placeholder="Judul"><input type="text" name="layanan_desc[]" placeholder="Deskripsi"><button type="button" class="adm-remove-btn" onclick="this.closest(\'.adm-form-row\').remove()">✖</button>';
    document.getElementById('layananContainer').appendChild(div);
}
function addTrust() {
    var div = document.createElement('div');
    div.className = 'adm-form-row';
    div.innerHTML = '<input type="text" name="trust_icon[]" placeholder="Icon (bi-...)" style="width:140px"><input type="text" name="trust_text[]" placeholder="Teks"><button type="button" class="adm-remove-btn" onclick="this.closest(\'.adm-form-row\').remove()">✖</button>';
    document.getElementById('trustContainer').appendChild(div);
}
</script>

<?php include __DIR__ . '/admin_footer.php'; ?>