<?php
declare(strict_types=1);

/** @return list<array<string,mixed>> */
function category_seed_defaults(): array
{
    $roots = [
        ['slug' => 'bal-recel', 'name' => 'Bal & Reçel', 'children' => ['Süzme Bal', 'Karakovan', 'Reçel', 'Pekmez']],
        ['slug' => 'zeytinyagi', 'name' => 'Zeytinyağı', 'children' => ['Soğuk Sıkım', 'Erken Hasat', 'Naturel Sızma']],
        ['slug' => 'kuruyemis', 'name' => 'Kuruyemiş', 'children' => ['Fındık', 'Ceviz', 'Badem', 'Kurutulmuş Meyve']],
        ['slug' => 'baharat', 'name' => 'Baharat', 'children' => ['Kekik', 'Sumak', 'Karışık Baharat']],
        ['slug' => 'cay-bitki', 'name' => 'Çay & Bitki', 'children' => ['Bitki Çayı', 'Adaçayı', 'Ihlamur']],
        ['slug' => 'sut-urun', 'name' => 'Süt Ürünleri', 'children' => ['Peynir', 'Tereyağı', 'Yoğurt']],
        ['slug' => 'diger', 'name' => 'Diğer', 'children' => ['Genel']],
    ];

    $out = [];
    $sort = 1;
    foreach ($roots as $root) {
        $parentId = 'c_' . $root['slug'];
        $out[] = [
            'id' => $parentId,
            'slug' => $root['slug'],
            'name' => $root['name'],
            'parent_id' => '',
            'sort' => $sort++,
            'created_at' => date('c'),
        ];
        $cSort = 1;
        foreach ($root['children'] as $childName) {
            $childSlug = category_slugify($childName);
            $out[] = [
                'id' => 'c_' . $root['slug'] . '_' . $childSlug,
                'slug' => $root['slug'] . '-' . $childSlug,
                'name' => $childName,
                'parent_id' => $parentId,
                'sort' => $cSort++,
                'created_at' => date('c'),
            ];
        }
    }
    return $out;
}

function category_slugify(string $name): string
{
    $map = [
        'ş' => 's', 'Ş' => 's', 'ı' => 'i', 'İ' => 'i', 'I' => 'i',
        'ğ' => 'g', 'Ğ' => 'g', 'ü' => 'u', 'Ü' => 'u',
        'ö' => 'o', 'Ö' => 'o', 'ç' => 'c', 'Ç' => 'c',
        '&' => '',
    ];
    $s = strtr(trim($name), $map);
    $s = mb_strtolower($s);
    $s = preg_replace('/[^a-z0-9]+/u', '-', $s) ?? '';
    $s = trim($s, '-');
    return $s !== '' ? $s : 'kat';
}

/** @return list<array<string,mixed>> */
function categories_all(): array
{
    $items = store_read('categories');
    if (!$items) {
        $items = category_seed_defaults();
        store_write('categories', $items);
    }
    usort($items, static function (array $a, array $b): int {
        $pa = (string) ($a['parent_id'] ?? '');
        $pb = (string) ($b['parent_id'] ?? '');
        if ($pa !== $pb) {
            return strcmp($pa, $pb);
        }
        return ((int) ($a['sort'] ?? 0)) <=> ((int) ($b['sort'] ?? 0));
    });
    return $items;
}

function category_find(string $id): ?array
{
    if ($id === '') {
        return null;
    }
    foreach (categories_all() as $c) {
        if (($c['id'] ?? '') === $id) {
            return $c;
        }
    }
    return null;
}

function category_find_by_slug(string $slug): ?array
{
    if ($slug === '') {
        return null;
    }
    foreach (categories_all() as $c) {
        if (($c['slug'] ?? '') === $slug) {
            return $c;
        }
    }
    return null;
}

/** @return list<array<string,mixed>> */
function categories_roots(): array
{
    return array_values(array_filter(
        categories_all(),
        static fn(array $c): bool => empty($c['parent_id'])
    ));
}

/** @return list<array<string,mixed>> */
function categories_children(string $parentId): array
{
    if ($parentId === '') {
        return [];
    }
    return array_values(array_filter(
        categories_all(),
        static fn(array $c): bool => ($c['parent_id'] ?? '') === $parentId
    ));
}

/** Vitrin filtreleri: ana kategori slug => ad */
function categories(): array
{
    $map = [];
    foreach (categories_roots() as $c) {
        $slug = (string) ($c['slug'] ?? '');
        if ($slug !== '') {
            $map[$slug] = (string) ($c['name'] ?? $slug);
        }
    }
    if (!$map) {
        $map = ['diger' => 'Diğer'];
    }
    return $map;
}

/** Tüm slug => ad (etiket için) */
function categories_flat_labels(): array
{
    $map = [];
    foreach (categories_all() as $c) {
        $slug = (string) ($c['slug'] ?? '');
        if ($slug !== '') {
            $map[$slug] = (string) ($c['name'] ?? $slug);
        }
    }
    return $map;
}

function category_label(string $slug): string
{
    $row = category_find_by_slug($slug);
    if ($row) {
        return (string) ($row['name'] ?? $slug);
    }
    $flat = categories_flat_labels();
    return $flat[$slug] ?? ($slug !== '' ? $slug : 'Diğer');
}

function category_tree_text(?array $parent, ?array $child): string
{
    $parts = [];
    if ($parent) {
        $parts[] = (string) ($parent['name'] ?? '');
    }
    if ($child) {
        $parts[] = (string) ($child['name'] ?? '');
    }
    $parts = array_values(array_filter($parts));
    return implode(' > ', $parts);
}

/** Ürün ana kategori slug’ı (filtre için). */
function product_category_root_slug(array $product): string
{
    $parentId = (string) ($product['category_parent_id'] ?? '');
    if ($parentId !== '') {
        $p = category_find($parentId);
        if ($p) {
            return (string) ($p['slug'] ?? '');
        }
    }
    $slug = (string) ($product['category'] ?? '');
    $row = category_find_by_slug($slug);
    if ($row && !empty($row['parent_id'])) {
        $parent = category_find((string) $row['parent_id']);
        return (string) ($parent['slug'] ?? $slug);
    }
    return $slug;
}
