<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Country;
use App\Models\CountrySectionsContent;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CountrySectionsContentController extends Controller
{
    public function edit()
    {
        $content  = CountrySectionsContent::getContent();
        $countries = Country::active()->ordered()->get(['id', 'name', 'slug']);

        return view('admin.country-sections.edit', compact('content', 'countries'));
    }

    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'subjects_title_prefix' => 'required|string|max:140',
            'subjects_country_map'  => 'nullable|string',

            'process_title'        => 'required|string|max:180',
            'process_subtitle'     => 'nullable|string|max:450',
            'process_country_map'  => 'nullable|string',

            'entry_title'          => 'required|string|max:180',
            'entry_rotate_ms'      => 'required|integer|min:1000|max:12000',
            'entry_country_map'    => 'nullable|string',
            'intakes_title'        => 'required|string|max:180',
            'intakes_country_map'  => 'nullable|string',

            // Array items
            'subjects_items'       => 'nullable|array',
            'subjects_items.*.id'  => 'nullable|string|max:60',
            'subjects_items.*.title' => 'required_with:subjects_items|string|max:180',
            'subjects_items.*.image' => 'nullable|string|max:1000',
            'subjects_items.*.image_file' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:5120',

            'process_items'        => 'nullable|array',
            'process_items.*.id'   => 'nullable|string|max:60',
            'process_items.*.title' => 'required_with:process_items|string|max:180',
            'process_items.*.text'  => 'nullable|string|max:600',
            'process_items.*.image' => 'nullable|string|max:1000',
            'process_items.*.image_file' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:5120',

            'entry_items'          => 'nullable|array',
            'entry_items.*.id'     => 'nullable|string|max:60',
            'entry_items.*.title'  => 'required_with:entry_items|string|max:180',
            'entry_items.*.text'   => 'nullable|string|max:1200',
            'entry_items.*.icon'   => 'nullable|string|max:20',
            'entry_items.*.image'  => 'nullable|string|max:1000',
            'entry_items.*.image_file' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:5120',

            'intakes_items'          => 'nullable|array',
            'intakes_items.*.id'     => 'nullable|string|max:60',
            'intakes_items.*.title'  => 'required_with:intakes_items|string|max:180',
            'intakes_items.*.text'   => 'nullable|string|max:600',
        ]);

        $subjectItems = [];
        foreach (($validated['subjects_items'] ?? []) as $index => $item) {
            if (empty(trim((string) ($item['title'] ?? '')))) {
                continue;
            }

            $image = trim((string) ($item['image'] ?? ''));
            if ($request->hasFile("subjects_items.$index.image_file")) {
                if ($image !== '' && ! str_starts_with($image, 'http')) {
                    Storage::disk('public')->delete($image);
                }
                $image = $request->file("subjects_items.$index.image_file")->store('country-sections', 'public');
            }

            $subjectItems[] = [
                'id' => $this->slug((string) ($item['title'] ?? ''), (string) ($item['id'] ?? '')),
                'title' => trim((string) ($item['title'] ?? '')),
                'image' => $image,
            ];
        }

        $processItems = [];
        foreach (($validated['process_items'] ?? []) as $index => $item) {
            if (empty(trim((string) ($item['title'] ?? '')))) {
                continue;
            }

            $image = trim((string) ($item['image'] ?? ''));
            if ($request->hasFile("process_items.$index.image_file")) {
                if ($image !== '' && ! str_starts_with($image, 'http')) {
                    Storage::disk('public')->delete($image);
                }
                $image = $request->file("process_items.$index.image_file")->store('country-sections', 'public');
            }

            $processItems[] = [
                'id' => $this->slug((string) ($item['title'] ?? ''), (string) ($item['id'] ?? '')),
                'title' => trim((string) ($item['title'] ?? '')),
                'text' => trim((string) ($item['text'] ?? '')),
                'image' => $image,
            ];
        }

        $entryItems = [];
        foreach (($validated['entry_items'] ?? []) as $index => $item) {
            if (empty(trim((string) ($item['title'] ?? '')))) {
                continue;
            }

            $image = trim((string) ($item['image'] ?? ''));
            if ($request->hasFile("entry_items.$index.image_file")) {
                if ($image !== '' && ! str_starts_with($image, 'http')) {
                    Storage::disk('public')->delete($image);
                }
                $image = $request->file("entry_items.$index.image_file")->store('country-sections', 'public');
            }

            $entryItems[] = [
                'id' => $this->slug((string) ($item['title'] ?? ''), (string) ($item['id'] ?? '')),
                'title' => trim((string) ($item['title'] ?? '')),
                'text' => trim((string) ($item['text'] ?? '')),
                'icon' => trim((string) ($item['icon'] ?? '')),
                'image' => $image,
            ];
        }

        $intakeItems = collect($validated['intakes_items'] ?? [])
            ->filter(fn ($i) => !empty(trim((string) ($i['title'] ?? ''))))
            ->map(fn ($i) => [
                'id'    => $this->slug($i['title'] ?? '', $i['id'] ?? ''),
                'title' => trim($i['title']),
                'text'  => trim($i['text'] ?? ''),
            ])
            ->values()
            ->all();

        $defaults = CountrySectionsContent::defaults();

        $content = [
            'subjects' => [
                'title_prefix' => $validated['subjects_title_prefix'],
                'items'        => $subjectItems ?: $defaults['subjects']['items'],
                'country_map'  => $this->parseCountryMap((string) ($validated['subjects_country_map'] ?? '')),
            ],
            'process' => [
                'title'       => $validated['process_title'],
                'subtitle'    => $validated['process_subtitle'] ?? '',
                'items'       => $processItems ?: $defaults['process']['items'],
                'country_map' => $this->parseCountryMap((string) ($validated['process_country_map'] ?? '')),
            ],
            'entry' => [
                'title'      => $validated['entry_title'],
                'rotate_ms'  => (int) $validated['entry_rotate_ms'],
                'items'      => $entryItems ?: $defaults['entry']['items'],
                'country_map' => $this->parseCountryMap((string) ($validated['entry_country_map'] ?? '')),
            ],
            'intakes' => [
                'title'      => $validated['intakes_title'],
                'items'      => $intakeItems ?: $defaults['intakes']['items'],
                'country_map' => $this->parseCountryMap((string) ($validated['intakes_country_map'] ?? '')),
            ],
        ];

        CountrySectionsContent::saveContent($content);

        return back()->with('success', 'Country Sections CMS saved.');
    }

    private function slug(string $title, string $existing): string
    {
        if ($existing !== '') {
            return $existing;
        }

        return strtolower(trim(preg_replace('/[^a-z0-9]+/i', '_', $title), '_'));
    }

    private function parseCountryMap(string $raw): array
    {
        $map = [];

        foreach (preg_split('/\r\n|\r|\n/', $raw) as $line) {
            $line = trim((string) $line);
            if ($line === '' || ! str_contains($line, '|')) {
                continue;
            }

            [$slug, $ids] = array_map('trim', explode('|', $line, 2));
            if ($slug === '' || $ids === '') {
                continue;
            }

            $map[$slug] = array_values(array_filter(array_map('trim', explode(',', $ids))));
        }

        return $map;
    }
}
