<?php

namespace Core\App\Services;

use Core\App\Models\Footer;
use Core\App\Models\FooterLink;
use Core\App\Models\Settings;
use Core\App\Models\Page;
use Core\System\ThemeManager;

class FooterBuilder
{
    public static function build(): array
    {
        $footerModel   = new Footer();
        $settingsModel = new Settings();
        $pageModel     = new Page();

        $settings = $settingsModel->getAll();
        $pages    = $pageModel->getAllIndexed('id');

        $rawSections = $footerModel->getAll();
        usort($rawSections, fn($a, $b) => ($a['position'] ?? 0) <=> ($b['position'] ?? 0));

        $sections = [];

        // Branding section always first (if exists & active)
        foreach ($rawSections as $section) {
            if (($section['type'] ?? '') === 'branding' && (int)($section['status'] ?? 0) === 1) {
                $branding = self::buildBrandingSection($section, $settings);
                if (!empty($branding)) {
                    $sections[] = $branding;
                }
                break;
            }
        }

        // Other sections
        foreach ($rawSections as $section) {
            if ((int)($section['status'] ?? 0) !== 1) {
                continue;
            }

            if (($section['type'] ?? '') === 'branding') {
                continue;
            }

            if (count($sections) >= 4) {
                break;
            }

            $built = self::buildSection($section, $pages, $settings);
            if (!empty($built)) {
                $sections[] = $built;
            }
        }

        return [
            'direction' => self::isRTL() ? 'rtl' : 'ltr',
            'sections'  => $sections,
            'copyright' =>
                $settings['copyright_text']
                ?? ('© ' . date('Y') . ' ' . ($settings['site_name'] ?? '')),
        ];
    }

    private static function buildSection(array $section, array $pages, array $settings): array
    {
        return match ($section['type'] ?? 'links') {
            'links', 'pages' => self::buildLinksSection($section, $pages),
            'social'         => self::buildSocialSection($section),
            'contact'        => self::buildContactSection($section, $settings),
            default          => [],
        };
    }

    private static function buildBrandingSection(array $section, array $settings): array
    {
        $logo =
            $settings['site_logo']
            ?? ThemeManager::getSetting('logo')
            ?? null;

        $description =
            $settings['site_description']
            ?? $settings['site_tagline']
            ?? null;

        if (empty($logo) && empty($description)) {
            return [];
        }

        return [
            'id'    => $section['id'] ?? null,
            'title' => $section['title'] ?? '',
            'type'  => 'branding',
            'items' => [
                'logo'        => $logo,
                'description' => $description,
            ],
            'position' => 0,
        ];
    }

    private static function buildLinksSection(array $section, array $pages): array
    {
        $footerModel = new Footer();
        $links = $footerModel->getLinks((int)$section['id']);

        $items = [];

        foreach ($links as $link) {
            if ((int)($link['is_enabled'] ?? 0) !== 1) {
                continue;
            }

            if (count($items) >= 4) {
                break;
            }

            $items[] = [
                'label' => $link['label'] ?? '',
                'url'   => self::resolveLinkUrl($link, $pages),
            ];
        }

        return [
            'id'    => $section['id'] ?? null,
            'title' => $section['title'] ?? '',
            'type'  => 'links',
            'items' => $items,
            'position' => (int)($section['position'] ?? 0),
        ];
    }

    private static function buildSocialSection(array $section): array
    {
        $footerLinkModel = new FooterLink();
        $links = $footerLinkModel->getBySection((int)$section['id']);

        $items = [];

        foreach ($links as $link) {
            if ((int)($link['is_enabled'] ?? 0) !== 1) {
                continue;
            }

            if (count($items) >= 4) {
                break;
            }

            $network = $link['label'] ?? '';

            $items[] = [
                'network' => $network,
                'url'     => $link['url'] ?? '',
                'icon'    => self::bootstrapIcon($network),
            ];
        }

        return [
            'id'    => $section['id'] ?? null,
            'title' => $section['title'] ?? '',
            'type'  => 'social',
            'items' => $items,
            'position' => (int)($section['position'] ?? 0),
        ];
    }

    private static function buildContactSection(array $section, array $settings): array
    {
        $items = [];

        if (!empty($settings['contact_phone'])) {
            $items[] = [
                'type'  => 'phone',
                'value' => $settings['contact_phone'],
            ];
        }

        if (!empty($settings['contact_whatsapp'])) {
            $items[] = [
                'type'  => 'whatsapp',
                'value' => $settings['contact_whatsapp'],
            ];
        }

        return [
            'id'    => $section['id'] ?? null,
            'title' => $section['title'] ?? '',
            'type'  => 'contact',
            'items' => $items,
            'position' => (int)($section['position'] ?? 0),
        ];
    }

    private static function resolveLinkUrl(array $link, array $pages): string
    {
        $rawUrl = $link['url'] ?? '';
        if (is_string($rawUrl) && preg_match('#^https?://#i', $rawUrl)) {
            return $rawUrl;
        }

        if (($link['type'] ?? '') === 'page' && !empty($link['page_id'])) {
            $page = $pages[(int)$link['page_id']] ?? null;

            if ($page) {
                $slug = $page['slug'] ?? '';
                if (!empty($slug)) {
                    return self::toUrl('/' . ltrim($slug, '/'));
                }
                return self::toUrl('/page/' . ($page['id'] ?? (int)$link['page_id']));
            }

            return self::toUrl('/page/' . (int)$link['page_id']);
        }

        if (!empty($rawUrl)) {
            return self::toUrl('/' . ltrim($rawUrl, '/'));
        }

        return '#';
    }

    private static function toUrl(string $path): string
    {
        $base = rtrim(self::basePath(), '/');
        $path = '/' . ltrim($path, '/');
        return $base . $path;
    }

    private static function basePath(): string
    {
        if (defined('BASE_URL') && BASE_URL !== '') {
            return rtrim(BASE_URL, '/');
        }
        if (defined('APP_URL') && APP_URL !== '') {
            return rtrim(APP_URL, '/');
        }

        $script = $_SERVER['SCRIPT_NAME'] ?? '';
        $dir = str_replace('\\', '/', dirname($script));
        return ($dir === '/' || $dir === '.') ? '' : $dir;
    }

    private static function bootstrapIcon(string $network): string
    {
        return match ($network) {
            'facebook'  => 'bi bi-facebook',
            'instagram' => 'bi bi-instagram',
            'twitter'   => 'bi bi-twitter',
            'tiktok'    => 'bi bi-tiktok',
            'youtube'   => 'bi bi-youtube',
            'linkedin'  => 'bi bi-linkedin',
            'snapchat'  => 'bi bi-snapchat',
            'telegram'  => 'bi bi-telegram',
            default     => 'bi bi-share',
        };
    }

    private static function isRTL(): bool
    {
        return function_exists('app')
            && method_exists(app(), 'isRTL')
            && app()->isRTL();
    }
}
