<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\UpdateNavigationRequest;
use App\Models\NavigationItem;
use App\Services\ActivityLogger;
use App\Services\ContentCacheService;
use App\Services\SettingsService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class NavigationController extends Controller
{
    public function index(SettingsService $settings): View
    {
        return view('admin.navigation.index', [
            'navigation' => [
                'header' => NavigationItem::where('location', 'header')->ordered()->get()->all(),
                'footer' => NavigationItem::where('location', 'footer')->ordered()->get()->all(),
                'legal' => NavigationItem::where('location', 'legal')->ordered()->get()->all(),
            ],
            'footerContent' => $settings->group('footer', config('nh_trans.footer')),
        ]);
    }

    public function update(UpdateNavigationRequest $request, SettingsService $settings, ActivityLogger $logger): RedirectResponse
    {
        DB::transaction(function () use ($request, $settings): void {
            foreach (['header', 'footer', 'legal'] as $location) {
                NavigationItem::where('location', $location)->delete();

                foreach (array_values($request->input($location, [])) as $index => $item) {
                    if (! filled($item['label'] ?? null)) {
                        continue;
                    }

                    $routeOrUrl = $item['url'] ?? null;

                    NavigationItem::create([
                        'location' => $location,
                        'label' => $item['label'],
                        'route_name' => $this->routeName($routeOrUrl),
                        'url' => $this->routeName($routeOrUrl) ? null : $routeOrUrl,
                        'target' => $item['target'] ?? '_self',
                        'sort_order' => $index + 1,
                        'is_active' => (bool) ($item['is_active'] ?? false),
                    ]);
                }
            }

            foreach ($request->input('footer_content', []) as $key => $value) {
                $settings->put('footer', $key, $value, 'text', true);
            }
        });

        app(ContentCacheService::class)->flush();
        $logger->log('navigation.updated', null, 'Navigation et pied de page mis à jour.');

        return back()->with('status', 'Navigation enregistrée.');
    }

    private function routeName(?string $value): ?string
    {
        return in_array($value, ['home', 'about', 'services', 'gallery', 'contact'], true) ? $value : null;
    }
}
