<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();
$db = getDB();

// Save (add/edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id   = (int)($_POST['id'] ?? 0);
    $name = sanitize($_POST['name'] ?? '');
    $slug = sanitize($_POST['slug'] ?? '') ?: slugify($name);
    $icon = sanitize($_POST['icon'] ?? 'fas fa-gavel');
    $desc = sanitize($_POST['description'] ?? '');
    $sort = (int)($_POST['sort_order'] ?? 0);
    $stat = (int)($_POST['status'] ?? 1);
    if ($name) {
        if ($id) {
            $db->prepare("UPDATE legal_categories SET name=?,slug=?,icon=?,description=?,sort_order=?,status=? WHERE id=?")->execute([$name,$slug,$icon,$desc,$sort,$stat,$id]);
            setAdminFlash('success','Category updated.');
        } else {
            $db->prepare("INSERT INTO legal_categories (name,slug,icon,description,sort_order,status) VALUES (?,?,?,?,?,?)")->execute([$name,$slug,$icon,$desc,$sort,$stat]);
            setAdminFlash('success','Category added.');
        }
    }
    header('Location: /admin/categories.php'); exit;
}

// Delete
if (isset($_GET['delete']) && (int)$_GET['delete']) {
    $db->prepare("DELETE FROM legal_categories WHERE id=?")->execute([(int)$_GET['delete']]);
    setAdminFlash('success','Category deleted.');
    header('Location: /admin/categories.php'); exit;
}

// Edit
$editCat = null;
if (isset($_GET['edit'])) {
    $s = $db->prepare("SELECT * FROM legal_categories WHERE id=?"); $s->execute([(int)$_GET['edit']]);
    $editCat = $s->fetch();
}

$cats = $db->query("SELECT c.*, (SELECT COUNT(*) FROM lawyer_expertise WHERE category_id=c.id) AS lawyer_count FROM legal_categories c ORDER BY c.sort_order, c.name")->fetchAll();

$icons = ['fas fa-home','fas fa-gavel','fas fa-balance-scale','fas fa-users','fas fa-heart-broken','fas fa-building','fas fa-shield-alt','fas fa-lightbulb','fas fa-hard-hat','fas fa-file-invoice-dollar','fas fa-shopping-cart','fas fa-leaf','fas fa-passport','fas fa-umbrella','fas fa-rocket','fas fa-briefcase','fas fa-landmark','fas fa-globe'];

adminHead('Legal Categories');
adminSidebar('categories');
?>
<div class="adm-main">
<?php adminTopbar('Manage Legal Categories'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<div class="row g-4">
    <!-- Form -->
    <div class="col-lg-4">
        <div class="adm-card" style="overflow:visible;">
            <div class="adm-card-head"><h6><?= $editCat ? 'Edit Category' : 'Add New Category' ?></h6></div>
            <div style="padding:22px;">
                <form method="POST">
                    <?php if ($editCat): ?><input type="hidden" name="id" value="<?= $editCat['id'] ?>"><?php endif; ?>
                    <div style="margin-bottom:14px;">
                        <label class="lbl">Category Name *</label>
                        <input type="text" name="name" class="form-ctrl" value="<?= htmlspecialchars($editCat['name'] ?? '') ?>" required
                               oninput="this.form.slug.value=this.value.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')">
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="lbl">URL Slug</label>
                        <input type="text" name="slug" class="form-ctrl" value="<?= htmlspecialchars($editCat['slug'] ?? '') ?>">
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="lbl">Icon Class (Font Awesome)</label>
                        <select name="icon" class="form-ctrl">
                            <?php foreach ($icons as $ic): ?>
                            <option value="<?= $ic ?>" <?= ($editCat['icon'] ?? '') === $ic ? 'selected' : '' ?>>
                                <?= $ic ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div style="margin-top:8px;font-size:.8rem;color:#718096;">Custom icon: <input type="text" name="icon" placeholder="fas fa-..." style="border:1px dashed var(--border);border-radius:6px;padding:5px 10px;font-size:.8rem;width:100%;margin-top:4px;" value="<?= htmlspecialchars($editCat['icon'] ?? 'fas fa-gavel') ?>"></div>
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="lbl">Description</label>
                        <textarea name="description" class="form-ctrl" rows="3"><?= htmlspecialchars($editCat['description'] ?? '') ?></textarea>
                    </div>
                    <div class="row g-2 mb-4">
                        <div class="col-6">
                            <label class="lbl">Sort Order</label>
                            <input type="number" name="sort_order" class="form-ctrl" value="<?= $editCat['sort_order'] ?? 0 ?>" min="0">
                        </div>
                        <div class="col-6">
                            <label class="lbl">Status</label>
                            <select name="status" class="form-ctrl">
                                <option value="1" <?= ($editCat['status'] ?? 1)==1?'selected':'' ?>>Active</option>
                                <option value="0" <?= ($editCat['status'] ?? 1)==0?'selected':'' ?>>Inactive</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn-gold w-100" style="width:100%;padding:11px;"><?= $editCat ? 'Update Category' : 'Add Category' ?></button>
                    <?php if ($editCat): ?>
                    <a href="/admin/categories.php" style="display:block;text-align:center;margin-top:10px;font-size:.82rem;color:#718096;">Cancel Edit</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- List -->
    <div class="col-lg-8">
        <div class="adm-card">
            <div class="adm-card-head"><h6>All Categories (<?= count($cats) ?>)</h6></div>
            <div style="overflow-x:auto;">
            <table class="table tbl mb-0">
                <thead><tr><th>Icon</th><th>Name</th><th>Slug</th><th>Lawyers</th><th>Order</th><th>Status</th><th>Actions</th></tr></thead>
                <tbody>
                <?php foreach ($cats as $c): ?>
                <tr>
                    <td style="text-align:center;"><i class="<?= $c['icon'] ?>" style="font-size:1.1rem;color:var(--primary);"></i></td>
                    <td style="font-weight:700;font-size:.85rem;"><?= htmlspecialchars($c['name']) ?></td>
                    <td style="font-size:.78rem;color:#718096;"><?= $c['slug'] ?></td>
                    <td><span style="background:rgba(10,35,66,.07);color:var(--primary);padding:3px 10px;border-radius:50px;font-size:.74rem;font-weight:700;"><?= $c['lawyer_count'] ?></span></td>
                    <td style="font-size:.82rem;"><?= $c['sort_order'] ?></td>
                    <td><span class="badge-pill badge-<?= $c['status']?'active':'inactive' ?>"><?= $c['status']?'Active':'Inactive' ?></span></td>
                    <td style="white-space:nowrap;">
                        <a href="?edit=<?= $c['id'] ?>" class="btn-sm-edit">Edit</a>
                        <a href="?delete=<?= $c['id'] ?>" class="btn-sm-del confirm-del" style="margin-left:5px;">Del</a>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>
    </div>
</div>
</div></div>
<?php adminFoot(); ?>