<?php
session_start();
require_once 'system/db.php';
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) { header("Location: login.php"); exit; }

if (isset($_POST['add'])) {
    $name = trim($_POST['name']);
    if(!empty($name)) $db->prepare("INSERT INTO blog_categories (name) VALUES (?)")->execute([$name]);
}
if (isset($_GET['del'])) {
    $id = intval($_GET['del']);
    $db->query("DELETE FROM blog_categories WHERE id = $id");
    // Kategorisi silinen yazıları 'Genel (0)' kategoriye çekelim
    $db->query("UPDATE blog_posts SET category_id = 0 WHERE category_id = $id");
    header("Location: blog-categories.php"); exit;
}
$cats = $db->query("SELECT * FROM blog_categories ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="tr" data-theme="light">
<?php include 'inc/header.php'; ?>
<body>
    <?php include 'inc/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'inc/navbar.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Blog Kategorileri</h6>
                <a href="blogs.php" class="btn btn-outline-primary px-4 py-2 radius-8">Geri Dön</a>
            </div>

            <div class="row gy-4">
                <div class="col-lg-4">
                    <div class="card p-24 radius-12">
                        <h6 class="mb-3">Kategori Ekle</h6>
                        <form method="POST">
                            <input type="text" name="name" class="form-control radius-8 mb-3" placeholder="Kategori Adı" required>
                            <button name="add" class="btn btn-primary w-100 radius-8">Ekle</button>
                        </form>
                    </div>
                </div>
                <div class="col-lg-8">
                    <div class="card p-24 radius-12">
                        <table class="table bordered-table sm-table mb-0">
                            <?php foreach($cats as $c): ?>
                            <tr>
                                <td class="fw-bold"><?php echo $c['name']; ?></td>
                                <td class="text-end"><a href="?del=<?php echo $c['id']; ?>" class="text-danger" onclick="return confirm('Sil?')">Sil</a></td>
                            </tr>
                            <?php endforeach; ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php include 'inc/copyright.php'; ?>
    </main>
    <?php include 'inc/footer.php'; ?>
</body>
</html>