<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component {
    use AuthorizesRequests, 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()
            ->with(['phoneNumbers', 'emailSenders'])
            ->when($this->search !== '', function ($query)
            {
                $query->where(function ($subQuery)
                {
                    $term = '%' . $this->search . '%';
                    $subQuery
                        ->where('name', 'like', $term)
                        ->orWhere('domain', 'like', $term)
                        // Search the subsystems rather than the deprecated columns,
                        // matching what the list now displays.
                        ->orWhereHas('emailSenders', fn ($q) => $q->where('email_address', 'like', $term))
                        ->orWhereHas('phoneNumbers', fn ($q) => $q->where('phone_number', 'like', $term));
                });
            })
            ->orderBy('name')
            ->paginate($this->perPage);
    }

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