<?php
include('auth.php'); // Sertakan autentikasi

// Tampilkan nama pengguna
$username = $_SESSION['username'] ?? 'Cobela'; // Gunakan 'Guest' sebagai default jika tidak ada username

// Aktifkan debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// File untuk menyimpan berita dan kategori
$newsDir = __DIR__ . '/../data/news/';
$kategoriFile = __DIR__ . '/../data/kategori.json';

// Fungsi untuk membuat slug dari judul
function generateSlug($string) {
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));
}

// Ambil daftar kategori dari file kategori.json
$kategoriList = [];
if (file_exists($kategoriFile)) {
    $kategoriList = json_decode(file_get_contents($kategoriFile), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        die('Error decoding JSON: ' . json_last_error_msg());
    }
}

// Ambil slug dari query string untuk mencari berita yang akan diedit
$slug = $_GET['slug'] ?? '';
if (empty($slug)) {
    die('Artikel tidak ditemukan.');
}

// Cek apakah file berita ada berdasarkan slug
$newsFilePath = $newsDir . $slug . '.json';
if (!file_exists($newsFilePath)) {
    die('Artikel tidak ditemukan.');
}

// Ambil data berita dari file JSON
$newsData = json_decode(file_get_contents($newsFilePath), true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die('Error decoding JSON: ' . json_last_error_msg());
}

// Proses form submit untuk update berita
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validasi data dari form
    $judul = $_POST['judul'] ?? '';
    $kategori = $_POST['kategori'] ?? '';
    $tanggal = $_POST['tanggal'] ?? '';
    $image = $_POST['image'] ?? '';
    $imageDescription = $_POST['image_description'] ?? ''; // Tambahkan deskripsi gambar
    $konten = $_POST['konten'] ?? '';
    $tag = $_POST['tag'] ?? '';

    if (empty($judul) || empty($kategori) || empty($tanggal) || empty($konten)) {
        die('Semua kolom harus diisi.');
    }

    // Update data berita
    $newsData['judul'] = $judul;
    $newsData['kategori'] = $kategori;
    $newsData['tanggal'] = $tanggal;
    $newsData['image'] = $image;
    $newsData['image_description'] = $imageDescription; // Update deskripsi gambar
    $newsData['konten'] = $konten;
    $newsData['tag'] = array_map('trim', explode(',', $tag));

    // Buat slug baru jika judul berubah
    $newSlug = generateSlug($judul);

    // Jika slug berubah, pindahkan file berita ke nama baru
    if ($newSlug !== $slug) {
        $newNewsFilePath = $newsDir . $newSlug . '.json';
        if (rename($newsFilePath, $newNewsFilePath)) {
            $newsFilePath = $newNewsFilePath;
        } else {
            die('Gagal mengubah nama file berita.');
        }
    }

    // Simpan berita yang diperbarui ke file JSON
    if (file_put_contents($newsFilePath, json_encode($newsData, JSON_PRETTY_PRINT))) {
        $success = "Berita berhasil diperbarui!";
        $slug = $newSlug; // Perbarui slug setelah penyimpanan berhasil
    } else {
        $error = "Gagal memperbarui berita.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Edit News - KoeasNews</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<!-- Place the first <script> tag in your HTML's <head> -->
<script src="js/tinymce/tinymce.min.js" referrerpolicy="origin"></script>
</head>
<body class="bg-dark">
<div class="container py-4">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card mt-4 border-0 shadow rounded-4 p-3">
<div class="card-body">
<h4 class="card-title"><a class="text-decoration-none text-dark" href="dashboard.php"> Dashboard CMS</a> - Edit Berita <span class="small float-end"><small>Halo <?php echo htmlspecialchars($username); ?></small>&nbsp;<a href="logout.php" class="btn btn-danger btn-sm">Logout</a></span></h4>
<a class="btn shadow btn-sm mb-3 mt-3" href="dashboard.php" role="button">Home</a> &nbsp; <a class="btn shadow btn-sm mb-3 mt-3" href="add_news.php" role="button">Create News</a> &nbsp; <a class="btn shadow btn-sm mb-3 mt-3" href="add_kategori.php" role="button">Add Category</a>  &nbsp; <a class="btn shadow btn-sm mb-3 mt-3" href="settings.php" role="button">Settings</a>
<?php if (isset($success)): ?>
            <div class="alert alert-success">
                <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>
        <?php if (isset($error)): ?>
            <div class="alert alert-danger">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>
    <form method="POST" enctype="multipart/form-data">
        <div class="form-group mb-3">
                <label class="form-label" for="judul">Judul</label>
                <input type="text" class="form-control" id="judul" name="judul" value="<?php echo htmlspecialchars($newsData['judul']); ?>" required>
            </div>
            <div class="form-group mb-3">
                <label class="form-label" for="kategori">Category</label>
                <select class="form-control" id="kategori" name="kategori" required>
                    <option value="" disabled>Select Kategory</option>
                    <?php foreach ($kategoriList as $kategori): ?>
                        <option value="<?php echo htmlspecialchars($kategori); ?>" <?php echo $kategori === $newsData['kategori'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($kategori); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group mb-3">
                <label class="form-label" for="tanggal">Date</label>
                <input type="date" class="form-control" id="tanggal" name="tanggal" value="<?php echo htmlspecialchars($newsData['tanggal']); ?>" required>
            </div>
            <div class="form-group mb-3">
                <label class="form-label" for="image">Image</label>
                <input type="text" class="form-control" id="image" name="image" value="<?php echo htmlspecialchars($newsData['image']); ?>">
            </div>
            <div class="form-group mb-3">
                <label class="form-label" for="image_description">Deskripsi Gambar:</label>
                <textarea class="form-control" id="image_description" name="image_description"><?php echo htmlspecialchars($newsData['image_description'] ?? ''); ?></textarea> <!-- Tambahkan field deskripsi gambar -->
            </div>
            <div class="form-group mb-3">
                <label class="form-label" for="konten">Content</label>
                <textarea id="mytextarea" class="form-control" id="konten" name="konten" rows="5" required><?php echo htmlspecialchars($newsData['konten']); ?></textarea>
                <script>
    function validateForm() {
        // Pastikan TinyMCE sinkron dengan textarea aslinya
        tinymce.triggerSave();

        // Cek apakah konten TinyMCE berhasil disimpan ke textarea
        var konten = document.getElementById('mytextarea').value;
        if (konten == "") {
            alert("Konten tidak boleh kosong!");
            return false; // Blokir pengiriman form jika konten kosong
        }
        return true; // Lanjutkan pengiriman form
    }

    tinymce.init({
        selector: '#mytextarea',
                selector: '#mytextarea',
                menubar: true,
                plugins: 'advlist autolink lists link image charmap preview anchor pagebreak searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking save table contextmenu directionality emoticons template paste textcolor colorpicker textpattern',
                toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
                toolbar_mode: 'sliding',
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
        }
    });
</script>
            </div>
            <div class="form-group mb-3">
                <label class="form-label" for="tag">Tag (Separate with commas)</label>
                <input type="text" class="form-control" id="tag" name="tag" value="<?php echo htmlspecialchars(implode(',', $newsData['tag'])); ?>">
            </div>
            <button type="submit" onsubmit="return validateForm();" class="btn btn-primary mt-3">Save</button>
        </form>
</body>
</div>
</div>
</div>
</div>
</html>
