<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ContentBlock;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ContentBlockController extends Controller
{
    public function index(): View
    {
        return view('admin.content-blocks.index', [
            'items' => ContentBlock::query()->orderBy('page')->orderBy('sort_order')->get(),
        ]);
    }

    public function create(): View
    {
        return view('admin.content-blocks.form', ['item' => new ContentBlock]);
    }

    public function store(Request $request): RedirectResponse
    {
        ContentBlock::query()->create($this->validated($request));

        return redirect()->route('admin.content-blocks.index')->with('success', 'Content block created.');
    }

    public function edit(ContentBlock $contentBlock): View
    {
        return view('admin.content-blocks.form', ['item' => $contentBlock]);
    }

    public function update(Request $request, ContentBlock $contentBlock): RedirectResponse
    {
        $contentBlock->update($this->validated($request));

        return redirect()->route('admin.content-blocks.index')->with('success', 'Content block updated.');
    }

    public function destroy(ContentBlock $contentBlock): RedirectResponse
    {
        $contentBlock->delete();

        return redirect()->route('admin.content-blocks.index')->with('success', 'Content block deleted.');
    }

    /** @return array<string, mixed> */
    private function validated(Request $request): array
    {
        $data = $request->validate([
            'page' => 'required|string|max:255',
            'section_key' => 'required|string|max:255',
            'title' => 'nullable|string|max:255',
            'body' => 'nullable|string',
            'meta' => 'nullable|string',
            'sort_order' => 'required|integer|min:0',
        ]);

        $meta = null;
        if (! empty($data['meta'])) {
            $decoded = json_decode($data['meta'], true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw \Illuminate\Validation\ValidationException::withMessages([
                    'meta' => 'Meta must be valid JSON.',
                ]);
            }
            $meta = $decoded;
        }

        unset($data['meta']);

        return $data + ['meta' => $meta];
    }
}
