<?php
session_start();
require_once '../config/db.php';
require_once 'auth.php';

$pageTitle = 'About Us';
$activePage = 'about';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $section = $_POST['section']??'';
    $title = trim($_POST['title']??'');
    $content = $_POST['content']??'';
    $existing_img = $_POST['existing_image']??'';
    $image = $existing_img;
    if (!empty($_FILES['image']['name'])) {
        $up = uploadFile($_FILES['image'], 'assets/images/about');
        if ($up) $image = $up;
    }
    $pdo->prepare("UPDATE about_content SET title=?,content=?,image=? WHERE section=?")
        ->execute([$title,$content,$image,$section]);
    $msg = adminAlert('Konten berhasil disimpan.');
}

$sections = $pdo->query("SELECT * FROM about_content ORDER BY id")->fetchAll();
include 'partials/header.php';
?>
<?= $msg ?>
<div class="row g-4">
    <?php foreach ($sections as $sec): ?>
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header text-capitalize"><i class="bi bi-pencil-square me-2"></i><?= ucwords(str_replace('_',' ',$sec['section'])) ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="section" value="<?= $sec['section'] ?>">
                    <input type="hidden" name="existing_image" value="<?= $sec['image'] ?>">
                    <div class="mb-3"><label class="form-label fw-semibold">Judul</label><input type="text" name="title" class="form-control" value="<?= htmlspecialchars($sec['title']??'') ?>"></div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Konten (HTML diperbolehkan)</label>
                        <textarea name="content" class="form-control" rows="6"><?= htmlspecialchars($sec['content']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Gambar</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <?php if ($sec['image']): ?><img src="../<?= $sec['image'] ?>" class="mt-1 rounded" style="height:60px;object-fit:cover;" onerror="this.style.display='none'"><?php endif; ?>
                    </div>
                    <button type="submit" class="btn btn-dark btn-sm"><i class="bi bi-save me-1"></i>Simpan</button>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php include 'partials/footer.php'; ?>
