<?php

namespace App\Livewire\Services;

use App\Models\Service;
use App\Models\ServiceCategory;
use Livewire\Component;

class ServiceDetail extends Component
{
    public $category;
    public $service;

    public function mount($categorySlug, $serviceSlug)
    {
        $this->category = ServiceCategory::where('slug', $categorySlug)
            ->where('status', 1)
            ->firstOrFail();

        // 1) Try direct slug first
        $service = Service::where('service_category_id', $this->category->id)
            ->where('status', 1)
            ->with('works')
            ->where('slug', $serviceSlug)
            ->first();

        // 2) If not found, try redirect_slug (old slug)
        if (!$service) {
            $service = Service::where('service_category_id', $this->category->id)
                ->where('status', 1)
                ->with('works')
                ->where('redirect_slug', $serviceSlug)
                ->first();

            // old slug hit → 301 redirect to new slug URL
            if ($service) {
                return redirect()->route(
                    'services.category.service',
                    [$categorySlug, $service->slug],
                    301
                );
            }
        }

        // 3) Still not found → 404
        $this->service = $service ?? abort(404);
    }

    public function render()
    {
        return view('livewire.services.service-detail')
            ->layout('components.layout');
    }
}
