<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use App\Services\HistoryService;
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, HistoryService $history): void {
        $this->authorize('solicitors.delete');
        $solicitor = Solicitor::findOrFail($id);
        $context = ['solicitor_id' => $solicitor->id, 'name' => $solicitor->name];
        $solicitor->delete();

        // The solicitor's own history cascades away with it, so record against the acting user.
        $history->addForActor("Deleted solicitor \"{$context['name']}\"", $context);

        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,
        ]);
    }
}
