<?php

namespace App\Livewire;

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

class Playlists extends Component
{
    use WithPagination;

    #[Url(history: true)]
    public $search;

    #[Url(history: true)]
    public $order = 'episode-count';

    public $pagination = 12;

    public function render()
    {
        $orderby = 'episodes_count';
        $orderdirection = 'desc';

        switch ($this->order) {
            case 'az':
                $orderby = 'name';
                $orderdirection = 'asc';
                break;
            case 'za':
                $orderby = 'name';
                $orderdirection = 'desc';
                break;
            case 'episode-count':
                $orderby = 'episodes_count';
                $orderdirection = 'desc';
                break;
            case 'newest':
                $orderby = 'created_at';
                $orderdirection = 'desc';
                break;
            case 'oldest':
                $orderby = 'created_at';
                $orderdirection = 'asc';
                break;
            default:
                $orderby = 'episodes_count';
                $orderdirection = 'desc';
        }

        $playlists = Playlist::where('is_private', 0)
            ->withCount('episodes')
            ->having('episodes_count', '>', 1)
            ->when($this->search != '', fn ($query) => $query->where('name', 'like', '%'.$this->search.'%'))
            ->orderBy($orderby, $orderdirection)
            ->paginate($this->pagination);

        return view('livewire.playlists', [
            'playlists' => $playlists,
        ]);
    }
}
