<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PageController extends Controller
{
    public function editHome()
    {
        $homePage = Page::where('is_home', true)->first();

        if (! $homePage) {
            $homePage = Page::create([
                'title' => 'Accueil',
                'slug' => 'accueil',
                'is_home' => true,
                'is_published' => true,
                'sections' => Page::getSectionPresets()['landing']['sections'] ?? [],
            ]);
        }

        return redirect()
            ->route('admin.pages.edit', $homePage)
            ->with('success', 'Vous modifiez maintenant la page d\'accueil.');
    }

    public function index()
    {
        return view('admin.pages.index', [
            'pages' => Page::orderBy('order')->orderBy('title')->get(),
        ]);
    }

    public function create()
    {
        return view('admin.pages.create', [
            'hasHomePage' => Page::where('is_home', true)->exists(),
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255',
            'sections' => 'nullable|array',
            'is_home' => 'boolean',
            'is_published' => 'boolean',
        ]);
        $data['slug'] = $data['slug'] ?? Str::slug($data['title']);
        $data['is_home'] = $request->boolean('is_home');
        if (! $data['is_home'] && ! Page::where('is_home', true)->exists()) {
            // Keep homepage editable from first page creation.
            $data['is_home'] = true;
        }
        $data['is_published'] = $request->boolean('is_published', true);
        $data['sections'] = $this->sanitizeSections($request->input('sections', []));
        if ($data['is_home']) {
            Page::where('is_home', true)->update(['is_home' => false]);
        }
        Page::create($data);
        return redirect()->route('admin.pages.index')->with('success', 'Page créée.');
    }

    public function edit(Page $page)
    {
        $multilangLocales = [];
        $multilangLabels = [];
        $defaultLocale = 'fr';
        if (\App\Models\MarketplacePurchase::hasPurchased('plugin', 'multilang')) {
            $raw = \App\Models\Setting::get('multilang_languages', '["fr"]');
            $enabled = is_array($raw) ? $raw : json_decode($raw, true);
            $defaultLocale = \App\Models\Setting::get('multilang_default', 'fr');
            $multilangLocales = is_array($enabled) ? array_values(array_diff($enabled, [$defaultLocale])) : [];
            $labels = \App\Http\Controllers\Admin\MultilangController::getAvailableLanguages();
            $multilangLabels = array_intersect_key($labels, array_flip(array_merge($multilangLocales, [$defaultLocale])));
        }
        return view('admin.pages.edit', compact('page', 'multilangLocales', 'multilangLabels', 'defaultLocale'));
    }

    public function update(Request $request, Page $page)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255',
            'sections' => 'nullable|array',
            'is_home' => 'boolean',
            'is_published' => 'boolean',
            'translations' => 'nullable|array',
            'translations.*' => 'nullable|array',
        ]);
        $data['slug'] = $data['slug'] ?? Str::slug($data['title']);
        $data['is_home'] = $request->boolean('is_home');
        $data['is_published'] = $request->boolean('is_published');
        $data['sections'] = $this->sanitizeSections($request->input('sections', $page->sections ?? []));
        if ($data['is_home']) {
            Page::where('is_home', true)->where('id', '!=', $page->id)->update(['is_home' => false]);
        }
        $translations = $page->translations ?? [];
        $sections = $data['sections'];
        foreach ((array) ($request->input('translations', [])) as $locale => $tr) {
            if (! is_array($tr)) {
                continue;
            }
            $trSections = $tr['sections'] ?? [];
            $mergedSections = [];
            foreach ($sections as $i => $section) {
                $type = $section['type'] ?? 'text';
                $origData = $section['data'] ?? [];
                $trData = $trSections[$i]['data'] ?? [];
                $mergedData = array_replace_recursive($origData, array_filter($trData, fn ($v) => $v !== '' && $v !== null));
                $mergedSections[] = ['type' => $type, 'data' => $mergedData];
            }
            $entry = [
                'title' => trim((string) ($tr['title'] ?? '')),
                'content' => trim((string) ($tr['content'] ?? '')),
                'sections' => $mergedSections,
            ];
            if ($entry['title'] !== '' || $entry['content'] !== '' || ! empty($entry['sections'])) {
                $translations[$locale] = $entry;
            }
        }
        $data['translations'] = $translations;
        $page->update($data);
        return redirect()->route('admin.pages.index')->with('success', 'Page mise à jour.');
    }

    public function destroy(Page $page)
    {
        $page->delete();
        return redirect()->route('admin.pages.index')->with('success', 'Page supprimée.');
    }

    private function sanitizeSections(array $sections): array
    {
        $types = array_merge(
            ['hero', 'text', 'image', 'text_image', 'features', 'stats', 'testimonials', 'team', 'faq', 'cta', 'contact'],
            array_keys(app(\App\Services\PluginService::class)->getPluginSectionTypes())
        );
        return collect($sections)->filter(function ($s) use ($types) {
            return isset($s['type']) && in_array($s['type'], $types);
        })->values()->toArray();
    }
}
