<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Services\AdminActivityLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class HomepageSettingsController extends Controller
{
    public function index(): View
    {
        $settings = Setting::query()->pluck('value', 'key');

        return view('admin.cms.homepage-settings', [
            'settings' => $settings,
            'trustBadges' => $this->decodeList($settings->get('trust_badges')),
            'aboutHighlights' => $this->decodeList($settings->get('about_highlights')),
            'complianceItems' => $this->decodeList($settings->get('compliance_items')),
        ]);
    }

    public function update(Request $request, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'hero_title' => ['nullable', 'string', 'max:191'],
            'hero_subtitle' => ['nullable', 'string', 'max:600'],
            'hero_button_1_text' => ['nullable', 'string', 'max:50'],
            'hero_button_1_link' => ['nullable', 'string', 'max:191'],
            'hero_button_2_text' => ['nullable', 'string', 'max:50'],
            'hero_button_2_link' => ['nullable', 'string', 'max:191'],
            'hero_background_image' => ['nullable', 'image', 'max:3072'],
            'hero_dashboard_image' => ['nullable', 'image', 'max:3072'],
            'trust_badges' => ['nullable', 'string'],
            'about_title' => ['nullable', 'string', 'max:191'],
            'about_description' => ['nullable', 'string', 'max:2000'],
            'about_highlights' => ['nullable', 'string'],
            'about_image' => ['nullable', 'image', 'max:3072'],
            'founder_name' => ['nullable', 'string', 'max:191'],
            'founder_signature' => ['nullable', 'image', 'max:2048'],
            'cta_title' => ['nullable', 'string', 'max:191'],
            'cta_subtitle' => ['nullable', 'string', 'max:600'],
            'cta_button_text' => ['nullable', 'string', 'max:50'],
            'cta_button_link' => ['nullable', 'string', 'max:191'],
            'homepage_stats_mode' => ['nullable', 'in:auto,manual'],
            'homepage_stat_total_members' => ['nullable', 'numeric', 'min:0'],
            'homepage_stat_total_withdrawals' => ['nullable', 'numeric', 'min:0'],
            'homepage_stat_total_business' => ['nullable', 'numeric', 'min:0'],
            'homepage_stat_active_distributors' => ['nullable', 'numeric', 'min:0'],
            'compliance_items' => ['nullable', 'string'],
            'home_meta_title' => ['nullable', 'string', 'max:191'],
            'home_meta_description' => ['nullable', 'string', 'max:600'],
            'home_og_image' => ['nullable', 'image', 'max:3072'],
            'home_canonical_url' => ['nullable', 'string', 'max:191'],
            'home_indexable' => ['nullable', 'boolean'],
        ]);

        if ($request->hasFile('hero_background_image')) {
            $path = $request->file('hero_background_image')->store('homepage/hero', 'public');
            Setting::setValue('hero_background_image', $path);
        }

        if ($request->hasFile('hero_dashboard_image')) {
            $path = $request->file('hero_dashboard_image')->store('homepage/hero', 'public');
            Setting::setValue('hero_dashboard_image', $path);
        }

        if ($request->hasFile('about_image')) {
            $path = $request->file('about_image')->store('homepage/about', 'public');
            Setting::setValue('about_image', $path);
        }

        if ($request->hasFile('founder_signature')) {
            $path = $request->file('founder_signature')->store('homepage/about', 'public');
            Setting::setValue('founder_signature', $path);
        }

        if ($request->hasFile('home_og_image')) {
            $path = $request->file('home_og_image')->store('homepage/seo', 'public');
            Setting::setValue('home_og_image', $path);
        }

        $simpleFields = [
            'hero_title',
            'hero_subtitle',
            'hero_button_1_text',
            'hero_button_1_link',
            'hero_button_2_text',
            'hero_button_2_link',
            'about_title',
            'about_description',
            'founder_name',
            'cta_title',
            'cta_subtitle',
            'cta_button_text',
            'cta_button_link',
            'home_meta_title',
            'home_meta_description',
            'home_canonical_url',
        ];

        foreach ($simpleFields as $key) {
            if (array_key_exists($key, $validated)) {
                Setting::setValue($key, $validated[$key]);
            }
        }

        $statsMode = $validated['homepage_stats_mode'] ?? 'auto';
        Setting::setValue('homepage_stats_mode', $statsMode);

        foreach ([
            'homepage_stat_total_members',
            'homepage_stat_total_withdrawals',
            'homepage_stat_total_business',
            'homepage_stat_active_distributors',
        ] as $key) {
            if (array_key_exists($key, $validated)) {
                Setting::setValue($key, (string) $validated[$key]);
            }
        }

        Setting::setValue('trust_badges', $this->linesToArray($request->input('trust_badges', '')));
        Setting::setValue('about_highlights', $this->linesToArray($request->input('about_highlights', '')));
        Setting::setValue('compliance_items', $this->linesToArray($request->input('compliance_items', '')));

        Setting::setValue('home_indexable', $request->boolean('home_indexable', true));

        $logger->log('homepage_settings.update', Setting::class, null, ['keys' => array_keys($validated)]);

        return back()->with('status', 'Homepage settings updated.');
    }

    /**
     * @return array<int, string>
     */
    private function linesToArray(string $value): array
    {
        $lines = preg_split('/\r\n|\r|\n/', $value) ?: [];
        $lines = array_map('trim', $lines);
        $lines = array_filter($lines, fn ($line) => $line !== '');

        return array_values($lines);
    }

    /**
     * @return array<int, string>
     */
    private function decodeList(mixed $value): array
    {
        if (is_array($value)) {
            return $value;
        }

        if (! is_string($value) || trim($value) === '') {
            return [];
        }

        $decoded = json_decode($value, true);
        if (is_array($decoded)) {
            return array_values(array_filter(array_map('strval', $decoded)));
        }

        return [];
    }
}
