<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/admin_layout.php';

require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? '');

    if ($action === 'save') {
        $id = trim((string) ($_POST['id'] ?? ''));
        $name = trim((string) ($_POST['name'] ?? ''));
        $parentId = trim((string) ($_POST['parent_id'] ?? ''));
        $slugIn = trim((string) ($_POST['slug'] ?? ''));
        $sort = max(0, (int) ($_POST['sort'] ?? 0));

        if ($name === '') {
            flash('error', 'Kategori adı zorunlu.');
            redirect(url('admin/kategoriler.php'));
        }

        if ($parentId !== '' && !category_find($parentId)) {
            flash('error', 'Üst kategori bulunamadı.');
            redirect(url('admin/kategoriler.php'));
        }

        // Alt kategorinin altına başka kategori yok (2 seviye)
        if ($parentId !== '') {
            $parent = category_find($parentId);
            if ($parent && !empty($parent['parent_id'])) {
                flash('error', 'Sadece ana kategori altına alt kategori eklenebilir (2 seviye).');
                redirect(url('admin/kategoriler.php'));
            }
        }

        $item = $id !== '' ? (category_find($id) ?? ['id' => $id, 'created_at' => date('c')]) : [
            'id' => new_id('c_'),
            'created_at' => date('c'),
        ];

        $slug = $slugIn !== '' ? category_slugify($slugIn) : category_slugify($name);
        if ($parentId !== '') {
            $parent = category_find($parentId);
            $pslug = (string) ($parent['slug'] ?? '');
            if ($pslug !== '' && !str_starts_with($slug, $pslug . '-')) {
                $slug = $pslug . '-' . $slug;
            }
        }

        // slug benzersiz
        foreach (categories_all() as $c) {
            if (($c['slug'] ?? '') === $slug && ($c['id'] ?? '') !== ($item['id'] ?? '')) {
                $slug .= '-' . substr(bin2hex(random_bytes(2)), 0, 3);
                break;
            }
        }

        $item['name'] = $name;
        $item['slug'] = $slug;
        $item['parent_id'] = $parentId;
        $item['sort'] = $sort > 0 ? $sort : ((int) ($item['sort'] ?? 0) ?: 99);
        $item['updated_at'] = date('c');
        store_upsert('categories', $item);
        flash('success', $id !== '' ? 'Kategori güncellendi.' : 'Kategori eklendi.');
        redirect(url('admin/kategoriler.php'));
    }

    if ($action === 'delete') {
        $id = (string) ($_POST['id'] ?? '');
        $children = categories_children($id);
        if ($children) {
            flash('error', 'Önce alt kategorileri sil.');
            redirect(url('admin/kategoriler.php'));
        }
        store_delete('categories', $id);
        flash('success', 'Kategori silindi.');
        redirect(url('admin/kategoriler.php'));
    }

    if ($action === 'reset') {
        store_write('categories', category_seed_defaults());
        flash('success', 'Varsayılan kategoriler yüklendi.');
        redirect(url('admin/kategoriler.php'));
    }
}

$roots = categories_roots();
$editId = (string) ($_GET['edit'] ?? '');
$edit = $editId !== '' ? category_find($editId) : null;

admin_layout_start('Kategoriler', 'categories');
?>

<section class="admin-panel">
    <div class="admin-panel-head">
        <h2><?= $edit ? 'Kategori düzenle' : 'Kategori / alt kategori ekle' ?></h2>
        <form method="post" onsubmit="return confirm('Varsayılan kategoriler yüklensin mi? Mevcut liste değişir.')">
            <input type="hidden" name="action" value="reset">
            <button class="admin-btn ghost sm" type="submit">Varsayılanları yükle</button>
        </form>
    </div>
    <p class="hint">Ana kategori + alt kategori (2 seviye). Ürün eklerken buradan seçilir; ağaç metni otomatik oluşur.</p>

    <form method="post" class="admin-form">
        <input type="hidden" name="action" value="save">
        <?php if ($edit): ?>
            <input type="hidden" name="id" value="<?= e((string) $edit['id']) ?>">
        <?php endif; ?>
        <div class="admin-form-row">
            <label>Ad
                <input type="text" name="name" required value="<?= e($edit['name'] ?? '') ?>" placeholder="Örn. Zeytinyağı / Soğuk Sıkım">
            </label>
            <label>Üst kategori
                <select name="parent_id">
                    <option value="">— Ana kategori —</option>
                    <?php foreach ($roots as $r): ?>
                        <?php if ($edit && ($edit['id'] ?? '') === ($r['id'] ?? '')) continue; ?>
                        <option value="<?= e((string) $r['id']) ?>" <?= (($edit['parent_id'] ?? '') === ($r['id'] ?? '')) ? 'selected' : '' ?>>
                            <?= e($r['name'] ?? '') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>
        </div>
        <div class="admin-form-row">
            <label>Slug (opsiyonel)
                <input type="text" name="slug" value="<?= e($edit['slug'] ?? '') ?>" placeholder="otomatik üretilir">
            </label>
            <label>Sıra
                <input type="number" name="sort" min="0" value="<?= (int) ($edit['sort'] ?? 0) ?>">
            </label>
        </div>
        <div style="display:flex;gap:0.5rem;flex-wrap:wrap">
            <button class="admin-btn" type="submit"><?= $edit ? 'Güncelle' : 'Ekle' ?></button>
            <?php if ($edit): ?>
                <a class="admin-btn ghost" href="<?= e(url('admin/kategoriler.php')) ?>">İptal</a>
            <?php endif; ?>
        </div>
    </form>
</section>

<section class="admin-panel">
    <h2>Kategori ağacı (<?= count(categories_all()) ?>)</h2>
    <?php if (!$roots): ?>
        <p class="hint">Henüz kategori yok.</p>
    <?php endif; ?>
    <?php foreach ($roots as $root):
        $kids = categories_children((string) $root['id']);
    ?>
        <div class="admin-order" style="margin-bottom:0.75rem">
            <div class="admin-order-head">
                <strong><?= e($root['name'] ?? '') ?></strong>
                <span class="admin-badge paid">Ana</span>
            </div>
            <p class="hint"><?= e($root['slug'] ?? '') ?> · sıra <?= (int) ($root['sort'] ?? 0) ?></p>
            <div style="display:flex;gap:0.4rem;flex-wrap:wrap;margin-top:0.45rem">
                <a class="admin-btn ghost sm" href="<?= e(url('admin/kategoriler.php?edit=' . urlencode((string) $root['id']))) ?>">Düzenle</a>
                <form method="post" onsubmit="return confirm('Ana kategori silinsin mi?')">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= e((string) $root['id']) ?>">
                    <button class="admin-btn danger sm" type="submit" <?= $kids ? 'disabled title="Önce altları sil"' : '' ?>>Sil</button>
                </form>
            </div>
            <?php if ($kids): ?>
                <div style="margin-top:0.75rem;padding-left:0.75rem;border-left:3px solid #d7e5d4;display:grid;gap:0.45rem">
                    <?php foreach ($kids as $kid): ?>
                        <div style="display:flex;justify-content:space-between;gap:0.5rem;flex-wrap:wrap;align-items:center">
                            <div>
                                <strong><?= e($kid['name'] ?? '') ?></strong>
                                <span class="hint"> · <?= e($kid['slug'] ?? '') ?></span>
                            </div>
                            <div style="display:flex;gap:0.35rem">
                                <a class="admin-btn ghost sm" href="<?= e(url('admin/kategoriler.php?edit=' . urlencode((string) $kid['id']))) ?>">Düzenle</a>
                                <form method="post" onsubmit="return confirm('Alt kategori silinsin mi?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= e((string) $kid['id']) ?>">
                                    <button class="admin-btn danger sm" type="submit">Sil</button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="hint" style="margin-top:0.5rem">Alt kategori yok — yukarıdan üst kategori seçerek ekle.</p>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
</section>

<?php admin_layout_end(); ?>
