<?php

namespace App\Livewire;

use App\Models\EntryReview;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class Reviews extends Component
{

    use WithPagination;

    #[Url(except:null)]
    public ?int $entryId = null;

    #[Url(except:null)]
    public ?int $rating = null;

    /**
     * Sort by field.
     * @var string
     */
    #[Url(as: 'sort',except: 'created_at')]
    public string $sortBy = 'created_at';

    /**
     * asc/desc
     * @var string
     */
    #[Url(as: 'dir',except: 'desc')]
    public string $sortDir = 'desc';

    /**
     * Translation of sort options key.
     */
    public const array SORT_OPTIONS = [
        'created_at' => 'Date added',
        'rating' => 'Rating',
        'title' => 'Title'
    ];

    public const int PAGINATION = 30;

    public function updatedEntryId(): void { $this->resetPage(); $this->dispatch('filters-updated'); }
    public function updatedRating(): void { $this->resetPage(); $this->dispatch('filters-updated'); }

    public function clearFilters(): void
    {
        $this->reset([
            'entryId', 'rating'
        ]);
        $this->dispatch('filters-updated');
        $this->resetPage();
    }

    public function setSort(string $field): void
    {
        if( $this->sortBy === $field ) {
            $this->sortDir = $this->sortDir === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDir = 'asc';
        }
        $this->resetPage();
        $this->dispatch('filters-updated');
    }

    private function buildQuery()
    {
        $query = EntryReview::query()->with([
            'entry'
        ]);

        if( $this->entryId ) {
            $query->where('entry_id', $this->entryId);
        }
        if( $this->rating ){
            $query->where('rating', $this->rating);
        }

        return $query->orderBy($this->sortBy, $this->sortDir);
    }

    public function render()
    {
        return view('livewire.reviews', [
            'reviews' => $this->buildQuery()->paginate(self::PAGINATION),
        ]);
    }
}
