<?php

namespace App\Livewire\Studio\Master\Outlet;

use App\Enums\Day;
use App\Models\Outlet;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Media\WithMediaHandler;
use App\Traits\Utilities\WithRequestNotification;
use Flux\Flux;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Outlet')]
class Index extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithMediaHandler, WithRequestNotification, WithToast;

    public string $search = '';

    public array $status = [];

    protected function formatOpeningHours(Outlet $outlet): array
    {
        if (! $outlet->openingHours || $outlet->openingHours->isEmpty()) {
            return [];
        }

        return $outlet->openingHours->mapWithKeys(fn ($hour) => [
            Str::ucfirst(Str::lower(Day::from($hour->day->value)->label())) => [
                'open' => formatTime($hour->open_time),
                'close' => formatTime($hour->close_time),
                'is_closed' => $hour->open_time === null && $hour->close_time === null,
            ],
        ])->toArray();
    }

    protected function getFeaturedImage(Outlet $outlet): string
    {
        $mediaCollection = $this->mapMediaCollection($outlet->getMedia('featured_image'));

        return data_get($mediaCollection[0] ?? null, 'temporaryUrl', asset('assets/images/logo.png'));
    }

    protected function getGalleryImages(Outlet $outlet): array
    {
        return collect($this->mapMediaCollection($outlet->getMedia('images')))
            ->pluck('temporaryUrl')
            ->filter()
            ->values()
            ->toArray();
    }

    public function delete(Outlet $outlet): void
    {
        $this->canOrAbort('delete outlet');

        $outlet->delete();
        $this->toast('Outlet berhasil dihapus.');
        Flux::modals()->close();
    }

    public function render(): View
    {
        $outlets = Outlet::with(['openingHours', 'facilities'])
            ->when(! empty($this->search), fn ($query) => $query->where('name', 'like', '%'.$this->search.'%'))
            ->when(! empty($this->status), fn ($query) => $query->whereIn('status', $this->status))
            ->latest()
            ->get();

        return view('livewire.studio.master.outlet.index', [
            'pageTitle' => 'Outlet',
            'outlets' => $outlets,
        ]);
    }
}
