<?php

function menu_locations()
{
    return [
        'header'   => 'Üst menü',
        'footer_1' => 'Alt bilgi · 1. sütun',
        'footer_2' => 'Alt bilgi · 2. sütun',
        'footer_3' => 'Alt bilgi · 3. sütun',
    ];
}

function menu_types()
{
    return ['category' => 'Kategori', 'page' => 'Sayfa', 'product' => 'Ürün', 'link' => 'Özel bağlantı'];
}

function menu_column_title($location)
{
    $defaults = ['footer_1' => 'Alışveriş', 'footer_2' => 'Kurumsal', 'footer_3' => 'Yardım'];
    return setting('menu_title_' . $location, $defaults[$location] ?? '');
}

// Konumdaki menüyü ağaç olarak döner: [öğe + children].
function menu_tree($location)
{
    static $cache = [];
    if (!isset($cache[$location])) {
        $rows = db_all('SELECT * FROM menus WHERE location = ? ORDER BY sort, id', [$location]);
        $items = [];
        foreach ($rows as $row) {
            $row['href'] = menu_href($row);
            if ($row['href'] === null) {
                continue;
            }
            $row['children'] = [];
            $items[$row['id']] = $row;
        }
        $tree = [];
        foreach ($items as $id => $item) {
            if ($item['parent_id'] && isset($items[$item['parent_id']])) {
                $items[$item['parent_id']]['children'][] = &$items[$id];
            } else {
                $tree[] = &$items[$id];
            }
        }
        $cache[$location] = $tree;
    }
    return $cache[$location];
}

// Menü öğesinin bağlantısı. Hedefi silinmişse null.
function menu_href($item)
{
    static $lookup = [];
    $key = $item['type'] . ':' . $item['target_id'];
    if (!array_key_exists($key, $lookup)) {
        $lookup[$key] = match ($item['type']) {
            'category' => ($row = db_one('SELECT slug FROM categories WHERE id = ? AND status = 1', [$item['target_id']])) ? category_url($row) : null,
            'page'     => ($row = db_one('SELECT slug FROM pages WHERE id = ? AND status = 1', [$item['target_id']])) ? page_url($row) : null,
            'product'  => ($row = db_one('SELECT slug FROM products WHERE id = ? AND status = 1', [$item['target_id']])) ? product_url($row) : null,
            default    => false,
        };
    }
    return $lookup[$key] === false ? section_link($item['url']) : $lookup[$key];
}

// Panelde menü hiç kurulmamışsa vitrin otomatik içerik gösterir.
function header_menu()
{
    $tree = menu_tree('header');
    if ($tree) {
        return $tree;
    }
    $items = [];
    foreach (array_slice(menu_categories(), 0, (int) theme('header_menu_count') ?: 6) as $category) {
        $items[] = ['label' => $category['name'], 'href' => category_url($category), 'children' => array_map(
            fn($child) => ['label' => $child['name'], 'href' => category_url($child), 'children' => []],
            menu_children($category['id'])
        )];
    }
    $items[] = ['label' => 'Tüm ürünler', 'href' => url('urunler'), 'children' => []];
    return $items;
}

function footer_menu($location)
{
    $tree = menu_tree($location);
    if ($tree) {
        return $tree;
    }
    return match ($location) {
        'footer_1' => array_merge(
            array_map(fn($category) => ['label' => $category['name'], 'href' => category_url($category)], array_slice(menu_categories(), 0, 6)),
            [['label' => 'Tüm ürünler', 'href' => url('urunler')]]
        ),
        'footer_2' => array_map(fn($page) => ['label' => $page['title'], 'href' => page_url($page)], footer_pages()),
        'footer_3' => [
            ['label' => 'İletişim', 'href' => url('iletisim')],
            ['label' => is_customer() ? 'Hesabım' : 'Giriş yap', 'href' => url(is_customer() ? 'hesabim' : 'giris')],
            ['label' => 'Siparişlerim', 'href' => url('siparislerim')],
            ['label' => 'Favorilerim', 'href' => url('favorilerim')],
        ],
        default => [],
    };
}

function menu_is_active($href)
{
    $path = parse_url((string) $href, PHP_URL_PATH) ?: '/';
    return $path !== '/' && rtrim(current_path(), '/') === rtrim($path, '/');
}

// Mevcut kategori ve sayfalardan varsayılan menüleri kurar.
function menus_seed()
{
    if (db_value('SELECT COUNT(*) FROM menus')) {
        return;
    }
    $sort = 0;
    foreach (db_all('SELECT * FROM categories WHERE status = 1 AND parent_id IS NULL ORDER BY sort, name LIMIT 6') as $category) {
        $parent = db_insert('menus', ['location' => 'header', 'label' => $category['name'], 'type' => 'category', 'target_id' => $category['id'], 'sort' => $sort++]);
        $child_sort = 0;
        foreach (db_all('SELECT * FROM categories WHERE status = 1 AND parent_id = ? ORDER BY sort, name', [$category['id']]) as $child) {
            db_insert('menus', ['location' => 'header', 'parent_id' => $parent, 'label' => $child['name'], 'type' => 'category', 'target_id' => $child['id'], 'sort' => $child_sort++]);
        }
    }
    if ($sort) {
        db_insert('menus', ['location' => 'header', 'label' => 'Tüm ürünler', 'type' => 'link', 'url' => '/urunler', 'sort' => $sort]);
    }
}
