<?php

namespace App\Http\Controllers;

use App\Models\Gallery;
use App\Models\Image;
use App\Settings\GeneralSettings;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Inertia\Inertia;

class HomeController extends Controller
{
    public function __construct(private GeneralSettings $settings) {}

    public function index(Request $request, ?Gallery $gallery = null)
    {
        $gallery = $gallery ?: Gallery::first();

        if (! $gallery) {
            abort(404, 'Gallery not found');
        }

        $galleryHeading = $gallery->title ?: $this->settings->gallery_heading;
        $newImageTimespanMinutes = $this->settings->new_image_timespan_minutes;

        $images = Image::where('gallery_id', $gallery->id)
            ->orderByDesc('updated_at')
            ->get()
            ->map(function ($image) use ($newImageTimespanMinutes) {
                $image->is_new = Carbon::parse($image->created_at)->diffInMinutes(Carbon::now()) <= $newImageTimespanMinutes;
                $image->path = asset('storage/'.$image->path);

                return $image;
            });

        return Inertia::render('Home', [
            'galleryHeading' => $galleryHeading,
            'gallery' => [
                'id' => $gallery->id,
                'slug' => $gallery->slug,
                'title' => $galleryHeading,
                'allow_ai_styles' => $gallery->allow_ai_styles,
                'allow_print' => $gallery->allow_print,
                'images_path' => $gallery->images_path,
            ],
            'images' => $images,
        ]);
    }
}
