<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ContentPage;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ContentPageController extends Controller
{
    public function index(): View
    {
        return view('admin.content-pages.index', [
            'pages' => ContentPage::query()->orderBy('title')->get(),
        ]);
    }

    public function edit(ContentPage $page): View
    {
        return view('admin.content-pages.edit', [
            'page' => $page,
        ]);
    }

    public function update(Request $request, ContentPage $page): RedirectResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'body_html' => ['required', 'string', 'max:50000'],
            'meta_title' => ['nullable', 'string', 'max:255'],
            'meta_description' => ['nullable', 'string', 'max:500'],
            'og_image' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        if (isset($data['og_image'])) {
            if ($page->og_image_path) {
                Storage::disk('public')->delete($page->og_image_path);
            }

            $data['og_image_path'] = $data['og_image']->store('seo', 'public');
        }

        $page->update([
            'title' => $data['title'],
            'body_html' => $data['body_html'],
            'meta_title' => $data['meta_title'] ?? null,
            'meta_description' => $data['meta_description'] ?? null,
            'og_image_path' => $data['og_image_path'] ?? $page->og_image_path,
            'is_active' => $request->boolean('is_active'),
        ]);

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