<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Middleware\SetLocale;
use App\Models\SitePage;
use App\Support\SiteContent;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SitePageController extends Controller
{
    public function index(): View
    {
        return view('admin.pages.index', [
            'pages' => SitePage::orderBy('slug')->orderBy('locale')->get(),
            'slugs' => ['about', 'admissions'],
            'locales' => SetLocale::SUPPORTED,
        ]);
    }

    public function edit(string $slug, string $locale): View
    {
        abort_unless(in_array($slug, ['about', 'admissions'], true), 404);
        abort_unless(in_array($locale, SetLocale::SUPPORTED, true), 404);

        $fallback = SiteContent::page($slug, $locale);
        $page = SitePage::firstOrNew(['slug' => $slug, 'locale' => $locale], [
            'title' => $fallback['title'],
            'intro' => $fallback['intro'],
            'body' => collect($fallback['sections'] ?? [])->map(fn ($section) => $section['heading']."\n".$section['body'])->implode("\n\n"),
        ]);

        return view('admin.pages.edit', compact('page', 'slug', 'locale'));
    }

    public function update(Request $request, string $slug, string $locale): RedirectResponse
    {
        abort_unless(in_array($slug, ['about', 'admissions'], true), 404);
        abort_unless(in_array($locale, SetLocale::SUPPORTED, true), 404);

        $data = $request->validate([
            'title' => ['required', 'string', 'max:220'],
            'intro' => ['nullable', 'string', 'max:1000'],
            'body' => ['nullable', 'string', 'max:12000'],
        ]);

        SitePage::updateOrCreate(
            ['slug' => $slug, 'locale' => $locale],
            array_merge($data, ['updated_by' => $request->user()->id])
        );

        return redirect()->route('admin.pages.index')->with('status', 'Page saved.');
    }
}
