<?php

namespace App\Components\HaClaim;

use App\Models\Claim\Claim;
use App\Models\Claim\Status;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

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

    public string $search = '';
    public string $statusId = '';
    public string $redressType = '';
    public int $perPage = 25;

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

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

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

    public function render() {
        $query = Claim::with(['client', 'status'])
            ->when($this->search, function ($q) {
                $q->where(function ($q) {
                    $q->where('case_number', 'like', '%' . $this->search . '%')
                      ->orWhereHas('client', fn($q) => $q->where('name_first', 'like', '%' . $this->search . '%')
                          ->orWhere('name_last', 'like', '%' . $this->search . '%'));
                });
            })
            ->when($this->statusId, fn($q) => $q->where('status_id', $this->statusId))
            ->when($this->redressType, fn($q) => $q->where('redress_type', $this->redressType))
            ->orderByDesc('created_at');

        return view('components.ha-claim.index', [
            'claims'   => $query->paginate($this->perPage),
            'statuses' => Status::orderBy('sort_order')->get(),
        ]);
    }

    public function placeholder() {
        return <<<'HTML'
<div class="card">
    <div class="card-body">
        <div class="placeholder-glow">
            <span class="placeholder col-12" style="height:40px;"></span>
        </div>
    </div>
</div>
HTML;
    }
}
