<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Services\ClientService;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

#[Lazy]
class ClientIndex extends Component
{
    use WithPagination;

    public string $search    = '';
    public string $date_from = '';
    public string $date_to   = '';
    public int    $perPage   = 25;

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

    public function render()
    {
        $query = Client::query()->orderBy('name_last')->orderBy('name_first');

        if ($this->search !== '') {
            $term = '%' . trim($this->search) . '%';
            $query->where(function ($q) use ($term) {
                $q->where('name_first', 'like', $term)
                  ->orWhere('name_last', 'like', $term)
                  ->orWhere('email_address', 'like', $term)
                  ->orWhere('phone_number', 'like', $term);
            });
        }

        if ($this->date_from) {
            $query->whereDate('created_at', '>=', $this->date_from);
        }

        if ($this->date_to) {
            $query->whereDate('created_at', '<=', $this->date_to);
        }

        return view('components.client.client-index', [
            'clients' => $query->paginate($this->perPage),
        ]);
    }

    public function placeholder()
    {
        return <<<'HTML'
        <div class="card">
            <div class="card-body placeholder-glow">
                <span class="placeholder col-12 mb-2"></span>
                <span class="placeholder col-12 mb-2"></span>
                <span class="placeholder col-8"></span>
            </div>
        </div>
        HTML;
    }
}
