<?php

namespace App\Livewire;

use App\Models\Downloads;
use Livewire\Component;
use Livewire\WithPagination;

class DownloadsSearch extends Component
{
    use WithPagination;

    public $fileSearch;

    public $order = 'created_at_desc';

    protected $queryString = [
        'fileSearch'    => ['except' => '', 'as' => 'fS'],
        'order'         => ['except' => '', 'as' => 'order'],
    ];

    public function updatingFileSearch()
    {
        $this->resetPage();
    }

    public function clicked($downloadId)
    {
        $download = Downloads::find($downloadId);
        if (!$download) {
            return;
        }

        $download->count++;
        $download->save();
        cache()->forget("episode_{$download->episode->id}_download_{$download->type}");
    }

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

        switch ($this->order) {
            case 'az':
                $orderby = 'url';
                $orderdirection = 'asc';
                break;
            case 'za':
                $orderby = 'url';
                $orderdirection = 'desc';
                break;
            case 'created_at_desc':
                $orderby = 'created_at';
                $orderdirection = 'desc';
                break;
            case 'created_at_asc':
                $orderby = 'created_at';
                $orderdirection = 'asc';
                break;
            case 'size_asc':
                $orderby = 'size';
                $orderdirection = 'asc';
                break;
            case 'size_desc':
                $orderby = 'size';
                $orderdirection = 'desc';
                break;
            default:
                $orderby = 'created_at';
                $orderdirection = 'desc';
        }

        $downloads = Downloads::when($this->fileSearch != '', fn ($query) => $query->where('url', 'like', '%'.$this->fileSearch.'%'))
            ->when(!auth()->user()->is_patreon, fn ($query) => $query->whereIn('type', ['FHD', 'FHDi']))
            ->whereNotNull('size')
            ->orderBy($orderby, $orderdirection)
            ->paginate(20);

        return view('livewire.downloads-search', [
            'downloads'       => $downloads,
            'query'           => $this->fileSearch,
        ]);
    }
}
