<?php
// admin/berita/tambah.php
$pageTitle = 'Tambah Berita';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Aktifkan error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Inisialisasi variabel error
$errors = [];

// Proses form jika ada submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Debugging - cek POST data
    // echo "<pre>"; print_r($_POST); echo "</pre>";
    // echo "<pre>"; print_r($_FILES); echo "</pre>";
    
    // Ambil data dari form
    $judul = sanitize($_POST['judul'] ?? '');
    $konten = $_POST['konten'] ?? ''; // Tidak perlu sanitize karena konten HTML
    
    // Validasi data
    if (empty($judul)) {
        $errors[] = 'Judul berita tidak boleh kosong';
    }
    
    if (empty($konten)) {
        $errors[] = 'Konten berita tidak boleh kosong';
    }
    
    // Proses upload gambar jika ada
    $gambar = 'default.jpg'; // Default gambar
    if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] == 0) {
        $upload_dir = UPLOAD_DIR . 'berita/';
        // Pastikan direktori ada
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $upload_result = uploadFile($_FILES['gambar'], $upload_dir, 'gambar');
        if ($upload_result) {
            $gambar = $upload_result;
        } else {
            $errors[] = 'Gagal mengupload gambar';
        }
    }
    
    // Jika tidak ada error, simpan data ke database
    if (empty($errors)) {
        try {
            // Mulai transaction
            $db->beginTransaction();
            
            // Insert data berita baru
            $db->query("INSERT INTO berita (judul, konten, gambar, created_by) 
                      VALUES (:judul, :konten, :gambar, :created_by)");
            $db->bind(':judul', $judul);
            $db->bind(':konten', $konten);
            $db->bind(':gambar', $gambar);
            $db->bind(':created_by', $_SESSION['user_id']);
            
            if ($db->execute()) {
                $berita_id = $db->lastInsertId();
                
                // Log aktivitas
                logActivity('Menambah berita baru', 'berita', $berita_id, "Admin menambahkan berita baru: $judul");
                
                // Commit transaction
                $db->endTransaction();
                
                setFlash('berita', 'Berita berhasil ditambahkan', 'success');
                header('Location: ' . SITE_URL . '/admin/berita/index.php');
                exit;
            } else {
                // Rollback transaction
                $db->cancelTransaction();
                $errors[] = 'Gagal menambahkan berita: ' . $db->error();
            }
        } catch (Exception $e) {
            // Rollback transaction
            $db->cancelTransaction();
            $errors[] = 'Terjadi kesalahan: ' . $e->getMessage();
        }
    }
}

// Include header admin
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <?php require_once '../../includes/sidebar-admin.php'; ?>
        
        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Tambah Berita</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/admin/berita/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?= $error ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <?php flash(); ?>

            <!-- Form Tambah Berita -->
            <div class="card">
                <div class="card-body">
                    <form action="<?= SITE_URL ?>/admin/berita/tambah.php" method="post" enctype="multipart/form-data" id="formBerita">
                        <div class="mb-3">
                            <label for="judul" class="form-label">Judul Berita</label>
                            <input type="text" class="form-control" id="judul" name="judul" value="<?= $_POST['judul'] ?? '' ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="gambar" class="form-label">Gambar Berita</label>
                            <input type="file" class="form-control image-upload" id="gambar" name="gambar" data-preview="gambar-preview" accept="image/*">
                            <div class="form-text">Format gambar: JPG, JPEG, PNG. Ukuran maksimal: 2MB. Disarankan rasio 16:9.</div>
                            <div class="mt-2">
                                <img id="gambar-preview" src="<?= SITE_URL ?>/assets/uploads/berita/default.jpg" class="img-thumbnail" alt="Preview" style="max-height: 200px;">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="konten" class="form-label">Konten Berita</label>
                            <textarea class="form-control" id="konten" name="konten" rows="10"><?= $_POST['konten'] ?? '' ?></textarea>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="submit" class="btn btn-success" id="btnSimpan">
                                <i class="fas fa-save me-1"></i> Simpan
                            </button>
                            <a href="<?= SITE_URL ?>/admin/berita/index.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Batal
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Include CKEditor -->
<script src="https://cdn.ckeditor.com/ckeditor5/35.0.1/classic/ckeditor.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        let editor;
        
        // Inisialisasi CKEditor
        ClassicEditor
            .create(document.querySelector('#konten'), {
                toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'outdent', 'indent', '|', 'blockQuote', 'insertTable', 'undo', 'redo']
            })
            .then(newEditor => {
                editor = newEditor;
                console.log('CKEditor initialized successfully');
            })
            .catch(error => {
                console.error('Error initializing CKEditor:', error);
            });
            
        // Preview gambar sebelum upload
        const imageInputs = document.querySelectorAll('.image-upload');
        imageInputs.forEach(function(input) {
            input.addEventListener('change', function(event) {
                const preview = document.getElementById(this.dataset.preview);
                if (preview && this.files && this.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        preview.src = e.target.result;
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            });
        });
        
        // Handle form submission
        const form = document.getElementById('formBerita');
        const btnSimpan = document.getElementById('btnSimpan');
        
        form.addEventListener('submit', function(e) {
            // e.preventDefault();
            console.log('Form submitted');
            btnSimpan.disabled = true;
            btnSimpan.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Menyimpan...';
        });
    });
</script>

<?php require_once '../../includes/footer.php'; ?>