<?php
session_start();
require_once '../config/db.php';
require_once 'auth.php';

$pageTitle = 'Berita & Kegiatan';
$activePage = 'news';
$msg = '';

// Delete
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT image FROM news WHERE id=?");
    $stmt->execute([$_GET['delete']]);
    $row = $stmt->fetch();
    if ($row && $row['image'] && file_exists(dirname(__DIR__).'/'.$row['image'])) @unlink(dirname(__DIR__).'/'.$row['image']);
    $pdo->prepare("DELETE FROM news WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Berita berhasil dihapus.');
}

// Toggle
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE news SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: news.php'); exit;
}

// Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $title = trim($_POST['title']??'');
    $slug = strtolower(preg_replace('/[^a-z0-9]+/','-',trim($_POST['slug']??$title)));
    $excerpt = trim($_POST['excerpt']??'');
    $content = $_POST['content']??'';
    $category = $_POST['category']??'news';
    $active = isset($_POST['is_active']) ? 1 : 0;
    $existing_img = $_POST['existing_image']??'';
    
    $image = $existing_img;
    if (!empty($_FILES['image']['name'])) {
        $uploaded = uploadFile($_FILES['image'], 'assets/images/news');
        if ($uploaded) $image = $uploaded;
    }
    
    if ($id) {
        $pdo->prepare("UPDATE news SET title=?,slug=?,excerpt=?,content=?,image=?,category=?,is_active=? WHERE id=?")
            ->execute([$title,$slug,$excerpt,$content,$image,$category,$active,$id]);
        $msg = adminAlert('Berita berhasil diperbarui.');
    } else {
        // make slug unique
        $base = $slug; $c = 1;
        while ($pdo->prepare("SELECT id FROM news WHERE slug=?")->execute([$slug]) && $pdo->query("SELECT id FROM news WHERE slug='$slug'")->fetch()) {
            $slug = $base.'-'.$c++;
        }
        $pdo->prepare("INSERT INTO news (title,slug,excerpt,content,image,category,is_active) VALUES (?,?,?,?,?,?,?)")
            ->execute([$title,$slug,$excerpt,$content,$image,$category,$active]);
        $msg = adminAlert('Berita berhasil ditambahkan.');
    }
}

$editItem = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM news WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $editItem = $stmt->fetch();
}

$items = $pdo->query("SELECT * FROM news ORDER BY created_at DESC")->fetchAll();
include 'partials/header.php';
?>

<?= $msg ?>

<div class="row g-4">
    <div class="col-lg-5">
        <div class="card">
            <div class="card-header"><?= $editItem ? 'Edit Berita' : 'Tambah Berita Baru' ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?= $editItem['id'] ?>">
                        <input type="hidden" name="existing_image" value="<?= $editItem['image'] ?>">
                    <?php endif; ?>
                    <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" required value="<?= htmlspecialchars($editItem['title']??'') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Slug</label>
                        <input type="text" name="slug" class="form-control" value="<?= htmlspecialchars($editItem['slug']??'') ?>" placeholder="auto-generated">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Kategori</label>
                        <select name="category" class="form-select">
                            <option value="news" <?= ($editItem['category']??'')=='news'?'selected':'' ?>>Berita</option>
                            <option value="event" <?= ($editItem['category']??'')=='event'?'selected':'' ?>>Kegiatan / Event</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Ringkasan</label>
                        <textarea name="excerpt" class="form-control" rows="2"><?= htmlspecialchars($editItem['excerpt']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Konten</label>
                        <textarea name="content" id="content" class="form-control" rows="6"><?= htmlspecialchars($editItem['content']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Gambar</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <?php if ($editItem && $editItem['image']): ?>
                            <img src="../<?= $editItem['image'] ?>" class="mt-2 rounded" style="height:80px;object-fit:cover;" onerror="this.style.display='none'">
                        <?php endif; ?>
                    </div>
                    <div class="mb-3 form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="ia" <?= ($editItem['is_active']??1) ? 'checked' : '' ?>>
                        <label class="form-check-label fw-semibold" for="ia">Tampilkan di website</label>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-dark"><?= $editItem ? 'Update' : 'Tambah' ?></button>
                        <?php if ($editItem): ?><a href="news.php" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-7">
        <div class="card">
            <div class="card-header">Daftar Berita (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light">
                        <tr><th>Gambar</th><th>Judul</th><th>Kat.</th><th>Status</th><th>Aksi</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><img src="../<?= $item['image'] ?>" style="width:70px;height:45px;object-fit:cover;border-radius:4px;" onerror="this.src='https://via.placeholder.com/70x45'"></td>
                            <td>
                                <div class="fw-semibold" style="max-width:200px;"><?= htmlspecialchars($item['title']) ?></div>
                                <small class="text-muted"><?= date('d/m/Y', strtotime($item['created_at'])) ?></small>
                            </td>
                            <td><span class="badge bg-secondary"><?= $item['category'] ?></span></td>
                            <td><a href="?toggle=<?= $item['id'] ?>" class="badge <?= $item['is_active'] ? 'badge-active' : 'badge-inactive' ?> text-decoration-none"><?= $item['is_active'] ? 'Aktif' : 'Nonaktif' ?></a></td>
                            <td>
                                <a href="?edit=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
                                <a href="?delete=<?= $item['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php include 'partials/footer.php'; ?>
