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

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

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

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

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

    // 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 halaman ke dalam file
    $pageFile = __DIR__ . '/../data/pages/' . $slug . '.json'; // Gunakan slug untuk nama file
    $pageData = [
        'judul' => $judul,
        'slug' => $slug, // Tambahkan slug ke data halaman
        'image' => $imagePath,
        'image_description' => $imageDescription, // Simpan deskripsi gambar
        'konten' => $konten
    ];

    // Simpan data halaman ke file JSON
    file_put_contents($pageFile, json_encode($pageData, JSON_PRETTY_PRINT));

    // Redirect ke dashboard setelah halaman 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 Page - KoeasCMS</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">
<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 Page <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>

<form action="add_page.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">
        <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() {
                tinymce.triggerSave();
                var konten = document.getElementById('mytextarea').value;
                if (konten == "") {
                    alert("Konten tidak boleh kosong!");
                    return false;
                }
                return true;
            }

            tinymce.init({
                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>
    <button class="btn btn-success" onsubmit="return validateForm();" type="submit">Save</button>
</form>

</div>
</div>
</div>
</div>
</body>
</html>
