<?php
require_once __DIR__ . '/../config/secure_bootstrap.php';
include __DIR__ . '/includes/header.php';

$upload_dir = __DIR__ . '/../uploads/berita/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

// Mode: add atau edit
$mode = $_GET['mode'] ?? 'add';
$id   = (int)($_GET['id'] ?? 0);
$row  = null;

if ($mode === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM news WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        echo "<script>alert('Data tidak ditemukan.');location.href='berita.php';</script>";
        exit;
    }
}

// ====== Fungsi slug ======
function generateSlug($pdo, $title, $exclude_id = null) {
    $slug_base = strtolower(trim(preg_replace('/[^a-z0-9]+/', '-', $title), '-'));
    if ($slug_base === '') $slug_base = 'berita-' . time();
    $slug = $slug_base;
    $counter = 1;
    while (true) {
        $sql = "SELECT COUNT(*) FROM news WHERE slug = ?";
        $params = [$slug];
        if ($exclude_id) { $sql .= " AND id != ?"; $params[] = $exclude_id; }
        $check = $pdo->prepare($sql);
        $check->execute($params);
        if ($check->fetchColumn() == 0) break;
        $slug = $slug_base . '-' . $counter++;
    }
    return $slug;
}

// ====== PROSES SIMPAN ======

/* TAMBAH */
if (isset($_POST['add'])) {
    $file_name = null;
    if (!empty($_FILES['featured_image']['name'])) {
        $allowed = ['jpg','jpeg','png','webp'];
        $ext = strtolower(pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            echo "<script>Swal.fire('Gagal','Format gambar tidak diizinkan! Gunakan JPG/PNG.','error');</script>";
            goto end_add;
        }
        if ($_FILES['featured_image']['size'] > 3 * 1024 * 1024) {
            echo "<script>Swal.fire('Gagal','Ukuran gambar maksimal 3MB!','error');</script>";
            goto end_add;
        }
        $clean = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', basename($_FILES['featured_image']['name']));
        $file_name = time() . '_' . $clean;
        move_uploaded_file($_FILES['featured_image']['tmp_name'], $upload_dir . $file_name);
    }

    $slug = generateSlug($pdo, $_POST['title'] ?? '');

    $stmt = $pdo->prepare("INSERT INTO news (title, slug, excerpt, content, featured_image, status, author_id, published_at)
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['title'] ?? '',
        $slug,
        $_POST['excerpt'] ?? '',
        $_POST['content'] ?? '',
        $file_name,
        $_POST['status'] ?? 'draft',
        $_SESSION['user_id'] ?? null,
        (($_POST['status'] ?? '') === 'published' ? date('Y-m-d H:i:s') : null),
    ]);

    echo "<script>Swal.fire('Berhasil','Berita berhasil ditambahkan','success')
          .then(()=>location.href='berita.php');</script>";
    exit;
    end_add:
}

/* UPDATE */
if (isset($_POST['update'])) {
    $edit_id = (int)($_POST['edit_id'] ?? 0);
    if (!$edit_id) { header('Location: berita.php'); exit; }

    // Ambil gambar lama
    $old_stmt = $pdo->prepare("SELECT featured_image FROM news WHERE id = ?");
    $old_stmt->execute([$edit_id]);
    $old_image = $old_stmt->fetchColumn();
    $file_name = $old_image;

    if (!empty($_FILES['featured_image']['name'])) {
        $allowed = ['jpg','jpeg','png','webp'];
        $ext = strtolower(pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            echo "<script>Swal.fire('Gagal','Format gambar tidak diizinkan! Gunakan JPG/PNG.','error');</script>";
            goto end_update;
        }
        if ($_FILES['featured_image']['size'] > 3 * 1024 * 1024) {
            echo "<script>Swal.fire('Gagal','Ukuran gambar maksimal 3MB!','error');</script>";
            goto end_update;
        }
        // Hapus gambar lama
        if ($old_image && file_exists($upload_dir . $old_image)) {
            @unlink($upload_dir . $old_image);
        }
        $clean = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', basename($_FILES['featured_image']['name']));
        $file_name = time() . '_' . $clean;
        move_uploaded_file($_FILES['featured_image']['tmp_name'], $upload_dir . $file_name);
    }

    $slug = generateSlug($pdo, $_POST['title'] ?? '', $edit_id);

    $stmt = $pdo->prepare("UPDATE news
                           SET title=?, slug=?, excerpt=?, content=?, featured_image=?,
                               status=?, updated_at=NOW(), published_at=?
                           WHERE id=?");
    $stmt->execute([
        $_POST['title'] ?? '',
        $slug,
        $_POST['excerpt'] ?? '',
        $_POST['content'] ?? '',
        $file_name,
        $_POST['status'] ?? 'draft',
        (($_POST['status'] ?? '') === 'published' ? date('Y-m-d H:i:s') : null),
        $edit_id,
    ]);

    echo "<script>Swal.fire('Berhasil','Berita berhasil diperbarui','success')
          .then(()=>location.href='berita.php');</script>";
    exit;
    end_update:
}
?>

<div class="container-fluid">
  <div class="card shadow border-0 rounded-4 p-4 mb-4" style="max-width:900px;margin:auto;">

    <!-- Header -->
    <div class="d-flex align-items-center mb-4 gap-3">
      <a href="berita.php" class="btn btn-outline-secondary btn-sm">
        <i class="fa-solid fa-arrow-left me-1"></i> Kembali
      </a>
      <h4 class="mb-0 fw-bold text-success">
        <?php if ($mode === 'edit'): ?>
          <i class="fa-solid fa-pen-to-square me-2"></i>Edit Berita
        <?php else: ?>
          <i class="fa-solid fa-plus me-2"></i>Tambah Berita
        <?php endif; ?>
      </h4>
    </div>

    <!-- FORM -->
    <form method="post" enctype="multipart/form-data">
      <?php if ($mode === 'edit'): ?>
        <input type="hidden" name="edit_id" value="<?= (int)$row['id'] ?>">
      <?php endif; ?>

      <!-- Judul -->
      <div class="mb-3">
        <label class="form-label fw-semibold">Judul <span class="text-danger">*</span></label>
        <input type="text" name="title" class="form-control"
               value="<?= htmlspecialchars($row['title'] ?? '') ?>" required>
      </div>

      <!-- Ringkasan -->
      <div class="mb-3">
        <label class="form-label fw-semibold">Ringkasan</label>
        <textarea name="excerpt" class="form-control" rows="2"><?= htmlspecialchars($row['excerpt'] ?? '') ?></textarea>
      </div>

      <!-- Isi Berita / TinyMCE -->
      <div class="mb-3">
        <label class="form-label fw-semibold">Isi Berita</label>
        <textarea name="content" id="content"><?= htmlspecialchars($row['content'] ?? '') ?></textarea>
      </div>

      <!-- Gambar & Status -->
      <div class="row mb-3">
        <div class="col-md-7">
          <label class="form-label fw-semibold">
            Gambar <?= $mode === 'edit' ? '(Baru - Opsional, JPG/PNG maks. 3MB)' : '(Opsional, JPG/PNG maks. 3MB)' ?>
          </label>
          <?php if ($mode === 'edit' && !empty($row['featured_image'])): ?>
            <div class="mb-2">
              <img src="../uploads/berita/<?= htmlspecialchars($row['featured_image']) ?>"
                   onerror="this.src='../assets/img/no-image.png';"
                   height="80" class="rounded shadow-sm object-fit-cover">
              <div class="small text-muted mt-1">Gambar saat ini: <?= htmlspecialchars($row['featured_image']) ?></div>
            </div>
          <?php endif; ?>
          <input type="file" name="featured_image" class="form-control" accept=".jpg,.jpeg,.png,.webp">
        </div>
        <div class="col-md-5">
          <label class="form-label fw-semibold">Status</label>
          <select name="status" class="form-select">
            <option value="draft"     <?= ($row['status'] ?? 'draft') === 'draft'     ? 'selected' : '' ?>>Draft</option>
            <option value="published" <?= ($row['status'] ?? '') === 'published' ? 'selected' : '' ?>>Published</option>
          </select>
        </div>
      </div>

      <!-- Tombol -->
      <div class="d-flex gap-2 mt-2">
        <a href="berita.php" class="btn btn-secondary">
          <i class="fa-solid fa-xmark me-1"></i> Batal
        </a>
        <?php if ($mode === 'edit'): ?>
          <button type="submit" name="update" class="btn btn-primary">
            <i class="fa-solid fa-floppy-disk me-1"></i> Perbarui
          </button>
        <?php else: ?>
          <button type="submit" name="add" class="btn btn-success">
            <i class="fa-solid fa-floppy-disk me-1"></i> Simpan
          </button>
        <?php endif; ?>
      </div>

    </form>
  </div>
</div>

<!-- TinyMCE langsung di halaman, TANPA modal Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>
<script>
tinymce.init({
    selector: '#content',
    height: 450,
    menubar: true,
    plugins: 'link lists table code image autoresize media',
    toolbar: 'undo redo | bold italic underline strikethrough | bullist numlist | link image | table | alignleft aligncenter alignright | code',
    branding: false,
    promotion: false,
    link_default_target: '_blank',
    convert_urls: false,
    images_upload_url: false,
    setup: function(editor) {
        editor.on('change', function() {
            tinymce.triggerSave();
        });
    }
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>