<?php

namespace App\Http\Controllers\Admin;

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

class GalleryImageController extends Controller
{
    public function index(): View
    {
        return view('admin.gallery-images.index', [
            'items' => GalleryImage::query()
                ->with('section')
                ->orderBy('sort_order')
                ->get(),
        ]);
    }

    public function create(): View
    {
        return view('admin.gallery-images.form', [
            'item' => new GalleryImage,
            'sections' => GallerySection::query()->orderBy('sort_order')->get(),
        ]);
    }

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

        return redirect()->route('admin.gallery-images.index')->with('success', 'Gallery image created.');
    }

    public function edit(GalleryImage $galleryImage): View
    {
        return view('admin.gallery-images.form', [
            'item' => $galleryImage,
            'sections' => GallerySection::query()->orderBy('sort_order')->get(),
        ]);
    }

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

        return redirect()->route('admin.gallery-images.index')->with('success', 'Gallery image updated.');
    }

    public function destroy(GalleryImage $galleryImage): RedirectResponse
    {
        $galleryImage->delete();

        return redirect()->route('admin.gallery-images.index')->with('success', 'Gallery image deleted.');
    }

    /** @return array<string, mixed> */
    private function validated(Request $request): array
    {
        return $request->validate([
            'gallery_section_id' => 'nullable|exists:gallery_sections,id',
            'image_path' => 'required|string|max:255',
            'caption' => 'nullable|string|max:255',
            'height_class' => 'required|string|max:255',
            'grid_class' => 'nullable|string|max:255',
            'sort_order' => 'required|integer|min:0',
            'is_featured' => 'sometimes|boolean',
        ]) + ['is_featured' => $request->boolean('is_featured')];
    }
}
