<?php

namespace App\Http\Controllers;

use App\Models\Banner;
use App\Models\Category;
use App\Models\Country;
use App\Models\Currency;
use App\Models\Game;
use App\Models\ProductVariant;
use App\Services\AnalyticsTracker;
use Illuminate\Http\Request;

class StorefrontController extends Controller
{
    public function home(Request $request, AnalyticsTracker $analytics)
    {
        $query = trim((string) $request->query('q', ''));
        $categorySlug = $request->query('category');

        $services = Game::query()
            ->with(['category', 'productVariants' => fn ($builder) => $builder->where('status', 'active')->orderBy('price_minor')])
            ->withMin(['productVariants as starting_price_minor' => fn ($builder) => $builder->where('status', 'active')], 'price_minor')
            ->where('is_active', true)
            ->whereHas('productVariants', fn ($builder) => $builder->where('status', 'active'))
            ->when($query !== '', function ($builder) use ($query) {
                $builder->where(function ($nested) use ($query) {
                    $nested
                        ->where('name_ar', 'like', "%{$query}%")
                        ->orWhere('name_en', 'like', "%{$query}%")
                        ->orWhere('publisher', 'like', "%{$query}%")
                        ->orWhereHas('productVariants', function ($variantQuery) use ($query) {
                            $variantQuery
                                ->where('name_ar', 'like', "%{$query}%")
                                ->orWhere('name_en', 'like', "%{$query}%")
                                ->orWhere('sku', 'like', "%{$query}%");
                        });
                });
            })
            ->when($categorySlug, function ($builder) use ($categorySlug) {
                $builder->whereHas('category', fn ($category) => $category->where('slug', $categorySlug));
            })
            ->orderByDesc('is_featured')
            ->latest()
            ->limit(24)
            ->get();

        $analytics->track($request, 'page_view', 'page', null, ['name' => 'home']);

        if ($query !== '') {
            $analytics->track($request, 'search', 'search', null, [
                'query' => $query,
                'results' => $services->count(),
            ]);
        }

        return view('store.home', [
            'banners' => Banner::where('is_active', true)->orderBy('sort_order')->get(),
            'categories' => Category::where('is_active', true)->orderBy('sort_order')->get(),
            'games' => $services,
            'services' => $services,
            'products' => $services->flatMap->productVariants,
            'countries' => Country::where('is_active', true)->get(),
            'currencies' => Currency::where('is_active', true)->get(),
            'query' => $query,
            'categorySlug' => $categorySlug,
        ]);
    }

    public function service(Game $game, Request $request, AnalyticsTracker $analytics)
    {
        abort_unless($game->is_active, 404);

        $game->load(['category', 'productVariants' => fn ($builder) => $builder->where('status', 'active')->orderBy('price_minor')]);

        abort_if($game->productVariants->isEmpty(), 404);

        $selected = $game->productVariants->firstWhere('id', (int) $request->query('variant')) ?? $game->productVariants->first();

        $analytics->track($request, 'product_view', 'game', $game->id, [
            'slug' => $game->slug,
            'selected_variant_id' => $selected?->id,
        ]);

        return $this->serviceView($game, $selected);
    }

    public function product(ProductVariant $productVariant, Request $request, AnalyticsTracker $analytics)
    {
        abort_unless($productVariant->status === 'active', 404);

        $productVariant->load(['game.category']);
        $game = $productVariant->game->load(['productVariants' => fn ($builder) => $builder->where('status', 'active')->orderBy('price_minor')]);

        $analytics->track($request, 'product_view', 'product_variant', $productVariant->id, [
            'game_id' => $game->id,
            'sku' => $productVariant->sku,
        ]);

        return $this->serviceView($game, $productVariant);
    }

    private function serviceView(Game $game, ProductVariant $selectedVariant)
    {
        return view('store.product', [
            'service' => $game,
            'game' => $game,
            'variants' => $game->productVariants,
            'selectedVariant' => $selectedVariant,
            'product' => $selectedVariant,
            'related' => ProductVariant::where('game_id', $game->id)->whereKeyNot($selectedVariant->id)->where('status', 'active')->limit(4)->get(),
        ]);
    }

    public function checkout(ProductVariant $productVariant, Request $request, AnalyticsTracker $analytics)
    {
        abort_unless($productVariant->status === 'active', 404);

        $analytics->track($request, 'checkout_start', 'product_variant', $productVariant->id, [
            'sku' => $productVariant->sku,
        ]);

        return view('store.checkout', [
            'product' => $productVariant->load('game'),
        ]);
    }
}
