<?php

declare(strict_types=1);

class FooterConfig
{
    public static function get(): array
    {
        $json = Setting::get('footer_config', '');
        if ($json !== '' && $json !== null) {
            $config = json_decode($json, true);
            if (is_array($config)) {
                return $config;
            }
        }
        return self::getDefault();
    }

    public static function getDefault(): array
    {
        $social = [];
        foreach (['twitter', 'instagram', 'reddit', 'telegram', 'discord'] as $key) {
            $social[$key] = Setting::get('social_' . $key, '') ?: '';
        }

        return [
            'columns' => [
                ['type' => 'logo', 'title' => '', 'enabled' => true],
                ['type' => 'navigation', 'title' => 'Navigation', 'enabled' => true],
                ['type' => 'pages', 'title' => 'Pages', 'page_ids' => [], 'enabled' => true],
                ['type' => 'badges', 'title' => 'About', 'enabled' => true, 'badges' => [
                    ['icon' => 'shield', 'label' => '18+ Only'],
                    ['icon' => 'upload', 'label' => 'Free Content'],
                    ['icon' => 'video', 'label' => 'HD Videos'],
                ]],
            ],
            'bottom' => [
                'show_copyright' => true,
                'copyright_text' => '',
                'show_disclaimer' => true,
                'disclaimer_text' => '',
                'show_social' => true,
            ],
            'social' => $social,
        ];
    }

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

         
        if (isset($config['social'])) {
            foreach ($config['social'] as $key => $url) {
                Setting::set('social_' . $key, $url);
            }
        }
    }

    public static function columnTypes(): array
    {
        return [
            'logo'         => ['label' => 'Logo & Description', 'hasConfig' => false],
            'navigation'   => ['label' => 'Navigation Links', 'hasConfig' => true],
            'pages'        => ['label' => 'CMS Pages', 'hasConfig' => true],
            'custom_links' => ['label' => 'Custom Links', 'hasConfig' => true],
            'badges'       => ['label' => 'Info Badges', 'hasConfig' => true],
            'text'         => ['label' => 'Custom Text/HTML', 'hasConfig' => true],
            'social'       => ['label' => 'Social Media Icons', 'hasConfig' => false],
        ];
    }

    public static function badgeIcons(): array
    {
        return [
            'shield'   => ['label' => 'Shield', 'svg' => '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>'],
            'upload'   => ['label' => 'Upload', 'svg' => '<circle cx="12" cy="12" r="10"></circle><polyline points="16 12 12 8 8 12"></polyline><line x1="12" y1="16" x2="12" y2="8"></line>'],
            'video'    => ['label' => 'Video', 'svg' => '<polygon points="23 7 16 12 23 17 23 7"></polygon><rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect>'],
            'star'     => ['label' => 'Star', 'svg' => '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>'],
            'check'    => ['label' => 'Check', 'svg' => '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline>'],
            'heart'    => ['label' => 'Heart', 'svg' => '<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>'],
            'globe'    => ['label' => 'Globe', 'svg' => '<circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path>'],
            'lock'     => ['label' => 'Lock', 'svg' => '<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path>'],
            'zap'      => ['label' => 'Zap', 'svg' => '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon>'],
            'award'    => ['label' => 'Award', 'svg' => '<circle cx="12" cy="8" r="7"></circle><polyline points="8.21 13.89 7 23 12 20 17 23 15.79 13.88"></polyline>'],
        ];
    }

    private const SEEDED_LABEL_KEYS = [
        '18+ Only'     => 'footer_badge_18',
        'Free Content' => 'footer_badge_free',
        'HD Videos'    => 'footer_badge_hd',
        'Navigation'   => 'navigation',
        'Pages'        => 'pages',
        'About'        => 'about_site',
    ];

    private static function translationsFor(mixed $bag, string $field): array
    {
        if (!is_array($bag)) {
            return [];
        }
        $set = $bag[$field] ?? null;
        return is_array($set) ? $set : [];
    }

    private static function localizedText(string $value, array $translations, string $locale, bool $translate): string
    {
        if (!$translate) {
            return $value;
        }
        if (($translations[$locale] ?? '') !== '') {
            return (string) $translations[$locale];
        }
        $key = self::SEEDED_LABEL_KEYS[$value] ?? null;
        if ($key !== null) {
            $translated = __($key);
            if ($translated !== '' && $translated !== $key) {
                return $translated;
            }
        }
        return $value;
    }

    private static function localizeList(mixed $rows, string $field, string $locale, bool $translate): array
    {
        if (!is_array($rows)) {
            return [];
        }
        foreach ($rows as &$row) {
            if (!is_array($row) || !isset($row[$field])) {
                continue;
            }
            $row[$field] = self::localizedText(
                (string) $row[$field],
                self::translationsFor($row['_translations'] ?? null, $field),
                $locale,
                $translate
            );
        }
        unset($row);
        return $rows;
    }

    public static function resolveColumns(array $config): array
    {
        $columns = $config['columns'] ?? [];
        $resolved = [];
        $locale = Translator::locale();
        $translate = ($locale !== Translator::getDefaultCode());

        foreach ($columns as $col) {
             
            if (isset($col['enabled']) && !$col['enabled']) {
                continue;
            }

            $type = $col['type'] ?? 'text';
            $item = [
                'type'           => $type,
                'title'          => self::localizedText((string) ($col['title'] ?? ''), self::translationsFor($col['_translations'] ?? null, 'title'), $locale, $translate),
                '_translations'  => $col['_translations'] ?? [],
            ];

            switch ($type) {
                case 'logo':
                    $customLogo = $col['custom_logo'] ?? '';
                    $item['custom_logo'] = $customLogo;
                    $item['logo'] = $customLogo ?: (Setting::get('site_logo_dark', '') ?: Setting::get('site_logo', ''));
                    $item['site_name'] = Branding::siteName();
                    $item['logo_height'] = (int) ($col['logo_height'] ?? 32);
                    $item['show_description'] = $col['show_description'] ?? true;
                    $item['description'] = self::localizedText(
                        (string) ($col['description'] ?? ''),
                        self::translationsFor($col['_translations'] ?? null, 'description'),
                        $locale,
                        $translate
                    );
                    if ($item['description'] === '') {
                        $item['description'] = Branding::siteDescription();
                    }
                    break;

                case 'navigation':
                    $item['nav_items'] = $col['nav_items'] ?? [];
                    $item['custom_links'] = self::localizeList($col['custom_links'] ?? [], 'label', $locale, $translate);
                    break;

                case 'pages':
                    $pageIds = $col['page_ids'] ?? [];
                    if (!empty($pageIds)) {
                        $item['pages'] = Page::findByIds($pageIds);
                    } else {
                        $item['pages'] = Page::footerPages();
                    }
                    break;

                case 'custom_links':
                    $item['links'] = self::localizeList($col['links'] ?? [], 'label', $locale, $translate);
                    break;

                case 'badges':
                    $item['badges'] = self::localizeList($col['badges'] ?? [], 'label', $locale, $translate);
                    break;

                case 'text':
                    $item['content'] = $col['content'] ?? '';
                    break;

                case 'social':
                    $social = $config['social'] ?? [];
                    $allLinks = array_filter($social, fn($v) => $v !== '');
                    $selectedItems = $col['social_items'] ?? null;
                    if ($selectedItems !== null) {
                        $allLinks = array_filter($allLinks, fn($v, $k) => in_array($k, $selectedItems, true), ARRAY_FILTER_USE_BOTH);
                    }
                    $item['links'] = $allLinks;
                    break;
            }

            $resolved[] = $item;
        }

        return $resolved;
    }

    public static function fromPost(array $post): array
    {
        $colCount = max(1, min(4, (int) ($post['footer_col_count'] ?? 4)));

        $columns = [];
        for ($i = 0; $i < $colCount; $i++) {
            $type = $post['footer_col_type'][$i] ?? 'text';
            if (!array_key_exists($type, self::columnTypes())) {
                $type = 'text';
            }

            $col = [
                'type'    => $type,
                'title'   => trim($post['footer_col_title'][$i] ?? ''),
                'enabled' => isset($post['footer_col_enabled'][$i]),
            ];

             
            $titleTl = array_filter(array_map('trim', $post['footer_col_title_translations'][$i] ?? []), fn($v) => $v !== '');
            if (!empty($titleTl)) {
                $col['_translations'] = ['title' => $titleTl];
            }

            switch ($type) {
                case 'logo':
                    $col['logo_height'] = max(16, min(64, (int) ($post['footer_col_logo_height'][$i] ?? 32)));
                    $col['show_description'] = isset($post['footer_col_show_desc'][$i]);
                    $col['description'] = trim($post['footer_col_description'][$i] ?? '');
                    $descTl = array_filter(array_map('trim', $post['footer_col_description_translations'][$i] ?? []), fn($v) => $v !== '');
                    if (!empty($descTl)) {
                        $col['_translations'] = array_merge($col['_translations'] ?? [], ['description' => $descTl]);
                    }
                     
                    break;

                case 'navigation':
                    $col['nav_items'] = array_values(array_filter(
                        array_map('trim', $post['footer_col_nav_items'][$i] ?? []),
                        fn($v) => $v !== ''
                    ));
                     
                    $cLabels = $post['footer_col_nav_custom_label'][$i] ?? [];
                    $cUrls = $post['footer_col_nav_custom_url'][$i] ?? [];
                    $cLabelTl = $post['footer_col_nav_custom_label_translations'][$i] ?? [];
                    $customLinks = [];
                    foreach ($cLabels as $j => $cLabel) {
                        $cLabel = trim($cLabel);
                        $cUrl = trim($cUrls[$j] ?? '');
                        if ($cLabel !== '' && $cUrl !== '') {
                            $cl = ['label' => $cLabel, 'url' => $cUrl];
                            $tl = array_filter(array_map('trim', $cLabelTl[$j] ?? []), fn($v) => $v !== '');
                            if (!empty($tl)) {
                                $cl['_translations'] = ['label' => $tl];
                            }
                            $customLinks[] = $cl;
                        }
                    }
                    $col['custom_links'] = $customLinks;
                    break;

                case 'pages':
                    $col['page_ids'] = array_map('intval', $post['footer_col_pages'][$i] ?? []);
                    break;

                case 'custom_links':
                    $links = [];
                    $labels = $post['footer_col_link_label'][$i] ?? [];
                    $urls = $post['footer_col_link_url'][$i] ?? [];
                    $linkLabelTl = $post['footer_col_link_label_translations'][$i] ?? [];
                    $linkIdx = 0;
                    foreach ($labels as $j => $label) {
                        $label = trim($label);
                        $url = trim($urls[$j] ?? '');
                        if ($label !== '' && $url !== '') {
                            $link = ['label' => $label, 'url' => $url];
                            $tl = array_filter(array_map('trim', $linkLabelTl[$j] ?? []), fn($v) => $v !== '');
                            if (!empty($tl)) {
                                $link['_translations'] = ['label' => $tl];
                            }
                            $links[] = $link;
                            $linkIdx++;
                        }
                    }
                    $col['links'] = $links;
                    break;

                case 'badges':
                    $badges = [];
                    $icons = $post['footer_col_badge_icon'][$i] ?? [];
                    $badgeLabels = $post['footer_col_badge_label'][$i] ?? [];
                    $badgeLabelTl = $post['footer_col_badge_label_translations'][$i] ?? [];
                    $validIcons = self::badgeIcons();
                    foreach ($icons as $j => $icon) {
                        $label = trim($badgeLabels[$j] ?? '');
                        if ($label !== '' && isset($validIcons[$icon])) {
                            $badge = ['icon' => $icon, 'label' => $label];
                            $tl = array_filter(array_map('trim', $badgeLabelTl[$j] ?? []), fn($v) => $v !== '');
                            if (!empty($tl)) {
                                $badge['_translations'] = ['label' => $tl];
                            }
                            $badges[] = $badge;
                        }
                    }
                    $col['badges'] = $badges;
                    break;

                case 'social':
                    $validSocials = ['twitter', 'instagram', 'reddit', 'telegram', 'discord'];
                    $items = $post['footer_col_social_items'][$i] ?? null;
                    if ($items !== null) {
                        $col['social_items'] = array_values(array_intersect((array) $items, $validSocials));
                    }
                    break;

                case 'text':
                    $col['content'] = $post['footer_col_content'][$i] ?? '';
                    break;
            }

            $columns[] = $col;
        }

        $bottom = [
            'show_copyright'  => isset($post['footer_show_copyright']),
            'copyright_text'  => trim($post['footer_copyright_text'] ?? ''),
            'show_disclaimer' => isset($post['footer_show_disclaimer']),
            'disclaimer_text' => trim($post['footer_disclaimer_text'] ?? ''),
            'show_social'     => isset($post['footer_show_social']),
        ];

         
        $copyrightTl = array_filter(array_map('trim', $post['footer_copyright_text_translations'] ?? []), fn($v) => $v !== '');
        $disclaimerTl = array_filter(array_map('trim', $post['footer_disclaimer_text_translations'] ?? []), fn($v) => $v !== '');
        if (!empty($copyrightTl) || !empty($disclaimerTl)) {
            $bottom['_translations'] = [];
            if (!empty($copyrightTl)) {
                $bottom['_translations']['copyright_text'] = $copyrightTl;
            }
            if (!empty($disclaimerTl)) {
                $bottom['_translations']['disclaimer_text'] = $disclaimerTl;
            }
        }

        $social = [];
        foreach (['twitter', 'instagram', 'reddit', 'telegram', 'discord'] as $key) {
            $val = trim($post['social_' . $key] ?? '');
            if ($val !== '' && !preg_match('#^https?://#i', $val)) {
                $val = '';
            }
            $social[$key] = $val;
        }

        return [
            'columns' => $columns,
            'bottom'  => $bottom,
            'social'  => $social,
        ];
    }
}
