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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php"); exit;
}

// Ambil ID berita yang akan diedit
if (!isset($_GET['id'])) {
    header("Location: manage_berita.php"); exit;
}

$id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM berita WHERE id_berita = ?");
$stmt->execute([$id]);
$b = $stmt->fetch();

if (!$b) { echo "Berita tidak ditemukan!"; exit; }

// Proses Update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $judul = $_POST['judul'];
    $isi   = $_POST['isi'];
    $kat   = $_POST['kategori'];
    $nama_file = $b['gambar']; // Default pakai foto lama

    // Jika ada upload foto baru
    if (!empty($_FILES['gambar']['name'])) {
        // Hapus foto lama jika ada
        if ($b['gambar'] && file_exists("../assets/img/berita/" . $b['gambar'])) {
            unlink("../assets/img/berita/" . $b['gambar']);
        }
        $nama_file = time() . "_" . $_FILES['gambar']['name'];
        move_uploaded_file($_FILES['gambar']['tmp_name'], "../assets/img/berita/" . $nama_file);
    }

    $update = $pdo->prepare("UPDATE berita SET judul=?, isi=?, gambar=?, kategori=? WHERE id_berita=?");
    if ($update->execute([$judul, $isi, $nama_file, $kat, $id])) {
        echo "<script>alert('Berita berhasil diperbarui!'); window.location='manage_berita.php';</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Berita</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
    <style>
        .ck-editor__editable { min-height: 300px; }
        .preview-img { max-height: 150px; border-radius: 10px; margin-bottom: 10px; }
    </style>
</head>
<body class="bg-light">
    <?php include 'sidebar.php'; ?>
    <div class="main-content">
        <div class="container-fluid">
            <div class="card border-0 shadow-sm rounded-4 mx-auto" style="max-width: 900px;">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h5 class="fw-bold mb-0">Edit Artikel</h5>
                        <a href="manage_berita.php" class="btn btn-sm btn-outline-secondary">Kembali</a>
                    </div>
                    
                    <form method="POST" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label class="small fw-bold">Judul Berita</label>
                                    <input type="text" name="judul" class="form-control" value="<?= htmlspecialchars($b['judul']) ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="small fw-bold">Isi Berita</label>
                                    <textarea name="isi" id="editor"><?= $b['isi'] ?></textarea>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="small fw-bold">Kategori</label>
                                    <select name="kategori" class="form-select">
                                        <option <?= $b['kategori'] == 'Info Kesehatan' ? 'selected' : '' ?>>Info Kesehatan</option>
                                        <option <?= $b['kategori'] == 'Kegiatan' ? 'selected' : '' ?>>Kegiatan</option>
                                        <option <?= $b['kategori'] == 'Pengumuman' ? 'selected' : '' ?>>Pengumuman</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="small fw-bold d-block">Foto Saat Ini</label>
                                    <?php if($b['gambar']): ?>
                                        <img src="../assets/img/berita/<?= $b['gambar'] ?>" class="preview-img img-thumbnail shadow-sm">
                                    <?php else: ?>
                                        <div class="p-3 bg-light text-muted small border mb-2 rounded">Tidak ada foto</div>
                                    <?php endif; ?>
                                    
                                    <label class="small fw-bold d-block mt-2">Ganti Foto (Opsional)</label>
                                    <input type="file" name="gambar" class="form-control" accept="image/*">
                                </div>
                                <hr>
                                <button type="submit" class="btn btn-success w-100 py-3 fw-bold shadow">
                                    <i class="fa fa-save me-2"></i>Simpan Perubahan
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ), {
                toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo' ]
            } )
            .catch( error => { console.error( error ); } );
    </script>
</body>
</html>