<?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 ClientList extends Component {

    use WithPagination;

    public $search = '';
    public $sortColumn = 'name_last';
    public $sortDirection = 'asc';
    public $perPage = 10;
    protected ClientService $clientService;

    public function placeholder() {
        return <<<'HTML'
        <div class="row">
            <div class="col-12 col-md-9">
                <div class="card">
                    <div class="card-body">
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-75"></div>
                        <div class="placeholder placeholder-wave w-50"></div>
                    </div>
                </div>
            </div>
        </div>
        HTML;

    }

    public function boot(ClientService $clientService) {
        $this->clientService = $clientService;
    }


    public function render() {
        $clients = Client::query();

        if ($this->search !== '') {
            $clients
                ->where('name_first', 'like', '%' . $this->search . '%')
                ->orWhere('email_address', 'like', '%' . $this->search . '%')
                ->orWhere('phone_number', 'like', '%' . $this->search . '%')
                ->orWhere('name_last', 'like', '%' . $this->search . '%');
        }

        $clients = $clients->paginate($this->perPage);
        return view('components.client.client-list', compact('clients'));
    }

    public function checkDeleteClient($clientId) {
        $this->dispatch('swal:confirm',
            itemId: $clientId,
            title: 'Are you absolutely sure?',
            text: 'You will not be able to recover this client.'
        );
    }

    public function deleteClient($clientId) {
        $client = Client::findOrFail($clientId);
        if ($this->clientService->delete($client)) {
            $this->dispatch("alert", title: $client->name_first . " " . $client->name_last . " Deleted");
        }
    }
}
