<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use App\Services\S3PresignedService;
use App\Settings\HomepageSettings;
use App\Settings\SocialMediaSettings;
use App\Settings\SystemSettings;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class HomepageController extends Controller
{
    public function __construct(
        private S3PresignedService $s3Service,
    ) {}

    public function __invoke(Request $request): Response
    {
        $system = app(SystemSettings::class);
        $homepage = app(HomepageSettings::class);
        $socialMedia = app(SocialMediaSettings::class);

        $categories = Category::select(['id', 'name', 'slug'])
            ->orderBy('name')
            ->get();

        $search = $request->input('search', '');
        $category = $request->input('category', '');

        $productsQuery = Product::select(['id', 'name', 'slug', 'description', 'status'])
            ->active()
            ->featured()
            ->with([
                'categories:id,name,slug',
                'productVariants:id,product_id,name,stock',
                'productVariants.productPrices:id,variant_id,type,price',
                'productVariants.media',
            ]);

        if ($search !== '') {
            $productsQuery->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        if ($category !== '') {
            $productsQuery->whereHas('categories', function ($q) use ($category) {
                $q->where('slug', $category);
            });
        }

        $s3Service = $this->s3Service;
        $products = Inertia::scroll(function () use ($productsQuery, $s3Service) {
            $paginator = $productsQuery->orderBy('created_at', 'desc')->paginate(12);

            $paginator->getCollection()->each(function ($product) use ($s3Service) {
                $product->productVariants->each(function ($variant) use ($s3Service) {
                    $media = $variant->getMedia('images');
                    $variant->photo_urls = $media->map(
                        fn ($m) => str_starts_with($m->getPath(), 'http')
                            ? $m->getPath()
                            : $s3Service->getTemporaryUrl($m->getPath(), 60)
                    )->toArray();
                });
            });

            return $paginator;
        });

        $galleryImages = array_map(
            fn ($key) => str_starts_with($key, 'http') ? $key : $this->s3Service->getTemporaryUrl($key, 60),
            $homepage->gallery_images ?? [],
        );

        return Inertia::render('welcome', [
            'appName' => $system->app_name,
            'aboutApp' => $system->about_app,
            'contactEmail' => $system->email,
            'contactPhone' => $system->phone,
            'contactAddress' => $system->address,
            'instagramUrl' => $socialMedia->instagram_url,
            'facebookUrl' => $socialMedia->facebook_url,
            'tiktokUrl' => $socialMedia->tiktok_url,
            'homepage' => [
                'hero_image_url' => $homepage->hero_image_url
                    ? (str_starts_with($homepage->hero_image_url, 'http') ? $homepage->hero_image_url : $this->s3Service->getTemporaryUrl($homepage->hero_image_url, 60))
                    : null,
                'about_image_url' => $homepage->about_image_url
                    ? (str_starts_with($homepage->about_image_url, 'http') ? $homepage->about_image_url : $this->s3Service->getTemporaryUrl($homepage->about_image_url, 60))
                    : null,
                'gallery_images' => $galleryImages,
            ],
            'categories' => $categories,
            'products' => $products,
            'filters' => [
                'search' => $search,
                'category' => $category,
            ],
            'seo' => [
                'title' => $system->app_name.' - Koleksi Segar 2026',
                'description' => 'Selamat datang di '.$system->app_name.'. Temukan keanggunan motif batik modern dan setelan pakaian santai berkualitas premium.',
                'image' => url('/assets/logo.png'),
                'url' => url('/'),
            ],
        ]);
    }
}
