<?php
// File: admin/form_artikel.php
session_start();
require '../includes/db_connect.php';
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit; }

$id = $_GET['id'] ?? null;
$a = ['judul' => '', 'konten' => '', 'gambar_cover_url' => '', 'meta_description' => '', 'status' => 'published'];

if ($id) {
    $stmt = $pdo->prepare("SELECT * FROM artikel WHERE id = ?");
    $stmt->execute([$id]);
    $a = $stmt->fetch();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $vals = [$_POST['judul'], $_POST['konten'], $_POST['gambar'], $_POST['meta'], $_POST['status']];
    if ($id) {
        $vals[] = $id;
        $pdo->prepare("UPDATE artikel SET judul=?, konten=?, gambar_cover_url=?, meta_description=?, status=? WHERE id=?")->execute($vals);
    } else {
        $pdo->prepare("INSERT INTO artikel (judul, konten, tanggal_buat, gambar_cover_url, meta_description, status) VALUES (?, ?, '".date('Y-m-d')."', ?, ?, ?)")->execute($vals);
    }
    header("Location: crud_artikel.php"); exit;
}

$page_title = 'Form Artikel';
require 'includes/header.php';
?>
<div class="container mx-auto px-4 max-w-2xl">
    <div class="bg-white p-6 rounded-[2.5rem] shadow-xl border border-slate-100">
        <h2 class="text-2xl font-black mb-8 uppercase tracking-tighter"><?= $id?'Edit':'Tambah' ?> Artikel</h2>
        <form method="POST" class="space-y-5">
            <input type="text" name="judul" value="<?= htmlspecialchars($a['judul']) ?>" placeholder="Judul Artikel" class="w-full p-4 bg-slate-50 rounded-2xl outline-none focus:ring-2 focus:ring-red-600" required>
            <textarea name="konten" rows="8" placeholder="Konten Artikel (HTML diperbolehkan)" class="w-full p-4 bg-slate-50 rounded-2xl outline-none focus:ring-2 focus:ring-red-600"><?= $a['konten'] ?></textarea>
            <input type="text" name="gambar" value="<?= $a['gambar_cover_url'] ?>" placeholder="URL Gambar Cover" class="w-full p-4 bg-slate-50 rounded-2xl outline-none">
            <input type="text" name="meta" value="<?= $a['meta_description'] ?>" placeholder="Meta Description (SEO)" class="w-full p-4 bg-slate-50 rounded-2xl outline-none">
            <select name="status" class="w-full p-4 bg-slate-50 rounded-2xl outline-none">
                <option value="published" <?= $a['status']=='published'?'selected':'' ?>>Published</option>
                <option value="pending" <?= $a['status']=='pending'?'selected':'' ?>>Pending</option>
            </select>
            <button type="submit" class="w-full py-5 bg-slate-900 text-white rounded-[1.5rem] font-black uppercase tracking-widest shadow-xl">SIMPAN ARTIKEL</button>
        </form>
    </div>
</div>
<?php require 'includes/footer.php'; ?>