<?php
include 'auth_check.php';
include '../config/koneksi.php';
include '../config/functions.php';

$page_title = "Tulis Berita";
$id = "";
$judul = "";
$konten = "";
$tanggal_terbit = date('Y-m-d');
$gambar = "";
$is_edit = false;

// Cek apakah mode edit
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $query = mysqli_query($koneksi, "SELECT * FROM berita WHERE id_berita = '$id'");
    if (mysqli_num_rows($query) > 0) {
        $data = mysqli_fetch_assoc($query);
        $judul = $data['judul'];
        $konten = $data['konten'];
        $tanggal_terbit = $data['tanggal_terbit'];
        $gambar = $data['gambar'];
        $page_title = "Edit Berita";
        $is_edit = true;
    } else {
        echo "<script>alert('Data tidak ditemukan!'); window.location='kelola_berita.php';</script>";
        exit;
    }
}

// Proses Submit
if (isset($_POST['submit'])) {
    $judul = cleanInput($_POST['judul']);
    // Konten tidak di-cleanInput ketat karena mungkin butuh tag HTML dasar jika pakai WYSIWYG nanti,
    // tapi untuk sekarang kita aman pakai mysqli_real_escape_string dulu di bawah.
    $konten = mysqli_real_escape_string($koneksi, $_POST['konten']); 
    $tanggal_terbit = cleanInput($_POST['tanggal_terbit']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $judul)));

    // Validasi sederhana
    if (empty($judul) || empty($konten)) {
        $error = "Judul dan Konten wajib diisi!";
    } else {
        // Upload Foto
        $gambar_baru = "";
        
        if ($_FILES['gambar']['error'] === 0) {
            $upload = uploadImage($_FILES['gambar'], "../uploads/berita/");
            
            if (strpos($upload, ' ') !== false) {
                 $error = "Gagal upload: " . $upload;
            } else {
                $gambar_baru = $upload;
            }
        } elseif ($_FILES['gambar']['error'] === 4) {
            // Tidak ada file yg diupload
            if (!$is_edit) {
                 $error = "Gambar wajib diupload untuk berita baru!";
            }
        } else {
             $error = "Terjadi error saat upload gambar.";
        }
        
        if (!isset($error)) {
            if ($is_edit) {
                // Update
                if (!empty($gambar_baru)) {
                    // Hapus gambar lama
                    if ($gambar != '' && file_exists("../uploads/berita/" . $gambar)) {
                        unlink("../uploads/berita/" . $gambar);
                    }
                    $q_update = "UPDATE berita SET judul='$judul', slug='$slug', konten='$konten', tanggal_terbit='$tanggal_terbit', gambar='$gambar_baru' WHERE id_berita='$id'";
                } else {
                    $q_update = "UPDATE berita SET judul='$judul', slug='$slug', konten='$konten', tanggal_terbit='$tanggal_terbit' WHERE id_berita='$id'";
                }
                
                if (mysqli_query($koneksi, $q_update)) {
                    echo "<script>alert('Berita berhasil diperbarui!'); window.location='kelola_berita.php';</script>";
                    exit;
                } else {
                    $error = "Gagal update data: " . mysqli_error($koneksi);
                }
            } else {
                // Insert
                if (empty($gambar_baru)) {
                     $error = "Silahkan upload gambar.";
                } else {
                    $id_admin = $_SESSION['id_admin']; // Ambil ID admin dari session
                    $q_insert = "INSERT INTO berita (judul, slug, konten, gambar, tanggal_terbit, id_admin) VALUES ('$judul', '$slug', '$konten', '$gambar_baru', '$tanggal_terbit', '$id_admin')";
                    if (mysqli_query($koneksi, $q_insert)) {
                        echo "<script>alert('Berita berhasil diterbitkan!'); window.location='kelola_berita.php';</script>";
                        exit;
                    } else {
                         $error = "Gagal terbit berita: " . mysqli_error($koneksi);
                    }
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title; ?> - Admin Dashboard</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .admin-container { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background-color: var(--primary-color); color: var(--white); display: flex; flex-direction: column; }
        .sidebar-header { padding: 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-menu { list-style: none; padding: 20px 0; flex: 1; }
        .sidebar-menu li a { display: block; padding: 15px 20px; color: #ecf0f1; text-decoration: none; transition: background 0.3s; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background-color: var(--accent-color); }
        .sidebar-menu li a i { width: 25px; }
        .main-content { flex: 1; background-color: #f4f6f9; padding: 30px; }
        
        .card-form { background: var(--white); padding: 30px; border-radius: 10px; box-shadow: var(--shadow); max-width: 800px; margin: 0 auto; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #333; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-size: 1rem; }
        textarea.form-control { height: 300px; resize: vertical; }
        .btn-submit { background-color: var(--accent-color); color: white; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1rem; }
        .btn-submit:hover { background-color: #2980b9; }
        .btn-back { background-color: #95a5a6; color: white; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; font-size: 1rem; margin-right: 10px; }
        .alert-error { background-color: #e74c3c; color: white; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .preview-img { max-width: 200px; margin-top: 10px; border-radius: 5px; border: 1px solid #ddd; padding: 5px; }
    </style>
</head>
<body>

<div class="admin-container">
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>Admin Panel</h3>
        </div>
        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
            <li><a href="kelola_profil.php"><i class="fas fa-info-circle"></i> Profil Desa</a></li>
            <li><a href="kelola_perangkat.php"><i class="fas fa-users-cog"></i> Perangkat Desa</a></li>
            <li><a href="kelola_potensi.php"><i class="fas fa-landmark"></i> Potensi Desa</a></li>
            <li><a href="kelola_berita.php" class="active"><i class="fas fa-newspaper"></i> Berita</a></li>
            <li><a href="kelola_galeri.php"><i class="fas fa-images"></i> Galeri</a></li>
            <li><a href="kelola_slider.php"><i class="fas fa-desktop"></i> Kelola Slider</a></li>
            <li><a href="pengaturan_akun.php"><i class="fas fa-user-cog"></i> Pengaturan Akun</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="card-form">
            <h2><?= $page_title; ?></h2>
            <hr style="margin-bottom: 20px; border: 0; border-top: 1px solid #eee;">
            
            <?php if (isset($error)): ?>
                <div class="alert-error"><?= $error; ?></div>
            <?php endif; ?>
            
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="judul">Judul Berita</label>
                    <input type="text" name="judul" id="judul" class="form-control" value="<?= htmlspecialchars($judul); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="tanggal_terbit">Tanggal Terbit</label>
                    <input type="date" name="tanggal_terbit" id="tanggal_terbit" class="form-control" value="<?= $tanggal_terbit; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="konten">Konten Berita</label>
                    <textarea name="konten" id="konten" class="form-control" required><?= htmlspecialchars($konten); ?></textarea>
                </div>
                
                <div class="form-group">
                    <label for="gambar">Gambar Utama</label>
                    <input type="file" name="gambar" id="gambar" class="form-control" accept="image/*" <?= $is_edit ? '' : 'required'; ?>>
                    <?php if ($is_edit && !empty($gambar) && file_exists("../uploads/berita/" . $gambar)): ?>
                        <div style="margin-top: 10px;">
                            <p>Gambar Saat Ini:</p>
                            <img src="../uploads/berita/<?= $gambar; ?>" class="preview-img">
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="form-group" style="margin-top: 30px;">
                    <a href="kelola_berita.php" class="btn-back"><i class="fas fa-arrow-left"></i> Kembali</a>
                    <button type="submit" name="submit" class="btn-submit"><i class="fas fa-save"></i> Simpan / Terbitkan</button>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>
