<?php

namespace App\Livewire\Home\Product;

use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('components.layouts.home', [
    'title' => 'Detail Produk',
])]
class Show extends Component
{
    public $product;

    public $productType;

    public array $relatedProducts = [];

    public function mount(string $slug): void
    {
        // Try to find product in all tables
        $this->product = Perfume::where('slug', $slug)->first();
        if ($this->product) {
            $this->productType = 'perfume';
            $this->product->load(['brand', 'categories']);
        } else {
            $this->product = Bottle::where('slug', $slug)->first();
            if ($this->product) {
                $this->productType = 'bottle';
            } else {
                $this->product = Product::where('slug', $slug)->firstOrFail();
                $this->productType = 'arabian';
            }
        }

        // Increment views
        $this->product->increment('views');

        // Load related products
        $this->loadRelatedProducts();
    }

    private function loadRelatedProducts(): void
    {
        $query = match ($this->productType) {
            'perfume' => Perfume::query()
                ->where('id', '!=', $this->product->id)
                ->when($this->product->categories->isNotEmpty(), function ($q) {
                    $q->whereHas('categories', function ($categoryQuery) {
                        $categoryQuery->whereIn('categories.id', $this->product->categories->pluck('id'));
                    });
                })
                ->with(['brand', 'categories']),
            'bottle' => Bottle::query()->where('id', '!=', $this->product->id),
            'arabian' => Product::query()->where('id', '!=', $this->product->id),
        };

        $this->relatedProducts = $query
            ->inRandomOrder()
            ->take(4)
            ->get()
            ->map(function ($product) {
                return [
                    'id' => $product->id,
                    'slug' => $product->slug,
                    'name' => $product->name,
                    'price' => $product->sale_price,
                    'image' => $product->getFirstMediaUrl('image') ?: asset('assets/images/dark-logo.png'),
                    'category' => $this->productType === 'perfume' ? $product->categories->first()?->name : null,
                ];
            })
            ->toArray();
    }

    public function render(): View
    {
        $product = $this->product;
        $product->image = $product->getFirstMediaUrl('image') ?: asset('assets/images/dark-logo.png');

        return view('livewire.home.product.show', [
            'pageTitle' => $this->product->name,
            'pageDesc' => 'Detail produk',
        ]);
    }
}
