<?php

namespace App\Livewire\Home;

use App\Models\Outlet as OutletModel;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('components.layouts.home', [
    'title' => 'Outlet',
])]
class Outlet extends Component
{
    public array $outlets = [];

    public string $search = '';

    public ?OutletModel $selectedOutlet = null;

    public function mount(): void
    {
        $this->outlets = OutletModel::with(['facilities', 'openingHours'])
            ->operational()
            ->when($this->search, function ($query) {
                $query->where(function ($query) {
                    $query->where('name', 'like', '%'.$this->search.'%')
                        ->orWhere('address', 'like', '%'.$this->search.'%');
                });
            })
            ->latest()
            ->get()
            ->map(function ($outlet) {
                $outlet->image = $outlet->getFirstMediaUrl('featured_image') ? $outlet->getFirstMediaUrl('featured_image') : asset('assets/images/dark-logo.png');
                $outlet->status_label = $outlet->status->label();
                $outlet->status_color = $outlet->status->color();

                return $outlet;
            })
            ->toArray();
    }

    public function showDetail(int $outletId): void
    {
        $this->selectedOutlet = OutletModel::with(['facilities', 'openingHours'])->find($outletId);
    }

    public function closeModal(): void
    {
        $this->selectedOutlet = null;
    }

    public function render(): View
    {
        return view('livewire.home.outlets', [
            'pageTitle' => 'Outlet',
        ]);
    }
}
