<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MenuItem;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AppearanceController extends Controller
{
    protected function getMultilangData(): array
    {
        if (! \App\Models\MarketplacePurchase::hasPurchased('plugin', 'multilang')) {
            return ['locales' => [], 'labels' => []];
        }
        $raw = \App\Models\Setting::get('multilang_languages', '["fr"]');
        $enabled = is_array($raw) ? $raw : json_decode($raw, true);
        $default = \App\Models\Setting::get('multilang_default', 'fr');
        $locales = is_array($enabled) ? array_values(array_diff($enabled, [$default])) : [];
        $allLabels = \App\Http\Controllers\Admin\MultilangController::getAvailableLanguages();
        $labels = array_intersect_key($allLabels, array_flip($locales));
        return ['locales' => $locales, 'labels' => $labels];
    }

    public function index()
    {
        $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'),
            'active_theme' => Setting::get('active_theme', 'classic'),
            '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,
            'page_loader_enabled' => Setting::get('page_loader_enabled', '0') === '1',
            'page_loader_image' => Setting::get('page_loader_image', ''),
        ];
        $menuItems = MenuItem::orderBy('order')->get();
        $availableThemes = app(\App\Services\ThemeService::class)->getAvailableThemes();
        $multilang = $this->getMultilangData();
        return view('admin.appearance.index', compact('settings', 'menuItems', 'availableThemes', 'multilang'));
    }

    public function store(Request $request)
    {
        $availableThemes = array_keys(app(\App\Services\ThemeService::class)->getAvailableThemes());
        $request->validate([
            'site_name' => 'required|string|max:255',
            'primary_color' => 'required|string|max:7',
            'secondary_color' => 'required|string|max:7',
            'active_theme' => 'required|in:'.implode(',', $availableThemes),
            'logo' => 'nullable|image|max:2048',
            'classic_background_image' => 'nullable|string|max:2048',
            'classic_background_file' => 'nullable|image|max:4096',
            'classic_background_size' => 'nullable|in:cover,contain,auto',
            'classic_background_overlay' => 'nullable|integer|min:0|max:80',
            'classic_hero_eyebrow' => 'nullable|string|max:80',
            'meta_description' => 'nullable|string|max:320',
            'meta_keywords' => 'nullable|string|max:255',
            'og_image' => 'nullable|image|max:2048',
            'og_image_url' => 'nullable|string|max:2048',
            'footer_bg_color' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'footer_text_color' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'footer_heading' => 'nullable|string|max:120',
            'footer_description' => 'nullable|string|max:500',
            'footer_nav_title' => 'nullable|string|max:80',
            'footer_social_title' => 'nullable|string|max:80',
            'footer_facebook_url' => 'nullable|string|max:2048',
            'footer_instagram_url' => 'nullable|string|max:2048',
            'footer_maps_url' => 'nullable|string|max:2048',
            'footer_links' => 'nullable|array',
            'footer_links.*.label' => 'nullable|string|max:120',
            'footer_links.*.url' => 'nullable|string|max:2048',
            'page_loader_enabled' => 'nullable|boolean',
            'page_loader_image' => 'nullable|string|max:2048',
        ]);
        Setting::set('site_name', $request->site_name, 'general');
        Setting::set('primary_color', $request->primary_color, 'appearance');
        Setting::set('secondary_color', $request->secondary_color, 'appearance');
        Setting::set('active_theme', $request->active_theme, 'appearance');
        $classicBackgroundImage = (string) ($request->classic_background_image ?? '');
        if ($request->hasFile('classic_background_file')) {
            $classicBackgroundImage = $request->file('classic_background_file')->store('theme-backgrounds', 'public');
        }
        Setting::set('classic_background_image', $classicBackgroundImage, 'appearance');
        Setting::set('classic_background_size', (string) ($request->classic_background_size ?? 'cover'), 'appearance');
        Setting::set('classic_background_overlay', (string) ($request->classic_background_overlay ?? 35), 'appearance');
        Setting::set('classic_hero_eyebrow', (string) ($request->classic_hero_eyebrow ?? 'Bienvenue'), 'appearance');
        Setting::set('classic_hero_eyebrow_enabled', $request->boolean('classic_hero_eyebrow_enabled') ? '1' : '0', 'appearance');
        if ($request->hasFile('logo')) {
            $path = $request->file('logo')->store('logos', 'public');
            Setting::set('logo', $path, 'appearance');
        }
        Setting::set('meta_description', (string) ($request->meta_description ?? ''), 'seo');
        Setting::set('meta_keywords', (string) ($request->meta_keywords ?? ''), 'seo');
        if ($request->hasFile('og_image')) {
            Setting::set('og_image', $request->file('og_image')->store('og-images', 'public'), 'seo');
        } else {
            Setting::set('og_image', trim($request->og_image_url ?? ''), 'seo');
        }
        Setting::set('footer_bg_color', (string) ($request->footer_bg_color ?? '#3d2a1f'), 'appearance');
        Setting::set('footer_text_color', (string) ($request->footer_text_color ?? '#faf8f5'), 'appearance');
        Setting::set('footer_heading', (string) ($request->footer_heading ?? ''), 'appearance');
        Setting::set('footer_description', (string) ($request->footer_description ?? ''), 'appearance');
        Setting::set('footer_nav_title', (string) ($request->footer_nav_title ?? 'Navigation'), 'appearance');
        Setting::set('footer_social_title', (string) ($request->footer_social_title ?? 'Reseaux sociaux'), 'appearance');
        Setting::set('footer_facebook_url', (string) ($request->footer_facebook_url ?? ''), 'appearance');
        Setting::set('footer_instagram_url', (string) ($request->footer_instagram_url ?? ''), 'appearance');
        Setting::set('footer_maps_url', (string) ($request->footer_maps_url ?? ''), 'appearance');
        $footerLinks = [];
        foreach ((array) ($request->footer_links ?? []) as $link) {
            $label = trim((string) ($link['label'] ?? ''));
            $url = trim((string) ($link['url'] ?? ''));
            if ($label !== '' && $url !== '') {
                $footerLinks[] = ['label' => $label, 'url' => $url];
            }
        }
        Setting::set('footer_links', $footerLinks, 'appearance');
        Setting::set('page_loader_enabled', $request->boolean('page_loader_enabled') ? '1' : '0', 'appearance');
        Setting::set('page_loader_image', trim((string) ($request->page_loader_image ?? '')), 'appearance');
        if ($request->has('menu_items')) {
            $idsToKeep = [];
            foreach ($request->menu_items ?? [] as $i => $item) {
                $label = trim((string) ($item['label'] ?? ''));
                $url = trim((string) ($item['url'] ?? ''));
                if ($label === '' || $url === '') {
                    continue;
                }
                $translations = $item['translations'] ?? [];
                $translations = is_array($translations) ? array_filter($translations, fn ($v) => $v !== '' && $v !== null) : [];
                if (isset($item['id']) && $item['id']) {
                    $existing = MenuItem::find($item['id']);
                    if ($existing) {
                        $existing->update([
                            'label' => $label,
                            'url' => $url,
                            'target' => $item['target'] ?? '_self',
                            'order' => $i,
                            'translations' => array_merge($existing->translations ?? [], $translations),
                        ]);
                        $idsToKeep[] = $existing->id;
                        continue;
                    }
                }
                $newItem = MenuItem::create([
                    'label' => $label,
                    'url' => $url,
                    'target' => $item['target'] ?? '_self',
                    'order' => $i,
                ]);
                if (! empty($translations)) {
                    $newItem->update(['translations' => $translations]);
                }
                $idsToKeep[] = $newItem->id;
            }
            MenuItem::whereNotIn('id', $idsToKeep)->delete();
        }
        return back()->with('success', 'Apparence mise à jour.');
    }
}
