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

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

// Folder data kategori
$kategoriFile = __DIR__ . '/../data/kategori.json';

// Baca data kategori
$kategoriData = json_decode(file_get_contents($kategoriFile), true);
if (!is_array($kategoriData)) {
    $kategoriData = [];
}

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

// Proses penyimpanan berita jika form dikirim
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $judul = $_POST['judul'];
    $kategori = $_POST['kategori'];
    $konten = $_POST['konten'];
    $tag = explode(',', $_POST['tag']);
    $imageDescription = $_POST['image_description']; // Ambil deskripsi gambar dari form

    // Hasilkan slug dari judul
    $slug = generateSlug($judul);

    // Dapatkan tanggal dan waktu saat ini
    $tanggal = date("Y-m-d H:i:s");

    // Proses upload gambar
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $imageName = basename($_FILES['image']['name']);
        $uploadDir = __DIR__ . '/../uploads/';
        $uploadFile = $uploadDir . $imageName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
            $imagePath = 'uploads/' . $imageName;
        }
    } else {
        $imagePath = ''; // Tidak ada gambar
    }

    // Simpan berita ke dalam file
    $newsFile = __DIR__ . '/../data/news/' . $slug . '.json'; // Gunakan slug untuk nama file
    $newsData = [
        'judul' => $judul,
        'slug' => $slug, // Tambahkan slug ke data berita
        'kategori' => $kategori,
        'tanggal' => $tanggal, // Gunakan tanggal otomatis dengan waktu
        'image' => $imagePath,
        'image_description' => $imageDescription, // Simpan deskripsi gambar
        'konten' => $konten,
        'tag' => array_map('trim', $tag)
    ];

    // Simpan data berita ke file JSON
    file_put_contents($newsFile, json_encode($newsData, JSON_PRETTY_PRINT));

    // Redirect ke dashboard setelah berita disimpan
    header('Location: dashboard.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Create 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> - Create News <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_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>
        <form action="add_news.php" method="post"  enctype="multipart/form-data">
        <div class="mb-3">
            <label class="form-label">Title</label>
            <input class="form-control" type="text" name="judul" required>
        </div>
        <div class="mb-3">
            <div class="form-group">
        <label class="form-label">Category</label>
            <select class="form-control" id="kategori" name="kategori" required>
                <option value="" disabled selected>Select Category</option>
                <?php foreach ($kategoriData as $kategori): ?>
                    <option value="<?php echo htmlspecialchars($kategori); ?>"><?php echo htmlspecialchars($kategori); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        </div>
        <div class="mb-3">
            <label class="form-label">Date</label>
            <input class="form-control" type="date" name="tanggal" required>
        </div>
        <div class="mb-3">
            <label class="form-label" for="image">Upload Image</label>
            <input class="form-control" type="file" id="image" name="image" accept="uploads/*">
        </div>
        <div class="mb-3">
            <label class="form-label" for="image_description">Deskripsi Gambar:</label>
            <textarea class="form-control" name="image_description" id="image_description"></textarea>
        </div>
        <div class="mb-3">
        <label>Content</label>
            <textarea id="mytextarea" class="form-control" name="konten" required></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="mb-3">
        <label class="form-label">Tags (Separate with commas)</label>
            <input class="form-control" type="text" name="tag">
        </div>
        <button class="btn btn-success" onsubmit="return validateForm();" type="submit">Save</button>
    </form>
    </div>
</div>
</div>
</div>
</body>
</html>
