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

$id_edit = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$success = '';
$error = '';

// Ambil data berita
$stmt = $pdo->prepare("SELECT * FROM berita WHERE id = ?");
$stmt->execute([$id_edit]);
$berita = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$berita) {
    header("Location: manajemen_berita.php");
    exit;
}

// Handle Update Berita
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_berita'])) {
    $judul = trim($_POST['judul']);
    $isi = $_POST['isi'];
    $kategori = $_POST['kategori'];
    $gambar_url = $berita['gambar']; // Tetap gunakan gambar lama

    // Upload gambar baru jika ada
    if (!empty($_FILES['gambar']['name'])) {
        // Hapus gambar lama jika ada
        if ($berita['gambar'] && file_exists('../' . $berita['gambar'])) {
            unlink('../' . $berita['gambar']);
        }
        
        $ext = pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION);
        $nama_file = 'berita_' . time() . '.' . $ext;
        $target = '../assets/uploads/berita/' . $nama_file;
        if (!is_dir('../assets/uploads/berita/')) {
            mkdir('../assets/uploads/berita/', 0755, true);
        }
        if (move_uploaded_file($_FILES['gambar']['tmp_name'], $target)) {
            $gambar_url = 'assets/uploads/berita/' . $nama_file;
        }
    }

    if (empty($judul) || empty(strip_tags($isi))) {
        $error = "Judul dan Isi berita wajib diisi!";
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE berita SET judul=?, isi=?, gambar=?, kategori=? WHERE id=?");
            $stmt->execute([$judul, $isi, $gambar_url, $kategori, $id_edit]);
            $success = "Berita berhasil diperbarui!";
            
            // Refresh data
            $stmt = $pdo->prepare("SELECT * FROM berita WHERE id = ?");
            $stmt->execute([$id_edit]);
            $berita = $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            $error = "Gagal memperbarui berita: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Edit Berita - SPAM</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- TinyMCE Editor dengan API Key -->
<script src="https://cdn.tiny.cloud/1/rf40dlddqeep0u98p87q03v6zjhnc2zj28focf88j13zl0fo/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<style>
body { background:#f4f7fe; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white; padding:18px;
    border-bottom-left-radius:20px; border-bottom-right-radius:20px;
}
.card-soft {
    background: white; border: none; border-radius: 20px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05); padding: 20px; margin-bottom: 15px;
}
.section-title { font-size: 1rem; font-weight: 800; color: #354052; margin-bottom: 15px; }
.form-control, .form-select {
    border-radius: 12px; padding: 12px 15px; border: 1px solid #e0e0e0; background: #f8f9fa;
}
.form-control:focus, .form-select:focus {
    border-color: #3A7CA5; box-shadow: 0 0 0 0.25rem rgba(58, 124, 165, 0.25); background: white;
}
.form-label { font-weight: 700; font-size: 0.85rem; color: #4a5568; }
.btn-sage {
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color: white; border: none; border-radius: 12px; padding: 12px; font-weight: 700; width: 100%;
}
.btn-secondary-custom {
    background: #6c757d;
    color: white; border: none; border-radius: 12px; padding: 12px; font-weight: 700; width: 100%;
}
.tox-tinymce { border-radius: 12px !important; border: 1px solid #e0e0e0 !important; }
.editor-tip {
    background: #f0f7ff; border-left: 4px solid #3A7CA5;
    padding: 10px 14px; border-radius: 8px; font-size: 0.82rem; color: #5a6270;
    margin-bottom: 10px;
}
.gambar-preview {
    max-width: 200px;
    border-radius: 12px;
    border: 2px dashed #e0e0e0;
    padding: 5px;
    margin-bottom: 10px;
}
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="manajemen_berita.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Edit Berita</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5 mt-3">
    <?php if ($success): ?>
        <div class="alert alert-success" style="font-size:0.85rem; border-radius:10px;"><?= $success ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger" style="font-size:0.85rem; border-radius:10px;"><?= $error ?></div>
    <?php endif; ?>

    <div class="card-soft">
        <div class="section-title"><i class="fa fa-pen-to-square me-2 text-primary"></i>Edit Berita / Pengumuman</div>
        
        <div class="editor-tip">
            <i class="fa fa-lightbulb me-1"></i> 
            <b>Tips:</b> Gunakan toolbar di bawah untuk memformat teks. Anda bisa membuat heading, italic, bullet list, numbered list, tabel, warna teks, link, dan sisipkan gambar.
        </div>

        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="update_berita" value="1">
            <div class="mb-3">
                <label class="form-label">Kategori</label>
                <select name="kategori" class="form-select" required>
                    <option value="berita" <?= $berita['kategori'] === 'berita' ? 'selected' : '' ?>>Berita</option>
                    <option value="pengumuman" <?= $berita['kategori'] === 'pengumuman' ? 'selected' : '' ?>>Pengumuman</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Judul</label>
                <input type="text" name="judul" class="form-control" required value="<?= htmlspecialchars($berita['judul']) ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">Isi Berita</label>
                <textarea name="isi" id="editorBerita" rows="10"><?= htmlspecialchars($berita['isi']) ?></textarea>
            </div>
            
            <div class="mb-4">
                <label class="form-label">Gambar Sampul</label>
                <?php if (!empty($berita['gambar'])): ?>
                    <div class="text-center mb-2">
                        <img src="../<?= htmlspecialchars($berita['gambar']) ?>" class="gambar-preview" alt="Gambar Saat Ini">
                        <div class="small text-muted">Gambar saat ini</div>
                    </div>
                <?php endif; ?>
                <input type="file" name="gambar" class="form-control" accept="image/*">
                <small class="text-muted">Kosongkan jika tidak ingin mengganti gambar</small>
            </div>

            <div class="row g-2">
                <div class="col-6">
                    <a href="manajemen_berita.php" class="btn btn-secondary-custom text-decoration-none">
                        <i class="fa fa-times me-2"></i> Batal
                    </a>
                </div>
                <div class="col-6">
                    <button type="submit" class="btn btn-sage">
                        <i class="fa fa-save me-2"></i> Simpan Perubahan
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Inisialisasi TinyMCE Editor
tinymce.init({
    selector: '#editorBerita',
    height: 400,
    menubar: true,
    plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'help', 'wordcount', 'directionality'
    ],
    toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough forecolor backcolor | ' +
             'alignleft aligncenter alignright alignjustify | ' +
             'bullist numlist outdent indent | link image media table | ' +
             'removeformat code fullscreen preview help',
    content_style: 'body { font-family: Segoe UI, Arial, sans-serif; font-size: 14px; line-height: 1.6; }',
    branding: false,
    promotion: false,
    language: 'id',
    images_upload_handler: function (blobInfo) {
        return new Promise(function (resolve, reject) {
            var reader = new FileReader();
            reader.onload = function () {
                resolve(reader.result);
            };
            reader.onerror = function () {
                reject('Gagal memuat gambar');
            };
            reader.readAsDataURL(blobInfo.blob());
        });
    }
});
</script>
</body>
</html>