<?php
$isEdit = !empty($berita);
$pageTitle = $isEdit ? 'Edit Berita' : 'Tulis Berita';
$action = $isEdit ? APP_URL . '/admin/berita/' . $berita['id'] : APP_URL . '/admin/berita';
$tanggalValue = $isEdit && !empty($berita['tanggal'])
    ? date('Y-m-d\TH:i', strtotime($berita['tanggal']))
    : date('Y-m-d\TH:i');
?>
<?php require BASE_PATH . '/app/Views/admin/layouts/header.php'; ?>

<div class="page-head">
  <h2><?= $isEdit ? 'Edit Berita' : 'Tulis Berita Baru' ?></h2>
  <a href="<?= APP_URL ?>/admin/berita" class="btn btn-secondary">Kembali</a>
</div>

<div class="card" style="max-width:860px;">
  <form method="POST" action="<?= $action ?>" enctype="multipart/form-data">
    <?= \App\Core\Csrf::field() ?>

    <div class="form-group">
      <label for="judul">Judul Berita</label>
      <input type="text" id="judul" name="judul" class="form-control" required
             value="<?= htmlspecialchars($berita['judul'] ?? '') ?>" placeholder="Judul berita...">
    </div>

    <div class="form-group">
      <label for="slug">Slug (URL)</label>
      <input type="text" id="slug" name="slug" class="form-control"
             value="<?= htmlspecialchars($berita['slug'] ?? '') ?>" placeholder="otomatis dari judul kalau dikosongkan">
      <p class="hint">Akan tampil sebagai: <?= APP_URL ?>/berita/<span id="slug-preview"><?= htmlspecialchars($berita['slug'] ?? '') ?></span></p>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label for="kategori_id">Kategori</label>
        <select id="kategori_id" name="kategori_id" class="form-control">
          <option value="">Tanpa kategori</option>
          <?php foreach ($kategori as $k): ?>
            <option value="<?= $k['id'] ?>" <?= (!empty($berita['kategori_id']) && (int) $berita['kategori_id'] === (int) $k['id']) ? 'selected' : '' ?>>
              <?= htmlspecialchars($k['nama']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label for="penulis">Penulis</label>
        <input type="text" id="penulis" name="penulis" class="form-control"
               value="<?= htmlspecialchars($berita['penulis'] ?? ($admin['nama'] ?? '')) ?>">
      </div>
    </div>

    <div class="form-group">
      <label for="ringkasan">Ringkasan Singkat</label>
      <textarea id="ringkasan" name="ringkasan" class="form-control" rows="2" placeholder="Muncul di kartu berita & preview (opsional)"><?= htmlspecialchars($berita['ringkasan'] ?? '') ?></textarea>
    </div>

    <div class="form-group">
      <label for="konten">Isi Berita</label>
      <textarea id="konten" name="konten"><?= $berita['konten'] ?? '' ?></textarea>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label for="status">Status</label>
        <select id="status" name="status" class="form-control">
          <option value="draft" <?= (($berita['status'] ?? 'draft') === 'draft') ? 'selected' : '' ?>>Draft</option>
          <option value="terbit" <?= (($berita['status'] ?? '') === 'terbit') ? 'selected' : '' ?>>Terbit</option>
        </select>
      </div>
      <div class="form-group">
        <label for="tanggal">Tanggal Terbit</label>
        <input type="datetime-local" id="tanggal" name="tanggal" class="form-control" value="<?= $tanggalValue ?>">
      </div>
    </div>

    <div class="form-group">
      <label for="thumbnail">Thumbnail</label>
      <?php if ($isEdit && !empty($berita['thumbnail'])): ?>
        <div style="margin-bottom:10px;">
          <img src="<?= APP_URL . '/uploads/berita/' . htmlspecialchars($berita['thumbnail']) ?>" alt="" style="width:160px; border-radius:8px; display:block;">
        </div>
      <?php endif; ?>
      <input type="file" id="thumbnail" name="thumbnail" class="form-control" accept="image/jpeg,image/png,image/webp">
      <p class="hint">Format JPG/PNG/WEBP, maksimal 2MB. <?= $isEdit ? 'Kosongkan kalau tidak ingin mengganti.' : '' ?></p>
    </div>

    <button type="submit" class="btn"><?= $isEdit ? 'Simpan Perubahan' : 'Publikasikan' ?></button>
  </form>
</div>

<!-- TinyMCE — CDN gratis. Ganti "no-api-key" dengan API key gratis dari https://www.tiny.cloud
     agar tidak muncul watermark peringatan di editor saat produksi. -->
<script src="https://cdn.tiny.cloud/1/asv1ccmdos5ku7aiipbb5do6l68ekdc4k2vk85p0bc8sthud/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#konten',
    height: 420,
    menubar: false,
    plugins: 'lists link image table code fullscreen media',
    toolbar: 'undo redo | blocks | bold italic underline | bullist numlist | link image media table | code fullscreen',
    branding: false,
    content_style: 'body { font-family: Inter, sans-serif; font-size: 14px; }'
  });

  // Auto-slug dari judul (hanya kalau slug belum diisi manual)
  (function () {
    var judul = document.getElementById('judul');
    var slug = document.getElementById('slug');
    var preview = document.getElementById('slug-preview');
    var slugTouched = slug.value.length > 0;

    slug.addEventListener('input', function () { slugTouched = true; });

    function slugify(text) {
      return text.toLowerCase().trim()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
    }

    judul.addEventListener('input', function () {
      if (!slugTouched) {
        var s = slugify(judul.value);
        slug.value = s;
        preview.textContent = s;
      }
    });

    slug.addEventListener('input', function () {
      preview.textContent = slugify(slug.value);
    });
  })();
</script>

<?php require BASE_PATH . '/app/Views/admin/layouts/footer.php'; ?>
