<?php

declare(strict_types=1);

class MenuConfig
{
    private static array $internalLinks = [
        'home'            => ['label_key' => 'home',             'url' => '/',                    'templates' => ['home']],
        'categories'      => ['label_key' => 'categories',       'url' => '/categories',          'templates' => ['categories', 'category']],
        'tags'            => ['label_key' => 'tags',             'url' => '/tags',                'templates' => ['tags', 'tag']],
        'pornstars'       => ['label_key' => 'pornstars',        'url' => '/pornstars',           'templates' => ['performers', 'performer']],
        'channels'         => ['label_key' => 'channels',          'url' => '/channels',             'templates' => ['channels', 'channel']],
        'albums'          => ['label_key' => 'albums',           'url' => '/albums',              'templates' => ['albums', 'album']],
        'new_videos'      => ['label_key' => 'new_videos',       'url' => '/videos/', 'slug_key' => 'slug_new_videos',       'templates' => ['video-list']],
        'top_rated'       => ['label_key' => 'top_rated',        'url' => '/videos/', 'slug_key' => 'slug_top_rated',        'templates' => ['video-list']],
        'most_viewed'     => ['label_key' => 'most_viewed',      'url' => '/videos/', 'slug_key' => 'slug_most_viewed',      'templates' => ['video-list']],
        'most_favorited'  => ['label_key' => 'most_favorited',   'url' => '/videos/', 'slug_key' => 'slug_most_favorited',   'templates' => ['video-list']],
        'vtype_switcher'  => ['label_key' => 'vtype_switcher',   'url' => '#',                    'templates' => [], 'widget' => true],
    ];

    public static function get(): array
    {
        $json = Setting::get('menu_config', '');
        if ($json !== '' && $json !== null) {
            $config = json_decode($json, true);
             
             
            if (is_array($config) && isset($config['items']) && is_array($config['items'])) {
                return $config;
            }
        }
        return self::getDefault();
    }

    public static function getDefault(): array
    {
        $items = [];
        $items[] = ['id' => 'home', 'type' => 'internal', 'label' => 'Home', 'url' => '/', 'icon' => 'house', 'children' => []];

        if (Setting::get('menu_categories', '1') === '1') {
            $items[] = ['id' => 'categories', 'type' => 'internal', 'label' => 'Categories', 'url' => '/categories', 'icon' => 'grid-2', 'children' => []];
        }
        if (Setting::get('menu_tags', '1') === '1') {
            $items[] = ['id' => 'tags', 'type' => 'internal', 'label' => 'Tags', 'url' => '/tags', 'icon' => 'tags', 'children' => []];
        }
        if (Setting::get('menu_pornstars', '1') === '1') {
            $items[] = ['id' => 'pornstars', 'type' => 'internal', 'label' => 'Pornstars', 'url' => '/pornstars', 'icon' => 'users', 'children' => []];
        }
        if (Setting::get('menu_channels', '1') === '1') {
            $items[] = ['id' => 'channels', 'type' => 'internal', 'label' => 'Channels', 'url' => '/channels', 'icon' => 'clapperboard', 'children' => []];
        }
        if (Setting::get('menu_albums', '1') === '1') {
            $items[] = ['id' => 'albums', 'type' => 'internal', 'label' => 'Albums', 'url' => '/albums', 'icon' => 'images', 'children' => []];
        }

        return ['items' => $items];
    }

    public static function save(array $config): void
    {
        Setting::set('menu_config', json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    public static function fromPost(string $json): array
    {
        if ($json === '') {
            return self::getDefault();
        }

        $data = json_decode($json, true);
        if (!is_array($data) || !isset($data['items'])) {
            return self::getDefault();
        }

        $items = [];
        foreach ($data['items'] as $item) {
            $items[] = self::sanitizeItem($item);
        }

        return ['items' => $items];
    }

    private static function sanitizeItem(array $item): array
    {
        $type = $item['type'] ?? 'custom';
        if (!in_array($type, ['internal', 'page', 'custom'], true)) {
            $type = 'custom';
        }

         
        $icon = trim($item['icon'] ?? '');
        if ($icon !== '' && !preg_match('/^[a-z0-9-]+$/', $icon)) {
            $icon = '';
        }

        $sanitized = [
            'id'       => substr(preg_replace('/[^a-z0-9_]/', '', $item['id'] ?? ''), 0, 50),
            'type'     => $type,
            'label'    => substr(trim($item['label'] ?? ''), 0, 100),
            'icon'     => $icon,
            'children' => [],
        ];

        if ($type === 'custom') {
            $url = trim($item['url'] ?? '');
             
            if ($url !== '' && !preg_match('#^(/|https?://)#i', $url)) {
                $url = '';
            }
            $sanitized['url'] = $url;
            $sanitized['target'] = ($item['target'] ?? '') === '_blank' ? '_blank' : '_self';
        } elseif ($type === 'internal') {
            $sanitized['url'] = $item['url'] ?? '/';
        } elseif ($type === 'page') {
            $sanitized['page_id'] = (int) ($item['page_id'] ?? 0);
        }

         
        if (($item['id'] ?? '') === 'categories') {
            $sanitized['mega_menu'] = ($item['mega_menu'] ?? true) !== false;
        }

         
        $translations = [];
        if (!empty($item['_translations']) && is_array($item['_translations'])) {
            foreach ($item['_translations'] as $langCode => $text) {
                $langCode = preg_replace('/[^a-z]/', '', (string)$langCode);
                if (strlen($langCode) === 2) {
                    $text = substr(trim((string)$text), 0, 100);
                    if ($text !== '') {
                        $translations[$langCode] = $text;
                    }
                }
            }
        }
        if (!empty($translations)) {
            $sanitized['_translations'] = $translations;
        }

         
        if (!empty($item['children']) && is_array($item['children'])) {
            foreach ($item['children'] as $child) {
                $childSanitized = self::sanitizeItem($child);
                $childSanitized['children'] = [];  
                $sanitized['children'][] = $childSanitized;
            }
        }

        return $sanitized;
    }

    public static function resolve(array $config): array
    {
        $items = $config['items'] ?? [];
        $resolved = [];

        foreach ($items as $item) {
            $r = self::resolveItem($item);
            if ($r !== null) {
                $resolved[] = $r;
            }
        }

        return $resolved;
    }

    private static function resolveItem(array $item): ?array
    {
        $type = $item['type'] ?? 'custom';
        $result = [
            'id'        => $item['id'] ?? '',
            'label'     => $item['label'] ?? '',
            'icon'      => $item['icon'] ?? '',
            'url'       => '',
            'target'    => $item['target'] ?? '_self',
            'templates' => [],
            'children'  => [],
        ];

        switch ($type) {
            case 'internal':
                $key = $item['id'] ?? '';
                if (isset(self::$internalLinks[$key])) {
                    $def = self::$internalLinks[$key];
                    $result['label'] = __($def['label_key']);
                    if (!empty($def['slug_key'])) {
                        $result['url'] = Router::url($def['url'] . Translator::slug($def['slug_key'], $def['label_key']));
                    } else {
                        $result['url'] = Router::url($def['url']);
                    }
                    $result['templates'] = $def['templates'];
                    if (!empty($def['widget'])) {
                        $result['widget'] = $key;
                    }
                } else {
                    $result['url'] = Router::url($item['url'] ?? '/');
                }
                break;

            case 'page':
                $pageId = (int) ($item['page_id'] ?? 0);
                if ($pageId > 0) {
                    $page = Page::find($pageId);
                    if ($page && ($page['status'] ?? '') === 'published') {
                        $currentLang = Translator::locale();
                        $defaultLang = Translator::getDefaultCode();
                        $slug = $page['slug'];
                        $label = $item['label'] ?? $page['title'];
                        if ($currentLang !== $defaultLang) {
                            $trans = Page::translation($pageId, $currentLang);
                            if ($trans) {
                                $slug = $trans['slug'];
                                $label = $trans['title'];
                            }
                        }
                        $result['label'] = $label;
                        $result['url'] = Router::url('/' . $slug);
                        $result['templates'] = ['page'];
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
                break;

            case 'custom':
                $result['url'] = $item['url'] ?? '#';
                $result['target'] = ($item['target'] ?? '_self') === '_blank' ? '_blank' : '_self';
                break;
        }

         
        if (($item['id'] ?? '') === 'categories' && isset($item['mega_menu'])) {
            $result['mega_menu'] = (bool) $item['mega_menu'];
        }

         
        $currentLang = Translator::locale();
        $defaultLang = Translator::getDefaultCode();
        if ($currentLang !== $defaultLang && !empty($item['_translations'][$currentLang])) {
            $result['label'] = $item['_translations'][$currentLang];
        }

         
        if (!empty($item['children'])) {
            foreach ($item['children'] as $child) {
                $rc = self::resolveItem($child);
                if ($rc !== null) {
                    $rc['children'] = [];  
                    $result['children'][] = $rc;
                }
            }
        }

        return $result;
    }
}
