<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../config/logger.php';

requireLogin();
requireRole(['admin','diocesan_chairman','diocese_chairman','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocesan_music_director']);

$basePath = '..';

function make_slug($str) {
    $s = strtolower($str);
    $s = preg_replace('/[^a-z0-9]+/i', '-', $s);
    $s = preg_replace('/-+/', '-', $s);
    $s = trim($s, '-');
    return $s ?: 'category';
}

function unique_slug($base, $excludeId = 0) {
    $slug = make_slug($base);
    $try = $slug;
    $i = 1;
    while (true) {
        if ($excludeId > 0) {
            $row = fetchRow("SELECT id FROM ad_categories WHERE slug=? AND id<>?", [$try, (int)$excludeId]);
        } else {
            $row = fetchRow("SELECT id FROM ad_categories WHERE slug=?", [$try]);
        }
        if (!$row) { return $try; }
        $i++;
        $try = $slug . '-' . $i;
    }
}

$errors = [];
$successMsg = '';

$editId = isset($_GET['edit_id']) ? (int)$_GET['edit_id'] : 0;
$editing = null;
if ($editId > 0) {
    $editing = fetchRow("SELECT * FROM ad_categories WHERE id=?", [$editId]);
    if (!$editing) { $editId = 0; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'create') {
        $name = trim($_POST['name'] ?? '');
        $parent_id = isset($_POST['parent_id']) ? (int)$_POST['parent_id'] : 0;
        if ($name === '') { $errors[] = 'Name is required'; }
        if (empty($errors)) {
            $slug = unique_slug($name);
            $ok = executeQuery("INSERT INTO ad_categories (name, slug, parent_id) VALUES (?,?,?)", [$name, $slug, $parent_id ?: null]);
            if ($ok) { $successMsg = 'Category created'; }
            else { $errors[] = 'Database error while creating category'; }
        }
    } elseif ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $parent_id = isset($_POST['parent_id']) ? (int)$_POST['parent_id'] : 0;
        if ($id <= 0) { $errors[] = 'Invalid category'; }
        if ($name === '') { $errors[] = 'Name is required'; }
        if ($id === $parent_id) { $errors[] = 'Category cannot be its own parent'; }
        if (empty($errors)) {
            $slug = unique_slug($name, $id);
            $ok = executeQuery("UPDATE ad_categories SET name=?, slug=?, parent_id=? WHERE id=?", [$name, $slug, $parent_id ?: null, $id]);
            if ($ok) { $successMsg = 'Category updated'; $editId = 0; $editing = null; }
            else { $errors[] = 'Database error while updating category'; }
        }
    } elseif ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) { $errors[] = 'Invalid category'; }
        if (empty($errors)) {
            $ok = executeQuery("DELETE FROM ad_categories WHERE id=?", [$id]);
            if ($ok) { $successMsg = 'Category deleted'; }
            else { $errors[] = 'Database error while deleting category'; }
        }
    }
}

$categories = fetchRows("SELECT c.*, p.name AS parent_name FROM ad_categories c LEFT JOIN ad_categories p ON c.parent_id = p.id ORDER BY c.name");
$parents = fetchRows("SELECT id, name FROM ad_categories ORDER BY name");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ad Categories - GHAMECC</title>
    <?php include '../includes/favicon.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>
<body>
<?php include '../includes/navbar.php'; ?>
<div class="container-fluid">
    <div class="row">
        <?php include '../includes/sidebar.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h1 class="h2">Ad Categories</h1>
                <a href="submit.php" class="btn btn-primary"><i class="fas fa-plus me-2"></i>Submit New Advert</a>
            </div>

            <?php if (!empty($successMsg)): ?><div class="alert alert-success"><?php echo htmlspecialchars($successMsg); ?></div><?php endif; ?>
            <?php if (!empty($errors)): ?><div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?></ul></div><?php endif; ?>

            <div class="row g-4">
                <div class="col-md-5">
                    <div class="card">
                        <div class="card-header"><?php echo $editId>0?'Edit Category':'Create Category'; ?></div>
                        <div class="card-body">
                            <form method="post">
                                <?php if ($editId>0): ?><input type="hidden" name="id" value="<?php echo (int)$editId; ?>"><?php endif; ?>
                                <div class="mb-3">
                                    <label class="form-label">Name</label>
                                    <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($editing['name'] ?? ''); ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Parent (optional)</label>
                                    <select name="parent_id" class="form-select">
                                        <option value="0">None</option>
                                        <?php foreach ($parents as $p): if ($editId>0 && (int)$p['id']===$editId) continue; ?>
                                            <option value="<?php echo (int)$p['id']; ?>" <?php echo ($editing && (int)$editing['parent_id']===(int)$p['id'])?'selected':''; ?>><?php echo htmlspecialchars($p['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <button class="btn btn-primary" type="submit" name="action" value="<?php echo $editId>0?'update':'create'; ?>"><?php echo $editId>0?'Save Changes':'Create Category'; ?></button>
                                    <?php if ($editId>0): ?><a href="categories.php" class="btn btn-secondary ms-2">Cancel</a><?php endif; ?>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-md-7">
                    <div class="card">
                        <div class="card-header">All Categories</div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-striped mb-0">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Slug</th>
                                            <th>Parent</th>
                                            <th>Created</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($categories)): ?>
                                            <tr><td colspan="5" class="text-center text-muted py-3">No categories</td></tr>
                                        <?php else: foreach ($categories as $c): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($c['name']); ?></td>
                                                <td class="text-muted small"><?php echo htmlspecialchars($c['slug']); ?></td>
                                                <td><?php echo htmlspecialchars($c['parent_name'] ?? ''); ?></td>
                                                <td><?php echo date('Y-m-d', strtotime($c['created_at'])); ?></td>
                                                <td class="text-nowrap">
                                                    <a href="categories.php?edit_id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-warning me-1">Edit</a>
                                                    <form method="post" style="display:inline-block" onsubmit="return confirm('Delete this category?');">
                                                        <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
                                                        <button class="btn btn-sm btn-outline-danger" type="submit" name="action" value="delete">Delete</button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
