<?php
$page_title = 'Categories';
require __DIR__ . '/_guard.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';
    $id = (int)($_POST['cat_id'] ?? 0);

    if ($do === 'delete' && $id) {
        // Safety — can't delete if listings still reference it
        $slug = db_value('SELECT slug FROM categories WHERE id=:id', ['id'=>$id]);
        $used = (int)db_value('SELECT COUNT(*) FROM listings WHERE category_slug=:s', ['s'=>$slug]);
        if ($used > 0) {
            header('Location: categories.php?err=' . urlencode("Can't delete — {$used} listing(s) are in this category. Move them first."));
            exit;
        }
        $img = db_value('SELECT image_path FROM categories WHERE id=:id', ['id'=>$id]);
        if ($img) {
            $p = __DIR__ . '/../' . ltrim($img, '/');
            if (file_exists($p)) @unlink($p);
        }
        db_exec('DELETE FROM categories WHERE id=:id', ['id'=>$id]);
        header('Location: categories.php?msg=deleted'); exit;
    }

    if ($do === 'reorder' && !empty($_POST['order'])) {
        $order = json_decode($_POST['order'], true);
        if (is_array($order)) {
            foreach ($order as $pos => $cid) {
                db_exec('UPDATE categories SET sort_order=:o WHERE id=:id',
                        ['o' => (int)$pos, 'id' => (int)$cid]);
            }
        }
        exit;
    }
}

$categories = db_all(
    "SELECT c.*,
            (SELECT COUNT(*) FROM listings l
              WHERE l.category_slug = c.slug AND l.published = 1) AS listing_count
       FROM categories c
       ORDER BY c.sort_order, c.name"
);
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.88rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.65rem 1rem;border-bottom:1px solid var(--line);vertical-align:middle;}
.atbl tr:last-child td{border-bottom:none;}
.atbl tbody tr{cursor:grab;}
.atbl tbody tr.dragging{opacity:.5;}
.atbl tbody tr:hover td{background:#fafafa;}
.c-img{width:80px;height:54px;border-radius:6px;overflow:hidden;background:var(--surface-alt);display:flex;align-items:center;justify-content:center;border:1px solid var(--line);}
.c-img img{width:100%;height:100%;object-fit:cover;}
.c-img .no-img{font-size:.7rem;color:var(--ink-light);text-align:center;padding:.3rem;}
.handle{color:var(--ink-light);font-size:1.2rem;padding-right:.5rem;cursor:grab;user-select:none;}
.inline-form{display:inline;}
.inline-form button{background:none;border:none;cursor:pointer;color:#b91c1c;font-size:.82rem;padding:0;font-family:inherit;}
.inline-form button:hover{text-decoration:underline;}
</style>

<?php
$settings_section = 'categories';
require __DIR__ . '/_settings_open.php';
?>

<div class="settings-page-head" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1>Categories <span class="muted" style="font-size:1rem;font-weight:400;">(<?= count($categories) ?>)</span></h1>
        <p class="crumb">Drag rows to reorder · the order controls tile order on the homepage and directory.</p>
    </div>
    <a href="category-edit.php?action=add" class="btn">+ Add category</a>
</div>

<!-- Hidden token for JS-driven reorder -->
<form id="reorder-token-form" style="display:none;"><?= csrf_field() ?></form>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success" data-autohide><?= htmlspecialchars($_GET['msg']==='deleted'?'Category deleted.':$_GET['msg']) ?></div>
<?php endif; ?>
<?php if (isset($_GET['err'])): ?>
    <div class="alert alert-error"><?= htmlspecialchars($_GET['err']) ?></div>
<?php endif; ?>

<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th></th>
                <th>Image</th>
                <th>Name</th>
                <th>Slug</th>
                <th style="text-align:right;">Listings</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody id="cat-tbody">
        <?php foreach ($categories as $c): ?>
            <tr data-id="<?= $c['id'] ?>" draggable="true">
                <td><span class="handle">⋮⋮</span></td>
                <td>
                    <div class="c-img">
                        <?php if (!empty($c['image_path'])): ?>
                            <img src="../<?= htmlspecialchars($c['image_path']) ?>" alt="">
                        <?php else: ?>
                            <span class="no-img">No image</span>
                        <?php endif; ?>
                    </div>
                </td>
                <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
                <td><code style="font-size:.78rem;"><?= htmlspecialchars($c['slug']) ?></code></td>
                <td style="text-align:right;font-weight:600;"><?= $c['listing_count'] ?></td>
                <td style="white-space:nowrap;">
                    <a href="category-edit.php?id=<?= $c['id'] ?>">Edit</a>
                    &nbsp;·&nbsp;
                    <form method="post" class="inline-form"
                          onsubmit="return confirm('Delete this category? This cannot be undone.');">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="delete">
                        <input type="hidden" name="cat_id" value="<?= $c['id'] ?>">
                        <button type="submit">Delete</button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php if (empty($categories)): ?>
    <div class="card" style="margin-top:1rem;"><p class="muted" style="margin:0;">No categories yet. Click "+ Add category" to create one.</p></div>
<?php endif; ?>

<?php require __DIR__ . '/_settings_close.php'; ?>

<script>
// Drag-and-drop reordering
(function () {
    const tbody = document.getElementById('cat-tbody');
    if (!tbody) return;
    let dragEl = null;

    tbody.addEventListener('dragstart', e => {
        const tr = e.target.closest('tr');
        if (!tr) return;
        dragEl = tr;
        tr.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
    });

    tbody.addEventListener('dragover', e => {
        e.preventDefault();
        const tr = e.target.closest('tr');
        if (!tr || tr === dragEl) return;
        const rect = tr.getBoundingClientRect();
        const mid = rect.top + rect.height/2;
        if (e.clientY < mid) tbody.insertBefore(dragEl, tr);
        else                 tbody.insertBefore(dragEl, tr.nextSibling);
    });

    tbody.addEventListener('dragend', () => {
        if (!dragEl) return;
        dragEl.classList.remove('dragging');
        dragEl = null;
        // Save new order
        const order = Array.from(tbody.querySelectorAll('tr')).map(t => t.dataset.id);
        const fd = new FormData();
        fd.append('do', 'reorder');
        fd.append('order', JSON.stringify(order));
        fd.append('_token', document.querySelector('#reorder-token-form input[name=_token]').value);
        fetch('categories.php', { method: 'POST', body: fd });
    });
})();
</script>

<?php require __DIR__ . '/_footer.php'; ?>