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

if (!function_exists('e')) {
  function e($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
}

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

function delete_file_lampiran($dir, $filename) {
  if ($filename && file_exists($dir . $filename)) {
    @unlink($dir . $filename);
  }
}

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

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

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

/* TAMBAH */
if (isset($_POST['add'])) {
  $lampiran_name = null;
  if (!empty($_FILES['file_lampiran']['name'])) {
    $allowed = ['pdf','doc','docx'];
    $ext  = strtolower(pathinfo($_FILES['file_lampiran']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['file_lampiran']['size'];
    if (!in_array($ext, $allowed)) {
      echo "<script>Swal.fire('Gagal','Format lampiran tidak diizinkan!','error');</script>";
      goto end_add;
    }
    if ($size > 5 * 1024 * 1024) {
      echo "<script>Swal.fire('Gagal','Lampiran maksimal 5MB!','error');</script>";
      goto end_add;
    }
    $lampiran_name = time() . '_lamp_' . uniqid() . '.' . $ext;
    move_uploaded_file($_FILES['file_lampiran']['tmp_name'], $lampiran_dir . $lampiran_name);
  }

  $judul = $_POST['judul'] ?? '';
  $slug  = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $judul), '-'));

  $stmt = $pdo->prepare("
    INSERT INTO pengumuman
      (judul, slug, isi, file_lampiran, tanggal_mulai, tanggal_selesai, prioritas, target_audience, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  ");
  $stmt->execute([
    $judul, $slug,
    $_POST['isi'] ?? '',
    $lampiran_name,
    $_POST['tanggal_mulai'] ?? date('Y-m-d'),
    $_POST['tanggal_selesai'] ?? date('Y-m-d'),
    $_POST['prioritas'] ?? 'normal',
    $_POST['target_audience'] ?: 'umum',
    $_POST['status'] ?? 'active',
  ]);

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

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

  $stmt_old = $pdo->prepare("SELECT file_lampiran FROM pengumuman WHERE id=?");
  $stmt_old->execute([$edit_id]);
  $old = $stmt_old->fetch(PDO::FETCH_ASSOC);
  $lampiran_old  = $old['file_lampiran'] ?? null;
  $lampiran_name = $lampiran_old;

  if (!empty($_FILES['file_lampiran']['name'])) {
    delete_file_lampiran($lampiran_dir, $lampiran_old);
    $allowed = ['pdf','doc','docx'];
    $ext  = strtolower(pathinfo($_FILES['file_lampiran']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['file_lampiran']['size'];
    if (!in_array($ext, $allowed)) {
      echo "<script>Swal.fire('Gagal','Format lampiran tidak diizinkan!','error');</script>";
      goto end_update;
    }
    if ($size > 5 * 1024 * 1024) {
      echo "<script>Swal.fire('Gagal','Lampiran maksimal 5MB!','error');</script>";
      goto end_update;
    }
    $lampiran_name = time() . '_lamp_' . uniqid() . '.' . $ext;
    move_uploaded_file($_FILES['file_lampiran']['tmp_name'], $lampiran_dir . $lampiran_name);
  }

  $judul = $_POST['judul'] ?? '';
  $slug  = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $judul), '-'));

  $stmt = $pdo->prepare("
    UPDATE pengumuman
    SET judul=?, slug=?, isi=?, file_lampiran=?,
        tanggal_mulai=?, tanggal_selesai=?,
        prioritas=?, target_audience=?, status=?
    WHERE id=?
  ");
  $stmt->execute([
    $judul, $slug,
    $_POST['isi'] ?? '',
    $lampiran_name,
    $_POST['tanggal_mulai'] ?? date('Y-m-d'),
    $_POST['tanggal_selesai'] ?? date('Y-m-d'),
    $_POST['prioritas'] ?? 'normal',
    $_POST['target_audience'] ?: 'umum',
    $_POST['status'] ?? 'active',
    $edit_id,
  ]);

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

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

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

    <!-- FORM -->
    <form method="post" enctype="multipart/form-data">
      <?php if ($mode === 'edit'): ?>
        <input type="hidden" name="edit_id" value="<?= e($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="judul" class="form-control"
               value="<?= e($row['judul'] ?? '') ?>" required>
      </div>

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

      <!-- Tanggal -->
      <div class="row mb-3">
        <div class="col-md-6">
          <label class="form-label fw-semibold">Tanggal Mulai <span class="text-danger">*</span></label>
          <input type="date" name="tanggal_mulai" class="form-control"
                 value="<?= e($row['tanggal_mulai'] ?? '') ?>" required>
        </div>
        <div class="col-md-6">
          <label class="form-label fw-semibold">Tanggal Selesai <span class="text-danger">*</span></label>
          <input type="date" name="tanggal_selesai" class="form-control"
                 value="<?= e($row['tanggal_selesai'] ?? '') ?>" required>
        </div>
      </div>

      <!-- Prioritas / Status / Sasaran -->
      <div class="row mb-3">
        <div class="col-md-4">
          <label class="form-label fw-semibold">Prioritas</label>
          <select name="prioritas" class="form-select">
            <?php foreach (['normal'=>'Normal','rendah'=>'Rendah','tinggi'=>'Tinggi','urgent'=>'Urgent'] as $val => $label): ?>
              <option value="<?= $val ?>" <?= ($row['prioritas'] ?? 'normal') === $val ? 'selected' : '' ?>>
                <?= $label ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label fw-semibold">Status</label>
          <select name="status" class="form-select">
            <?php foreach (['active'=>'Active','inactive'=>'Inactive','expired'=>'Expired'] as $val => $label): ?>
              <option value="<?= $val ?>" <?= ($row['status'] ?? 'active') === $val ? 'selected' : '' ?>>
                <?= $label ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label fw-semibold">Sasaran</label>
          <input type="text" name="target_audience" class="form-control"
                 value="<?= e($row['target_audience'] ?? '') ?>"
                 placeholder="umum/mahasiswa/dosen">
        </div>
      </div>

      <!-- Lampiran -->
      <div class="mb-4">
        <label class="form-label fw-semibold">
          File Lampiran <?= $mode === 'edit' ? '(Baru - Opsional)' : '(Opsional, PDF/DOC)' ?>
        </label>
        <?php if ($mode === 'edit' && !empty($row['file_lampiran'])): ?>
          <div class="mb-2 text-muted small">
            Lampiran saat ini:
            <a href="../uploads/pengumuman/<?= e($row['file_lampiran']) ?>" target="_blank">
              <?= e($row['file_lampiran']) ?>
            </a>
          </div>
        <?php endif; ?>
        <input type="file" name="file_lampiran" class="form-control" accept=".pdf,.doc,.docx">
      </div>

      <!-- Tombol -->
      <div class="d-flex gap-2">
        <a href="pengumuman.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: '#isi',
    height: 400,
    menubar: true,
    plugins: 'link lists table code image autoresize',
    toolbar: 'undo redo | bold italic underline | bullist numlist | link image | table | code',
    branding: false,
    promotion: false,
    link_default_target: '_blank',
    convert_urls: false,
    setup: function(editor) {
        editor.on('change', function() {
            tinymce.triggerSave();
        });
    }
});
</script>

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