<?php

namespace App\Components\Solicitor;

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

class Index extends Component {
    use WithPagination;

    public string $search = '';
    public int $perPage = 10;
    public bool $readyToLoad = false;

    protected $queryString = [
        'search' => ['except' => ''],
        'page' => ['except' => 1],
    ];

    public function mount(): void {
        $this->authorize('solicitors.view');
        // Keep false initially so the heavy query does not run on first paint.
    }

    public function loadSolicitors(): void {
        $this->readyToLoad = true;
    }

    public function updatingSearch(): void {
        $this->resetPage();
    }

    public function updatedPerPage(): void {
        $this->resetPage();
    }

    public function delete(int $id): void {
        $this->authorize('solicitors.delete');
        Solicitor::findOrFail($id)->delete();

        session()->flash('success', 'Solicitor deleted successfully.');
    }

    public function getSolicitorsProperty() {
        if (!$this->readyToLoad) {
            return collect();
        }

        return Solicitor::query()
            ->when($this->search !== '', function ($query)
            {
                $query->where(function ($subQuery)
                {
                    $subQuery
                        ->where('name', 'like', '%' . $this->search . '%')
                        ->orWhere('domain', 'like', '%' . $this->search . '%')
                        ->orWhere('email_address', 'like', '%' . $this->search . '%')
                        ->orWhere('phone_number', 'like', '%' . $this->search . '%');
                });
            })
            ->orderBy('name')
            ->paginate($this->perPage);
    }

    public function render() {
        return view('components.solicitor.index', [
            'solicitors' => $this->solicitors,
        ]);
    }
}
