<?php ob_start(); ?>

<div class="content-header">
    <h2><?= __('admin.blog_categories.title') ?></h2>
    <div class="header-actions">
        <a href="/admin/blog/tags" class="btn btn-secondary"><?= __('admin.nav.tags') ?></a>
        <a href="/admin/blog" class="btn btn-secondary"><?= __('admin.blog_categories.back') ?></a>
    </div>
</div>

<div style="display:grid; grid-template-columns:1fr 1.6fr; gap:2rem; align-items:start;">

    <!-- Add category form -->
    <div class="form-card">
        <h4><?= __('admin.blog_categories.add_title') ?></h4>
        <form method="POST" action="/admin/blog/categories/store" class="admin-form">
            <?= $csrf->field() ?>

            <div class="form-group">
                <label for="name"><?= __('admin.blog_categories.name') ?> <span class="required">*</span></label>
                <input type="text" id="name" name="name" required
                       oninput="autoCatSlug(this.value)">
            </div>

            <div class="form-group">
                <label for="slug"><?= __('admin.blog_categories.slug') ?></label>
                <input type="text" id="cat-slug" name="slug"
                       placeholder="<?= __('admin.blog_categories.slug_placeholder') ?>">
            </div>

            <div class="form-group">
                <label for="description"><?= __('admin.blog_categories.description') ?></label>
                <textarea id="description" name="description" rows="2"></textarea>
            </div>

            <button type="submit" class="btn btn-primary btn-full"><?= __('admin.blog_categories.add_btn') ?></button>
        </form>
    </div>

    <!-- Category list -->
    <div>

        <!-- Live-search bar -->
        <?php if (count($categories) > 4): ?>
        <div class="filter-bar" style="margin-bottom:1rem;">
            <input type="search" id="cat-search"
                   placeholder="<?= e(__('admin.blog_categories.search_placeholder')) ?>"
                   oninput="filterCats()">
        </div>
        <?php endif; ?>

        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th><?= __('admin.blog_categories.name') ?></th>
                    <th><?= __('admin.blog_categories.slug') ?></th>
                    <th><?= __('admin.blog_categories.posts') ?></th>
                    <th><?= __('admin.common.actions') ?></th>
                </tr>
            </thead>
            <tbody id="cat-tbody">
                <?php if (empty($categories)): ?>
                <tr><td colspan="4" class="text-center text-muted"><?= __('admin.blog_categories.no_categories') ?></td></tr>
                <?php else: ?>
                <?php foreach ($categories as $cat): ?>
                <tr id="cat-row-<?= (int) $cat['id'] ?>"
                    class="cat-data-row"
                    data-id="<?= (int) $cat['id'] ?>"
                    data-name="<?= e(mb_strtolower($cat['name'])) ?>"
                    data-slug="<?= e(mb_strtolower($cat['slug'])) ?>">
                    <!-- Display row -->
                    <td>
                        <strong><?= e($cat['name']) ?></strong>
                        <?php if (!empty($cat['description'])): ?>
                        <br><small class="text-muted"><?= e(mb_substr($cat['description'], 0, 60)) ?><?= mb_strlen($cat['description']) > 60 ? '…' : '' ?></small>
                        <?php endif; ?>
                    </td>
                    <td><code><?= e($cat['slug']) ?></code></td>
                    <td>
                        <?php if ((int) $cat['post_count'] > 0): ?>
                        <a href="/blog/category/<?= e($cat['slug']) ?>" target="_blank"><?= (int) $cat['post_count'] ?></a>
                        <?php else: ?>
                        <span class="text-muted">0</span>
                        <?php endif; ?>
                    </td>
                    <td class="actions">
                        <button type="button" class="btn btn-sm btn-secondary"
                                onclick="toggleCatEdit(<?= (int) $cat['id'] ?>)"><?= __('admin.common.edit') ?></button>
                        <?php if ((int) $cat['post_count'] === 0): ?>
                        <form method="POST" action="/admin/blog/categories/delete/<?= (int) $cat['id'] ?>" class="inline-form"
                              onsubmit="return confirm('<?= e(__('admin.blog_categories.confirm_delete', [':name' => $cat['name']])) ?>')">
                            <?= $csrf->field() ?>
                            <button type="submit" class="btn btn-sm btn-danger"><?= __('admin.common.delete') ?></button>
                        </form>
                        <?php else: ?>
                        <button type="button" class="btn btn-sm btn-danger" disabled
                                title="<?= e(__('admin.blog_categories.cannot_delete', [':count' => $cat['post_count']])) ?>"><?= __('admin.common.delete') ?></button>
                        <?php endif; ?>
                    </td>
                </tr>
                <!-- Inline edit row (hidden by default) -->
                <tr id="cat-edit-<?= (int) $cat['id'] ?>" class="cat-edit-row" style="display:none; background:#f9f9f9;">
                    <td colspan="4" style="padding:1rem;">
                        <form method="POST" action="/admin/blog/categories/update/<?= (int) $cat['id'] ?>" class="admin-form">
                            <?= $csrf->field() ?>
                            <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem; margin-bottom:0.75rem;">
                                <div class="form-group" style="margin-bottom:0;">
                                    <label><?= __('admin.blog_categories.name') ?> <span class="required">*</span></label>
                                    <input type="text" name="name" value="<?= e($cat['name']) ?>" required>
                                </div>
                                <div class="form-group" style="margin-bottom:0;">
                                    <label><?= __('admin.blog_categories.slug') ?></label>
                                    <input type="text" name="slug" value="<?= e($cat['slug']) ?>">
                                </div>
                            </div>
                            <div class="form-group">
                                <label><?= __('admin.blog_categories.description') ?></label>
                                <textarea name="description" rows="2"><?= e($cat['description'] ?? '') ?></textarea>
                            </div>
                            <div style="display:flex; gap:0.5rem;">
                                <button type="submit" class="btn btn-sm btn-primary"><?= __('admin.common.save') ?></button>
                                <button type="button" class="btn btn-sm btn-secondary"
                                        onclick="toggleCatEdit(<?= (int) $cat['id'] ?>)"><?= __('admin.common.cancel') ?></button>
                            </div>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                <tr id="cat-no-results" style="display:none;">
                    <td colspan="4" class="text-center text-muted"><?= __('admin.blog_categories.no_results') ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
        </div>
    </div>

</div>

<script>
function autoCatSlug(val) {
    var s = document.getElementById('cat-slug');
    if (!s._userEdited) {
        s.value = val.toLowerCase()
            .replace(/[äöüÄÖÜ]/g, function(c){return {ä:'ae',ö:'oe',ü:'ue',Ä:'ae',Ö:'oe',Ü:'ue'}[c];})
            .replace(/ß/g,'ss')
            .replace(/[^a-z0-9]+/g,'-')
            .replace(/^-+|-+$/g,'');
    }
}
document.getElementById('cat-slug').addEventListener('input', function(){this._userEdited=true;});

function toggleCatEdit(id) {
    var editRow = document.getElementById('cat-edit-' + id);
    if (editRow.style.display === 'none') {
        editRow.style.display = 'table-row';
    } else {
        editRow.style.display = 'none';
    }
}

function filterCats() {
    var searchEl = document.getElementById('cat-search');
    if (!searchEl) return;
    var q      = searchEl.value.toLowerCase().trim();
    var rows   = document.querySelectorAll('.cat-data-row');
    var visCount = 0;

    rows.forEach(function(row) {
        var name = row.dataset.name || '';
        var slug = row.dataset.slug || '';
        var id   = row.dataset.id;
        var editRow = document.getElementById('cat-edit-' + id);
        var show = !q || name.indexOf(q) !== -1 || slug.indexOf(q) !== -1;

        row.style.display = show ? '' : 'none';
        if (editRow) editRow.style.display = 'none'; // collapse edit row on filter change
        if (show) visCount++;
    });

    var noRes = document.getElementById('cat-no-results');
    if (noRes) noRes.style.display = (visCount === 0 && rows.length > 0) ? 'table-row' : 'none';
}
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
