<?php
// admin/berita.php - CRUD Berita (News) for admin
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$db = get_db();

// Auto-migrate berita table
$db->exec("CREATE TABLE IF NOT EXISTS berita (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    kategori TEXT DEFAULT '',
    content TEXT NOT NULL,
    image TEXT,
    date TEXT NOT NULL,
    author TEXT
)");
// Add kategori column if not exists (for migration)
try { $db->query("SELECT kategori FROM berita LIMIT 1"); } catch (Exception $e) {
  $db->exec("ALTER TABLE berita ADD COLUMN kategori TEXT DEFAULT ''");
}

// Handle add/edit/delete actions
$action = $_GET['action'] ?? '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Add Berita
if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
  $kategori = trim($_POST['kategori'] ?? '');
  $content = trim($_POST['content'] ?? '');
    $date = date('Y-m-d');
    $author = $_SESSION['user']['username'] ?? 'admin';
    $image = null;
    if (!empty($_FILES['image']['name'])) {
        $imgName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['image']['name']);
        $dest = __DIR__ . '/../data/uploads/' . $imgName;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
            $image = $imgName;
        }
    }
  $stmt = $db->prepare("INSERT INTO berita (title, kategori, content, image, date, author) VALUES (?, ?, ?, ?, ?, ?)");
  $stmt->execute([$title, $kategori, $content, $image, $date, $author]);
    header('Location: berita.php?msg=added'); exit;
}

// Edit Berita
if ($action === 'edit' && $id && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
  $kategori = trim($_POST['kategori'] ?? '');
  $content = trim($_POST['content'] ?? '');
    $author = $_SESSION['user']['username'] ?? 'admin';
    $image = $_POST['old_image'] ?? null;
    if (!empty($_FILES['image']['name'])) {
        $imgName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['image']['name']);
        $dest = __DIR__ . '/../data/uploads/' . $imgName;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
            $image = $imgName;
        }
    }
  $stmt = $db->prepare("UPDATE berita SET title=?, kategori=?, content=?, image=?, author=? WHERE id=?");
  $stmt->execute([$title, $kategori, $content, $image, $author, $id]);
    header('Location: berita.php?msg=updated'); exit;
}

// Delete Berita
if ($action === 'delete' && $id) {
    $stmt = $db->prepare("DELETE FROM berita WHERE id=?");
    $stmt->execute([$id]);
    header('Location: berita.php?msg=deleted'); exit;
}

// Fetch berita list
$berita = $db->query("SELECT * FROM berita ORDER BY date DESC, id DESC")->fetchAll(PDO::FETCH_ASSOC);

// Fetch single berita for edit
$edit = null;
if ($action === 'edit' && $id) {
    $stmt = $db->prepare("SELECT * FROM berita WHERE id=?");
    $stmt->execute([$id]);
    $edit = $stmt->fetch(PDO::FETCH_ASSOC);
}

include '_header.php';
?>
<div class="container-fluid">
  <h1 class="mt-3 mb-4">Manajemen Berita</h1>
  <?php if (!empty($_GET['msg'])): ?>
    <div class="alert alert-success">Berita berhasil <?php echo e($_GET['msg']); ?>.</div>
  <?php endif; ?>
  <div class="row">
    <div class="col-md-5">
      <div class="card mb-4">
        <div class="card-header">Tambah / Edit Berita</div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data" action="berita.php?action=<?php echo $edit ? 'edit&id=' . $edit['id'] : 'add'; ?>">
            <div class="mb-2">
              <label>Judul</label>
              <input type="text" name="title" class="form-control" required value="<?php echo e($edit['title'] ?? ''); ?>">
            </div>
            <div class="mb-2">
              <label>Kategori</label>
              <input type="text" name="kategori" class="form-control" placeholder="Misal: Pengumuman, Prestasi, dll" value="<?php echo e($edit['kategori'] ?? ''); ?>">
            </div>
            <div class="mb-2">
              <label>Isi Berita</label>
              <textarea name="content" class="form-control" rows="5" required><?php echo e($edit['content'] ?? ''); ?></textarea>
            </div>
            <div class="mb-2">
              <label>Gambar (opsional)</label>
              <input type="file" name="image" class="form-control">
              <?php if (!empty($edit['image'])): ?>
                <img src="../data/uploads/<?php echo e($edit['image']); ?>" alt="Gambar" class="img-thumbnail mt-2" style="max-width:120px;">
                <input type="hidden" name="old_image" value="<?php echo e($edit['image']); ?>">
              <?php endif; ?>
            </div>
            <button type="submit" class="btn btn-primary">Simpan</button>
            <?php if ($edit): ?>
              <a href="berita.php" class="btn btn-secondary">Batal</a>
            <?php endif; ?>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-7">
      <div class="card mb-4">
        <div class="card-header">Daftar Berita</div>
        <div class="card-body p-0">
          <table class="table table-striped mb-0">
            <thead><tr><th>Judul</th><th>Kategori</th><th>Tanggal</th><th>Author</th><th>Gambar</th><th>Aksi</th></tr></thead>
            <tbody>
              <?php foreach ($berita as $b): ?>
                <tr>
                  <td><?php echo e($b['title']); ?></td>
                  <td><?php echo e($b['kategori'] ?? ''); ?></td>
                  <td><?php echo e($b['date']); ?></td>
                  <td><?php echo e($b['author']); ?></td>
                  <td><?php if ($b['image']): ?><img src="../data/uploads/<?php echo e($b['image']); ?>" alt="Gambar" style="max-width:60px;max-height:40px;object-fit:cover;"><?php endif; ?></td>
                  <td>
                    <a href="berita.php?action=edit&id=<?php echo $b['id']; ?>" class="btn btn-sm btn-warning">Edit</a>
                    <a href="berita.php?action=delete&id=<?php echo $b['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus berita ini?')">Hapus</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<?php include '_footer.php'; ?>
