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

// Handle Tambah Berita
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tambah_berita'])) {
    $judul = trim($_POST['judul']);
    $isi = $_POST['isi'];
    $kategori = $_POST['kategori'];
    $penulis = $_SESSION['nama'];
    $gambar_url = '';

    if (!empty($_FILES['gambar']['name'])) {
        $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("INSERT INTO berita (judul, isi, gambar, kategori, penulis) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$judul, $isi, $gambar_url, $kategori, $penulis]);
            $success = "Berita berhasil ditambahkan!";
        } catch (PDOException $e) {
            $error = "Gagal menyimpan berita: " . $e->getMessage();
        }
    }
}

// Handle Hapus
if (isset($_GET['hapus'])) {
    $id_hapus = (int)$_GET['hapus'];
    $stmt = $pdo->prepare("SELECT gambar FROM berita WHERE id = ?");
    $stmt->execute([$id_hapus]);
    $gbr = $stmt->fetchColumn();
    if ($gbr && file_exists('../' . $gbr)) {
        unlink('../' . $gbr);
    }
    $pdo->prepare("DELETE FROM berita WHERE id = ?")->execute([$id_hapus]);
    header("Location: manajemen_berita.php");
    exit;
}

$berita_list = $pdo->query("SELECT * FROM berita ORDER BY tgl_posting DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!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>Manajemen 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">
<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%;
}
.berita-item {
    border: 1px solid #f0f0f0; border-radius: 14px; padding: 14px; margin-bottom: 12px;
    display: flex; gap: 12px; align-items: flex-start;
}
.berita-img {
    width: 70px; height: 70px; border-radius: 10px; object-fit: cover;
    background: #f0f0f0; flex-shrink: 0;
}
.berita-info { flex: 1; }
.berita-judul { font-weight: 700; font-size: 0.95rem; color: #2f3440; margin-bottom: 4px; }
.berita-meta { font-size: 0.75rem; color: #7a8190; }
.badge-kat { font-size: 0.7rem; padding: 3px 8px; border-radius: 10px; }
.badge-berita { background: #e9f2ff; color: #0d6efd; }
.badge-pengumuman { background: #fff3cd; color: #856404; }
.action-buttons {
    display: flex;
    gap: 8px;
    flex-direction: column;
}
.btn-action {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    font-size: 0.95rem;
    transition: all 0.2s;
}
.btn-edit {
    background: #fff3cd;
    color: #856404;
}
.btn-edit:hover {
    background: #ffc107;
    color: white;
}
.btn-delete {
    background: #fdecec;
    color: #dc3545;
}
.btn-delete:hover {
    background: #dc3545;
    color: white;
}
.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;
}
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Manajemen 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; ?>

    <!-- Form Tambah Berita -->
    <div class="card-soft">
        <div class="section-title"><i class="fa fa-plus-circle me-2 text-primary"></i>Tambah 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="tambah_berita" value="1">
            <div class="mb-3">
                <label class="form-label">Kategori</label>
                <select name="kategori" class="form-select" required>
                    <option value="berita">Berita</option>
                    <option value="pengumuman">Pengumuman</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Judul</label>
                <input type="text" name="judul" class="form-control" required placeholder="Judul berita">
            </div>
            <div class="mb-3">
                <label class="form-label">Isi Berita</label>
                <textarea name="isi" id="editorBerita" rows="10"></textarea>
            </div>
            <div class="mb-4">
                <label class="form-label">Gambar Sampul (Opsional)</label>
                <input type="file" name="gambar" class="form-control" accept="image/*">
            </div>
            <button type="submit" class="btn btn-sage">
                <i class="fa fa-save me-2"></i> Publikasikan
            </button>
        </form>
    </div>

    <!-- Daftar Berita -->
    <div class="card-soft">
        <div class="section-title"><i class="fa fa-newspaper me-2 text-primary"></i>Daftar Berita (<?= count($berita_list) ?>)</div>
        <?php if (empty($berita_list)): ?>
            <div class="text-center text-muted py-3 small">Belum ada berita yang dipublikasikan.</div>
        <?php else: ?>
            <?php foreach ($berita_list as $b): ?>
            <div class="berita-item">
                <?php if (!empty($b['gambar'])): ?>
                    <img src="../<?= htmlspecialchars($b['gambar']) ?>" class="berita-img" alt="Gambar">
                <?php else: ?>
                    <div class="berita-img d-flex align-items-center justify-content-center">
                        <i class="fa fa-image text-muted"></i>
                    </div>
                <?php endif; ?>
                <div class="berita-info">
                    <div class="berita-judul"><?= htmlspecialchars($b['judul']) ?></div>
                    <div class="berita-meta">
                        <span class="badge-kat <?= $b['kategori'] === 'pengumuman' ? 'badge-pengumuman' : 'badge-berita' ?>">
                            <?= ucfirst($b['kategori']) ?>
                        </span>
                        • <?= date('d/m/Y H:i', strtotime($b['tgl_posting'])) ?>
                    </div>
                </div>
                <div class="action-buttons">
                    <a href="edit_berita.php?id=<?= $b['id'] ?>" class="btn-action btn-edit" title="Edit">
                        <i class="fa fa-pen"></i>
                    </a>
                    <a href="?hapus=<?= $b['id'] ?>" class="btn-action btn-delete" onclick="return confirm('Hapus berita ini?')" title="Hapus">
                        <i class="fa fa-trash"></i>
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
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>