<?php

namespace App\Services;

use App\Models\MarketplacePurchase;
use App\Models\Setting;
use Illuminate\Support\Facades\File;
use Illuminate\View\View as ViewInstance;

class ThemeService
{
    protected string $themesPath;

    protected ?string $activeTheme = null;

    public function __construct()
    {
        $this->themesPath = base_path('themes');
    }

    public function getActiveTheme(): string
    {
        if ($this->activeTheme === null) {
            $this->activeTheme = Setting::get('active_theme', 'classic');
        }
        return $this->activeTheme;
    }

    public function getThemePath(string $theme = null): string
    {
        return $this->themesPath.'/'.($theme ?? $this->getActiveTheme());
    }

    public function getSettings(): array
    {
        $footerLinksRaw = Setting::get('footer_links', '');
        $footerLinks = is_array($footerLinksRaw) ? $footerLinksRaw : json_decode((string) $footerLinksRaw, true);
        if (! is_array($footerLinks)) {
            $footerLinks = [];
        }
        if (empty($footerLinks)) {
            $footerLinks = [
                ['label' => 'Mentions legales', 'url' => '/mentions-legales'],
                ['label' => 'Nous contacter', 'url' => '/contact'],
            ];
        }

        $settings = [
            'site_name' => Setting::get('site_name', 'Mon Site'),
            'primary_color' => Setting::get('primary_color', '#6366f1'),
            'secondary_color' => Setting::get('secondary_color', '#8b5cf6'),
            'logo' => Setting::get('logo'),
            'classic_background_image' => Setting::get('classic_background_image'),
            'classic_background_size' => Setting::get('classic_background_size', 'cover'),
            'classic_background_overlay' => (int) Setting::get('classic_background_overlay', 35),
            'classic_hero_eyebrow' => Setting::get('classic_hero_eyebrow', 'Bienvenue'),
            'classic_hero_eyebrow_enabled' => Setting::get('classic_hero_eyebrow_enabled', '1') === '1',
            'meta_description' => Setting::get('meta_description'),
            'meta_keywords' => Setting::get('meta_keywords'),
            'og_image' => Setting::get('og_image'),
            'footer_bg_color' => Setting::get('footer_bg_color', '#3d2a1f'),
            'footer_text_color' => Setting::get('footer_text_color', '#faf8f5'),
            'footer_heading' => Setting::get('footer_heading', ''),
            'footer_description' => Setting::get('footer_description', 'Bijoux en micro-macrame et ateliers creatifs en Haute-Savoie. Faits main avec soin et amour.'),
            'footer_nav_title' => Setting::get('footer_nav_title', 'Navigation'),
            'footer_social_title' => Setting::get('footer_social_title', 'Reseaux sociaux'),
            'footer_facebook_url' => Setting::get('footer_facebook_url', ''),
            'footer_instagram_url' => Setting::get('footer_instagram_url', ''),
            'footer_maps_url' => Setting::get('footer_maps_url', ''),
            'footer_links' => $footerLinks,
            'menu_items' => \App\Models\MenuItem::orderBy('order')->get(),
            'cookie_banner_enabled' => Setting::get('cookie_banner_enabled', '0') === '1',
            'cookie_banner_title' => Setting::get('cookie_banner_title', 'Utilisation des cookies'),
            'cookie_banner_content' => Setting::get('cookie_banner_content', ''),
            'cookie_banner_accept' => Setting::get('cookie_banner_accept', 'Accepter'),
            'cookie_banner_reject' => Setting::get('cookie_banner_reject', 'Refuser'),
            'age_verification_enabled' => Setting::get('age_verification_enabled', '0') === '1',
            'age_verification_title' => Setting::get('age_verification_title', 'Accès réservé aux majeurs'),
            'age_verification_content' => Setting::get('age_verification_content', ''),
            'age_verification_confirm' => Setting::get('age_verification_confirm', "J'ai plus de 18 ans"),
            'age_verification_back' => Setting::get('age_verification_back', 'Retour'),
            'age_verification_back_url' => Setting::get('age_verification_back_url', 'https://www.google.com'),
            'page_loader_enabled' => Setting::get('page_loader_enabled', '0') === '1',
            'page_loader_image' => Setting::get('page_loader_image', ''),
            'google_analytics_id' => trim((string) Setting::get('google_analytics_id', '')),
            'newsletter_enabled' => $this->isPluginActive('newsletter'),
            'newsletter_popup_enabled' => Setting::get('newsletter_popup_enabled', '1') === '1',
            'newsletter_popup_mode' => Setting::get('newsletter_popup_mode', 'auto'),
            'newsletter_popup_title' => Setting::get('newsletter_popup_title', 'Restez informé'),
            'newsletter_popup_content' => Setting::get('newsletter_popup_content', 'Inscrivez-vous à notre newsletter pour recevoir nos actualités et offres exclusives.'),
            'newsletter_popup_image' => Setting::get('newsletter_popup_image'),
            'newsletter_popup_cta' => Setting::get('newsletter_popup_cta', "S'inscrire"),
            'newsletter_popup_trigger_text' => Setting::get('newsletter_popup_trigger_text', 'Newsletter'),
            'newsletter_popup_delay_seconds' => (int) Setting::get('newsletter_popup_delay_seconds', 3),
            'newsletter_popup_repeat_days' => (int) Setting::get('newsletter_popup_repeat_days', 7),
            'banners' => $this->getActiveBanners(),
            'multilang_enabled' => $this->isPluginActive('multilang'),
            'multilang_languages' => $this->getMultilangLanguages(),
            'multilang_current' => session('locale') ?: Setting::get('multilang_default', 'fr'),
            'multilang_default' => Setting::get('multilang_default', 'fr'),
        ];

        if (MarketplacePurchase::hasPurchased('plugin', 'ecommerce')) {
            $settings['ecommerce_navbar_submenu'] = Setting::get('ecommerce_navbar_submenu', '1') !== '0';
            $settings['ecommerce_categories'] = \App\Models\ProductCategory::with('children')
                ->whereNull('parent_id')
                ->orderBy('order')
                ->orderBy('name')
                ->get();
        } else {
            $settings['ecommerce_navbar_submenu'] = false;
            $settings['ecommerce_categories'] = collect();
        }

        $cart = session('cart', []);
        $settings['cart_count'] = is_array($cart) ? (int) array_sum($cart) : 0;

        return $settings;
    }

    public function render(string $view, array $data = []): ViewInstance
    {
        $theme = $this->getActiveTheme();
        $viewPath = "themes.{$theme}.{$view}";
        if (! view()->exists($viewPath)) {
            $viewPath = "themes.classic.{$view}";
        }
        $data = array_merge($this->getSettings(), $data);
        return view($viewPath, $data);
    }

    /**
     * Liste tous les thèmes disponibles (core + personnalisés + achetés).
     */
    public function getAvailableThemes(): array
    {
        $themes = [];

        // Thèmes core (dans themes/)
        if (File::isDirectory($this->themesPath)) {
            foreach (File::directories($this->themesPath) as $dir) {
                $configPath = $dir.'/theme.json';
                if (File::exists($configPath)) {
                    $config = json_decode(File::get($configPath), true);
                    if ($config && ($config['price'] ?? 0) == 0) {
                        $themes[$config['slug']] = array_merge($config, ['installed' => true, 'source' => 'core']);
                    }
                }
            }
        }

        // Thèmes personnalisés (dans content/themes/)
        $customPath = config('cms.custom_themes_path');
        if ($customPath && File::isDirectory($customPath)) {
            foreach (File::directories($customPath) as $dir) {
                $configPath = $dir.'/theme.json';
                if (File::exists($configPath)) {
                    $config = json_decode(File::get($configPath), true);
                    if ($config && view()->exists("themes.{$config['slug']}.home")) {
                        $themes[$config['slug']] = array_merge($config, [
                            'installed' => true,
                            'source' => $config['source'] ?? 'custom',
                        ]);
                    }
                }
            }
        }

        // Thèmes achetés (doivent avoir des vues dans resources/views/themes/)
        $installedPaid = MarketplacePurchase::where('item_type', 'theme')
            ->where('is_active', true)
            ->where('admin_enabled', true)
            ->pluck('item_slug');
        $catalog = collect(config('marketplace_catalog.themes', []))->keyBy('slug');
        foreach ($installedPaid as $slug) {
            if (! isset($themes[$slug]) && view()->exists("themes.{$slug}.home")) {
                $info = $catalog->get($slug);
                $themes[$slug] = [
                    'slug' => $slug,
                    'name' => $info['name'] ?? ucfirst($slug),
                    'description' => $info['description'] ?? '',
                    'installed' => true,
                    'source' => 'marketplace',
                ];
            }
        }

        return $themes;
    }

    protected function getMultilangLanguages(): array
    {
        if (! $this->isPluginActive('multilang')) {
            return [];
        }
        $raw = Setting::get('multilang_languages', '["fr"]');
        $arr = is_array($raw) ? $raw : json_decode((string) $raw, true);
        if (! is_array($arr)) {
            return [];
        }
        $labels = [
            'fr' => 'Français', 'en' => 'English', 'de' => 'Deutsch', 'es' => 'Español',
            'it' => 'Italiano', 'pt' => 'Português', 'nl' => 'Nederlands',
        ];
        $result = [];
        foreach ($arr as $code) {
            $result[$code] = $labels[$code] ?? strtoupper($code);
        }
        return $result;
    }

    protected function getActiveBanners(): \Illuminate\Support\Collection
    {
        if (! $this->isPluginActive('banners')) {
            return collect();
        }
        try {
            return \App\Models\Banner::orderBy('order')->orderBy('id')->get()->filter(fn ($b) => $b->isCurrentlyActive());
        } catch (\Throwable $e) {
            return collect();
        }
    }

    public function isPluginActive(string $slug): bool
    {
        if (\App\Models\MarketplacePurchase::hasPurchased('plugin', $slug)) {
            return true;
        }
        if (in_array($slug, config('cms.marketplace_only_plugins', []), true)) {
            return false;
        }
        $customPath = config('cms.custom_plugins_path');
        if ($customPath && is_dir($customPath.'/'.$slug)) {
            $configPath = $customPath.'/'.$slug.'/plugin.json';
            if (file_exists($configPath)) {
                $config = json_decode(file_get_contents($configPath), true);
                return ($config['source'] ?? '') === 'custom';
            }
        }
        return false;
    }

    public function isThemeAvailable(string $slug): bool
    {
        $available = $this->getAvailableThemes();
        return isset($available[$slug]);
    }
}
