<?php
require "../fungsi.php";

// Cek apakah `id` berita ada di URL
if (!isset($_GET['id'])) {
    echo "<div class='alert alert-danger' role='alert'>ID berita tidak ditemukan!</div>";
    exit;
}

$id = intval($_GET['id']); // Ambil ID berita dan konversi ke integer

// Ambil data berita dari database
$query = "SELECT * FROM news WHERE id = ?";
$stmt = executeQuery($conn, $query, "i", [$id]);
$news = $stmt->get_result()->fetch_assoc();

// Jika berita tidak ditemukan
if (!$news) {
    echo "<div class='alert alert-danger' role='alert'>Berita tidak ditemukan!</div>";
    exit;
}

// Proses update jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = stripslashes($_POST['title']);
    $content = stripslashes($_POST['content']);
    $author_id = $_SESSION['user_id']; //intval($_POST['author_id']);
    $status = stripslashes($_POST['status']);
    $updated_at = date('Y-m-d H:i:s'); // Waktu update

    // Validasi judul berita (tidak boleh duplikasi kecuali judul yang sedang diupdate)
    $query = "SELECT COUNT(*) AS count FROM news WHERE title = ? AND id != ?";
    $stmt = executeQuery($conn, $query, "si", [$title, $id]);
    $result = $stmt->get_result()->fetch_assoc();

    if ($result['count'] > 0) {
        echo "<div class='alert alert-danger' role='alert'>Judul berita sudah digunakan!</div>";
    } else {
        // Update data berita
        $query = "UPDATE news SET title = ?, content = ?, author_id = ?, updated_at = ?, status= ? WHERE id = ?";
        $success = executeQuery($conn, $query, "ssissi", [$title, $content, $author_id,  $updated_at, $status, $id]);

        if ($success) {
            /*echo "<div class='alert alert-success' role='alert'>Berita berhasil diperbarui. 
            <a href='?page=news'>Lihat berita</a></div>";*/
            echo "<script>            
            alert('Data berhasil diperbarui!');
            window.location.href = '?page=news';
          </script>";
        } else {
            echo "Gagal memperbarui berita: " . $conn->error;
        }
    }
}
?>
<!-- Begin Page Content -->
<div class="container-fluid">

    <!-- Page Heading -->
    <h1 class="h3 mb-4 text-gray-800">Edit Berita</h1>

    <!-- Form Edit Berita -->
    <form action="" method="POST">
        <div class="form-group">
            <label for="title">Judul Berita</label>
            <input type="text" class="form-control" id="title" name="title" value="<?= htmlspecialchars($news['title']); ?>" required>
        </div>
        <div class="form-group">
            <label for="content">Isi Berita</label>
            <textarea class="form-control" id="content" name="content" rows="5" required><?= htmlspecialchars($news['content']); ?></textarea>
        </div>
        <!--<div class="form-group">
            <label for="author_id">ID Penulis</label>
            <input type="number" class="form-control" id="author_id" name="author_id" value="<? //= $news['author_id']; 
                                                                                                ?>" required>
        </div>-->
        <div class="form-group">
            <label for="status">Status</label>
            <select class="form-control" id="status" name="status" required>
                <option value="pending" <?= $news['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="approved" <?= $news['status'] == 'approved' ? 'selected' : ''; ?>>Approved</option>
                <option value="rejected" <?= $news['status'] == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
        <a href="javascript:history.back()" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Kembali
        </a>
    </form>

</div>
<!-- /.container-fluid -->

<!-- TinyMCE Script -->
<script src="https://cdn.tiny.cloud/1/j2ntfmgnjwvnjrvkb9u0nhv8n0swfgllrnrfhlgru5mi5res/tinymce/7/tinymce.min.js" referrerpolicy="origin"></script>
<script>
    tinymce.init({
        selector: 'textarea',
        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',
        setup: function(editor) {
            editor.on('change', function() {
                tinymce.triggerSave(); // Sinkronkan konten TinyMCE ke <textarea>
            });
        }
    });

    // Tambahkan listener untuk form submit
    document.querySelector('form').addEventListener('submit', function(e) {
        tinymce.triggerSave(); // Pastikan konten editor disimpan ke dalam <textarea>
    });
</script>