<?php
// admin/news.php — CRUD Berita (lengkap & aman header)
// ====== BOOTSTRAP (tanpa output HTML lebih dulu) ======
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/db.php';
require_login();

@session_start();
$pdo = db();
$action = $_GET['action'] ?? 'index';

/* -----------------------
   MIGRASI: Tabel news
------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS news (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    slug VARCHAR(255) NOT NULL UNIQUE,
    author VARCHAR(150) DEFAULT NULL,
    publish_date DATE DEFAULT NULL,
    category VARCHAR(255) DEFAULT NULL,
    source VARCHAR(255) DEFAULT NULL,
    photo_path VARCHAR(255) DEFAULT NULL,
    content MEDIUMTEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    INDEX (publish_date),
    INDEX (category)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* -----------------------
   Polyfill utilities
------------------------ */
if (!function_exists('starts_with')) {
  function starts_with($h, $n){ return (string)$n !== '' && strncmp($h, $n, strlen($n)) === 0; }
}
if (!function_exists('is_abs_http')) {
  function is_abs_http($url){ return (bool)preg_match('~^https?://~i', (string)$url); }
}

/* -----------------------
   Paths & Public URL base
------------------------ */
$publicRoot = realpath(__DIR__ . '/../public') ?: (__DIR__ . '/../public');
$docRoot = realpath($_SERVER['DOCUMENT_ROOT'] ?? '');
$publicUrlBase = str_replace('\\', '/', $publicRoot);
$docRootNorm   = str_replace('\\', '/', (string)$docRoot);
if ($docRootNorm && starts_with($publicUrlBase, $docRootNorm)) {
  $publicUrlBase = substr($publicUrlBase, strlen($docRootNorm));
}
$publicUrlBase = '/' . ltrim($publicUrlBase, '/');

// Direktori & URL upload (khusus berita)
$uploadDir = $publicRoot . '/uploads/news';
$uploadUrl = rtrim($publicUrlBase, '/') . '/uploads/news';
if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0775, true); }

/* -----------------------
   Helpers gambar & URL
------------------------ */
function safe_ext_from_mime($tmpFile) {
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  $mime  = $finfo->file($tmpFile);
  $map = ['image/jpeg'=>'.jpg','image/png'=>'.png','image/webp'=>'.webp','image/gif'=>'.gif'];
  return $map[$mime] ?? null;
}
function save_uploaded_image($file, $title, $uploadDir, $uploadUrl) {
  if (!isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) return [null, null];
  if ($file['error'] !== UPLOAD_ERR_OK) return [null, 'Gagal upload (error code '.$file['error'].')'];
  if (($file['size'] ?? 0) > 5*1024*1024) return [null, 'Ukuran gambar maksimal 5MB.'];
  $ext = safe_ext_from_mime($file['tmp_name']);
  if (!$ext) return [null, 'Tipe file tidak didukung. Gunakan JPG/PNG/WEBP/GIF.'];
  $slug = preg_replace('~[^a-z0-9]+~i', '-', $title);
  $slug = trim($slug, '-');
  $name = $slug . '-' . substr(sha1(uniqid('', true)), 0, 10) . $ext;
  $target = $uploadDir . '/' . $name;
  if (!@move_uploaded_file($file['tmp_name'], $target)) return [null, 'Gagal menyimpan file upload.'];
  return [$uploadUrl . '/' . $name, null];
}
function unlink_if_local($publicRoot, $publicUrlBase, $imagePath) {
  if (!$imagePath || is_abs_http($imagePath)) return;
  $rel = $imagePath;
  if (!starts_with($rel, $publicUrlBase)) {
    if (starts_with($rel, '/uploads/')) $rel = rtrim($publicUrlBase, '/') . $rel;
    else $rel = rtrim($publicUrlBase, '/') . '/' . ltrim($rel, '/');
  }
  $full = $publicRoot . $rel;
  if (is_file($full)) @unlink($full);
}
function to_public_url($path, $publicUrlBase) {
  if (empty($path)) return '';
  if (is_abs_http($path)) return $path;
  if (starts_with($path, $publicUrlBase)) return $path;
  if (starts_with($path, '/uploads/')) return rtrim($publicUrlBase, '/') . $path;
  return rtrim($publicUrlBase, '/') . '/' . ltrim($path, '/');
}

/* -----------------------
   Helper: slug unik
------------------------ */
function make_slug($s){
  $slug = strtolower(trim(preg_replace('~[^a-z0-9]+~i', '-', $s), '-'));
  return $slug ?: substr(sha1(uniqid('', true)), 0, 8);
}
function ensure_unique_slug(PDO $pdo, $baseSlug, $excludeId = 0){
  $slug = $baseSlug;
  $i = 1;
  while (true) {
    if ($excludeId) {
      $st = $pdo->prepare("SELECT COUNT(*) FROM news WHERE slug=? AND id<>?");
      $st->execute([$slug, $excludeId]);
    } else {
      $st = $pdo->prepare("SELECT COUNT(*) FROM news WHERE slug=?");
      $st->execute([$slug]);
    }
    if ($st->fetchColumn() == 0) return $slug;
    $i++;
    $slug = $baseSlug . '-' . $i;
  }
}

/* -----------------------
   DELETE (GET ?del=ID)
------------------------ */
if (isset($_GET['del'])) {
  $id = (int)$_GET['del'];
  // ambil foto untuk hapus file lokal
  $st = $pdo->prepare("SELECT photo_path FROM news WHERE id=?");
  $st->execute([$id]);
  if ($row = $st->fetch()) {
    unlink_if_local($publicRoot, $publicUrlBase, $row['photo_path'] ?? null);
  }
  $pdo->prepare("DELETE FROM news WHERE id=?")->execute([$id]);
  flash('ok','Berita dihapus.');
  header('Location: news.php'); exit;
}

/* -----------------------
   CREATE/UPDATE (POST)
------------------------ */
if (is_post() && ($_POST['action'] ?? '') !== 'delete') {
  csrf_check();

  $id      = (int)($_POST['id'] ?? 0);
  $title   = trim($_POST['title'] ?? '');
  $author  = trim($_POST['author'] ?? '');
  $pubdate = trim($_POST['publish_date'] ?? '');
  $category= trim($_POST['category'] ?? '');
  $source  = trim($_POST['source'] ?? '');
  $content = trim($_POST['content'] ?? '');
  $imgUrlInput = trim($_POST['image_url'] ?? '');

  if ($title === '') { flash('err','Judul wajib diisi.'); header('Location: news.php'.($id?'?id='.$id:'')); exit; }

  // slug
  $baseSlug = make_slug($title);
  $slug = ensure_unique_slug($pdo, $baseSlug, $id);

  // Gambar: prioritas upload
  $finalImage = $imgUrlInput;
  if (!empty($_FILES['image_file']) && $_FILES['image_file']['error'] !== UPLOAD_ERR_NO_FILE) {
    [$saved, $err] = save_uploaded_image($_FILES['image_file'], $title, $uploadDir, $uploadUrl);
    if ($err) { flash('err', $err); header('Location: news.php'.($id?'?id='.$id:'')); exit; }
    $finalImage = $saved;

    // Jika update → hapus foto lama lokal
    if ($id) {
      $st = $pdo->prepare("SELECT photo_path FROM news WHERE id=?");
      $st->execute([$id]);
      $old = $st->fetch();
      if ($old && !empty($old['photo_path'])) {
        unlink_if_local($publicRoot, $publicUrlBase, $old['photo_path']);
      }
    }
  }

  if ($id) {
    $st = $pdo->prepare("
      UPDATE news
         SET title=?, slug=?, author=?, publish_date=?, category=?, source=?, photo_path=?, content=?, updated_at=NOW()
       WHERE id=?");
    $st->execute([$title, $slug, $author ?: null, $pubdate ?: null, $category ?: null, $source ?: null, $finalImage ?: null, $content ?: null, $id]);
    flash('ok','Berita diperbarui.');
  } else {
    $st = $pdo->prepare("
      INSERT INTO news (title, slug, author, publish_date, category, source, photo_path, content, created_at)
      VALUES (?,?,?,?,?,?,?,?,NOW())");
    $st->execute([$title, $slug, $author ?: null, $pubdate ?: null, $category ?: null, $source ?: null, $finalImage ?: null, $content ?: null]);
    $id = (int)$pdo->lastInsertId();
    flash('ok','Berita tersimpan.');
  }

  header('Location: news.php?id='.$id); exit;
}

/* -----------------------
   LOAD EDIT TARGET
------------------------ */
$edit = null;
if (isset($_GET['id'])) {
  $st = $pdo->prepare("SELECT * FROM news WHERE id=?");
  $st->execute([(int)$_GET['id']]);
  $edit = $st->fetch();
}

/* -----------------------
   LOAD TABLE DATA
------------------------ */
$rows = $pdo->query("
  SELECT *
    FROM news
ORDER BY COALESCE(publish_date, DATE(created_at)) DESC, id DESC
")->fetchAll();

/* -----------------------
   VIEW DETAIL (?view=ID)
------------------------ */
$view = null;
if (isset($_GET['view'])) {
  $vid = (int)$_GET['view'];
  $st = $pdo->prepare("SELECT * FROM news WHERE id=?");
  $st->execute([$vid]);
  $view = $st->fetch();
}

/* -----------------------
   OUTPUT (mulai HTML)
------------------------ */
require_once __DIR__ . '/_layout_top.php';
$ok  = flash('ok'); $err = flash('err');
?>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

  <!-- FORM BERITA -->
  <div class="bg-white rounded-xl border border-gray-200">
    <div class="p-5 border-b flex items-center justify-between">
      <h2 class="font-semibold"><?php echo $edit ? 'Edit' : 'Tambah' ?> Berita</h2>
      <div class="flex items-center gap-2">
        <?php if($ok): ?><span class="text-sm text-emerald-700 bg-emerald-50 border border-emerald-100 rounded px-2 py-1"><?php echo e($ok) ?></span><?php endif; ?>
        <?php if($err): ?><span class="text-sm text-red-700 bg-red-50 border border-red-100 rounded px-2 py-1"><?php echo e($err) ?></span><?php endif; ?>
      </div>
    </div>

    <div class="p-5">
      <form method="post" enctype="multipart/form-data" class="grid grid-cols-1 gap-4" id="news-form">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="id" value="<?php echo e($edit['id'] ?? '') ?>">

        <div>
          <label class="text-sm">Judul</label>
          <input class="mt-1 w-full border rounded-lg px-3 py-2" name="title" required
                 value="<?php echo e($edit['title'] ?? '') ?>">
        </div>

        <div class="grid md:grid-cols-2 gap-4">
          <div>
            <label class="text-sm">Penulis</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="author"
                   value="<?php echo e($edit['author'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm">Tanggal Terbit</label>
            <input type="date" class="mt-1 w-full border rounded-lg px-3 py-2" name="publish_date"
                   value="<?php echo e($edit['publish_date'] ?? '') ?>">
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-4">
          <div>
            <label class="text-sm">Kategori</label>
            <input list="catlist" class="mt-1 w-full border rounded-lg px-3 py-2" name="category"
                   value="<?php echo e($edit['category'] ?? '') ?>" placeholder="Berita / Pengumuman / Event ...">
            <datalist id="catlist">
              <option>Berita</option>
              <option>Pengumuman</option>
              <option>Event</option>
              <option>Keuangan</option>
            </datalist>
          </div>
          <div>
            <label class="text-sm">Sumber (URL)</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="source"
                   value="<?php echo e($edit['source'] ?? '') ?>" placeholder="https://...">
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-4">
          <div>
            <label class="text-sm">Foto Sampul (Upload)</label>
            <input type="file" name="image_file" accept="image/*"
                   class="mt-1 w-full border rounded-lg px-3 py-2 bg-white">
            <p class="text-xs text-gray-500 mt-1">JPG/PNG/WEBP/GIF • Maks 5MB.</p>
          </div>
          <div>
            <label class="text-sm">Foto Sampul (URL alternatif)</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="image_url"
                   value="<?php echo e($edit['photo_path'] ?? '') ?>" placeholder="https://...">
            <p class="text-xs text-gray-500 mt-1">Jika upload & URL diisi, yang dipakai adalah hasil upload.</p>
          </div>
        </div>

        <div>
          <label class="text-sm">Konten</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="8" name="content"><?php
            echo e($edit['content'] ?? '');
          ?></textarea>
        </div>

        <?php if(!empty($edit['photo_path'])): ?>
        <div>
          <label class="text-sm block mb-1">Preview Sampul</label>
          <?php $imgUrl = to_public_url($edit['photo_path'], $publicUrlBase); ?>
          <img src="<?php echo e($imgUrl) ?>" alt="preview" class="max-h-40 rounded-lg border">
        </div>
        <?php endif; ?>

        <div class="flex items-center gap-2">
          <button class="bg-blue-600 hover:bg-blue-700 text-white rounded-lg px-4 py-2">Simpan</button>
          <?php if($edit): ?>
            <a href="news.php" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a>
          <?php endif; ?>
        </div>
      </form>
    </div>
  </div>

  <!-- TABEL BERITA -->
  <div class="bg-white rounded-xl border border-gray-200 overflow-x-auto">
    <div class="p-5 border-b flex items-center justify-between">
      <h2 class="font-semibold">Daftar Berita</h2>
      <a href="news.php" class="text-sm text-primary hover:underline">Refresh</a>
    </div>
    <table class="min-w-full text-sm">
      <thead class="bg-gray-50 text-gray-600">
        <tr>
          <th class="px-4 py-2 text-left">#</th>
          <th class="px-4 py-2 text-left">Sampul</th>
          <th class="px-4 py-2 text-left">Judul & Info</th>
          <th class="px-4 py-2 text-left">Terbit</th>
          <th class="px-4 py-2 text-left">Aksi</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach($rows as $r): ?>
        <tr class="border-t align-top">
          <td class="px-4 py-2"><?php echo (int)$r['id'] ?></td>
          <td class="px-4 py-2">
            <?php if(!empty($r['photo_path'])): ?>
              <?php $thumb = to_public_url($r['photo_path'], $publicUrlBase); ?>
              <img src="<?php echo e($thumb) ?>" alt="" class="h-14 w-20 object-cover rounded border">
            <?php else: ?>
              <span class="text-gray-400">—</span>
            <?php endif; ?>
          </td>
          <td class="px-4 py-2">
            <div class="font-medium"><?php echo e($r['title']) ?></div>
            <div class="text-xs text-gray-500 mt-0.5">
              Slug: <code><?php echo e($r['slug']) ?></code>
              <?php if(!empty($r['category'])): ?> • Kategori: <?php echo e($r['category']) ?><?php endif; ?>
              <?php if(!empty($r['author'])): ?> • Penulis: <?php echo e($r['author']) ?><?php endif; ?>
            </div>
            <?php if(!empty($r['source'])): ?>
              <div class="text-xs mt-1">
                <a class="text-primary hover:underline" href="<?php echo e($r['source']) ?>" target="_blank" rel="noopener">Sumber</a>
              </div>
            <?php endif; ?>
          </td>
          <td class="px-4 py-2">
            <?php echo e($r['publish_date'] ?: ($r['created_at'] ?? '')); ?>
          </td>
          <td class="px-4 py-2">
            <div class="flex items-center gap-2">
              <a class="px-2 py-1 rounded border text-sm" href="?view=<?php echo (int)$r['id'] ?>">Lihat</a>
              <a class="px-2 py-1 rounded border text-sm" href="?id=<?php echo (int)$r['id'] ?>">Edit</a>
              <a class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm"
                 href="?del=<?php echo (int)$r['id'] ?>"
                 onclick="return confirm('Hapus berita ini?')">Hapus</a>
            </div>
          </td>
        </tr>
      <?php endforeach; if(empty($rows)): ?>
        <tr><td colspan="5" class="px-4 py-6 text-center text-gray-500">Belum ada data.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- MODAL VIEW DETAIL -->
<?php if($view): ?>
  <?php
    $vImg = to_public_url($view['photo_path'] ?? '', $publicUrlBase);
    $vSrc = trim($view['source'] ?? '');
  ?>
  <div id="news-viewer" class="fixed inset-0 z-[100] flex items-start justify-center bg-black/50 p-4">
    <div class="bg-white w-full max-w-4xl rounded-xl shadow-2xl overflow-hidden">
      <div class="flex items-center justify-between border-b px-5 py-3">
        <h3 class="font-semibold text-lg">Detail Berita: <?php echo e($view['title'] ?? ''); ?></h3>
        <div class="flex items-center gap-2">
          <?php if($vSrc): ?>
            <a href="<?php echo e($vSrc) ?>" target="_blank" rel="noopener"
               class="px-3 py-1.5 rounded border text-sm hover:bg-gray-50">Buka Sumber</a>
          <?php endif; ?>
          <button class="px-3 py-1.5 rounded border text-sm hover:bg-gray-50" onclick="closeViewer()">Tutup</button>
        </div>
      </div>

      <div class="p-5 grid md:grid-cols-2 gap-5">
        <div class="space-y-3">
          <div class="text-sm text-gray-500">
            Terbit: <?php echo e($view['publish_date'] ?: ($view['created_at'] ?? '')); ?>
            <?php if(!empty($view['category'])): ?> • Kategori: <?php echo e($view['category']) ?><?php endif; ?>
          </div>
          <?php if($vImg): ?>
            <img src="<?php echo e($vImg) ?>" class="w-full max-h-72 object-cover rounded border" alt="">
          <?php else: ?>
            <div class="w-full h-48 bg-gray-100 rounded border flex items-center justify-center text-gray-400">Tidak ada foto</div>
          <?php endif; ?>
        </div>
        <div>
          <div class="font-medium mb-2">Konten</div>
          <div class="text-gray-700 whitespace-pre-line"><?php echo e($view['content'] ?? ''); ?></div>
          <?php if(!empty($view['author'])): ?>
            <div class="text-xs text-gray-500 mt-3">Penulis: <?php echo e($view['author']); ?></div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <script>
    function closeViewer(){
      const url = new URL(window.location.href);
      url.searchParams.delete('view');
      window.location.href = url.toString();
    }
    document.getElementById('news-viewer')?.addEventListener('click', function(e){
      if(e.target === this){ closeViewer(); }
    });
    document.addEventListener('keydown', function(e){
      if(e.key === 'Escape') closeViewer();
    });
  </script>
<?php endif; ?>

<?php require __DIR__ . '/_layout_bottom.php'; ?>
