<?php
// File: admin/crud_artikel.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require '../includes/db_connect.php';
require '../includes/functions.php';
require '../includes/upload_helper.php';

if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit; }

$view = $_GET['view'] ?? 'list';
$error = '';

// DELETE
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    try {
        $stmt = $pdo->prepare("SELECT gambar_cover_url FROM artikel WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $row = $stmt->fetch();
        if ($row) deleteFile($row['gambar_cover_url']);
        
        $pdo->prepare("DELETE FROM artikel WHERE id = ?")->execute([$_GET['id']]);
        header("Location: crud_artikel.php?msg=deleted"); exit;
    } catch (Exception $e) { $error = $e->getMessage(); }
}

// SAVE
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $id = $_POST['id'] ?? null;
        $judul = $_POST['judul'];
        $konten = $_POST['konten']; 
        $date = $_POST['date']; 
        $meta_desc = $_POST['meta_description']; 

        // Upload Image
        $img = $_POST['existing_image'] ?? '';
        if (!empty($_FILES['image']['name'])) {
            $up = uploadImage($_FILES['image'], "../uploads/artikel/", "art");
            if ($up) {
                deleteFile($img);
                $img = $up;
            }
        } elseif (!empty($_POST['image_url_external'])) {
            $img = $_POST['image_url_external'];
        }

        if ($id) {
            $pdo->prepare("UPDATE artikel SET judul=?, konten=?, tanggal_buat=?, gambar_cover_url=?, meta_description=? WHERE id=?")
                ->execute([$judul, $konten, $date, $img, $meta_desc, $id]);
        } else {
            $pdo->prepare("INSERT INTO artikel (judul, konten, tanggal_buat, gambar_cover_url, meta_description) VALUES (?, ?, ?, ?, ?)")
                ->execute([$judul, $konten, $date, $img, $meta_desc]);
        }
        header("Location: crud_artikel.php?msg=saved"); exit;
    } catch (Exception $e) { $error = $e->getMessage(); }
}

$articles = getAllArticles($pdo);
$edit = null;
if ($view == 'edit' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM artikel WHERE id = ?");
    $stmt->execute([$_GET['id']]);
    $edit = $stmt->fetch();
}

$page_title = 'Kelola Artikel';
require 'includes/header.php';
?>

<!-- SCRIPT TINYMCE (VERSI GRATIS/OPEN SOURCE VIA CDNJS) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.2/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#editor_content', 
    height: 400,
    menubar: false,
    plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
    toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
    branding: false, // Hilangkan logo TinyMCE
    promotion: false // Hilangkan tombol upgrade
  });
</script>

<main class="flex-1 overflow-y-auto p-6 md:p-10 bg-gray-50 w-full">
    <?php if($error): ?><div class="bg-red-100 text-red-700 p-4 rounded mb-4"><?= $error ?></div><?php endif; ?>
    <?php if(isset($_GET['msg'])): ?><div class="bg-green-100 text-green-700 p-4 rounded mb-4">Berhasil!</div><?php endif; ?>

    <?php if ($view == 'list'): ?>
        <div class="flex justify-between mb-4">
            <h1 class="text-2xl font-bold">Artikel</h1>
            <a href="?view=add" class="bg-blue-600 text-white px-4 py-2 rounded">Tambah Artikel</a>
        </div>
        <div class="bg-white shadow rounded overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-800 text-white"><tr><th class="p-3">Img</th><th class="p-3">Judul</th><th class="p-3">Tanggal</th><th class="p-3">Aksi</th></tr></thead>
                <tbody>
                    <?php foreach($articles as $a): ?>
                    <tr class="border-b hover:bg-gray-50">
                        <td class="p-3"><img src="<?= (strpos($a['image'],'http')===0?$a['image']:'../'.$a['image']) ?>" class="h-10 w-16 object-cover rounded"></td>
                        <td class="p-3 font-bold"><?= htmlspecialchars($a['title']) ?></td>
                        <td class="p-3 text-sm text-gray-500"><?= $a['date'] ?></td>
                        <td class="p-3">
                            <a href="?view=edit&id=<?= $a['id'] ?>" class="text-blue-600 mr-2"><i class="fa-solid fa-pen"></i></a>
                            <a href="?action=delete&id=<?= $a['id'] ?>" onclick="return confirm('Hapus?')" class="text-red-600"><i class="fa-solid fa-trash"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

    <?php else: ?>
        <form method="POST" enctype="multipart/form-data" class="bg-white p-6 rounded shadow max-w-4xl mx-auto">
            <input type="hidden" name="id" value="<?= $edit['id']??'' ?>">
            <input type="hidden" name="existing_image" value="<?= $edit['gambar_cover_url']??'' ?>">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
                <div>
                    <label class="block font-bold mb-1">Judul Artikel</label>
                    <input type="text" name="judul" value="<?= htmlspecialchars($edit['judul']??'') ?>" class="w-full border p-2 rounded" required>
                </div>
                <div>
                    <label class="block font-bold mb-1">Tanggal</label>
                    <input type="date" name="date" value="<?= $edit['tanggal_buat'] ?? date('Y-m-d') ?>" class="w-full border p-2 rounded">
                </div>
            </div>

            <!-- META DESCRIPTION (SEO) -->
            <div class="mb-4">
                <label class="block font-bold mb-1 text-sm text-blue-600">Meta Description (SEO)</label>
                <textarea name="meta_description" rows="2" class="w-full border p-2 rounded text-sm text-gray-600" placeholder="Ringkasan singkat untuk Google..."><?= htmlspecialchars($edit['meta_description']??'') ?></textarea>
            </div>

            <!-- TINYMCE EDITOR -->
            <div class="mb-4">
                <label class="block font-bold mb-1">Isi Artikel</label>
                <textarea id="editor_content" name="konten" class="w-full"><?= htmlspecialchars($edit['konten']??'') ?></textarea>
            </div>

            <div class="mb-4">
                <label class="block font-bold mb-1">Gambar Utama</label>
                <input type="file" name="image" class="w-full border p-1 mb-1">
                <input type="text" name="image_url_external" value="<?= $edit['gambar_cover_url']??'' ?>" class="w-full border p-1 text-sm" placeholder="URL External...">
            </div>

            <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded font-bold hover:bg-blue-700">Simpan Artikel</button>
        </form>
    <?php endif; ?>
</main>
<?php require 'includes/footer.php'; ?>