<?php

namespace App\Components\WillsCase;

use App\Models\WillsCase\WillsCase;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

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

    public string $search = '';
    public string $status = 'all'; // all | open | closed
    public int $perPage = 25;

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

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

    public function render() {
        $query = WillsCase::with('client')->orderByDesc('created_at');

        if ($this->search) {
            $term = '%' . $this->search . '%';
            $query->where(function ($q) use ($term) {
                $q->where('case_number', 'like', $term)
                  ->orWhere('national_insurance', 'like', $term)
                  ->orWhereHas('client', fn($c) => $c->where('name_first', 'like', $term)
                      ->orWhere('name_last', 'like', $term));
            });
        }

        if ($this->status === 'open') {
            $query->open();
        } elseif ($this->status === 'closed') {
            $query->closed();
        }

        $cases = $query->paginate($this->perPage);

        return view('components.wills-case.index', compact('cases'));
    }

    public function placeholder() {
        return <<<HTML
<div>
    <div class="placeholder-glow mb-3">
        <span class="placeholder col-4 placeholder-lg"></span>
    </div>
    <div class="card shadow-sm">
        <div class="card-body">
            <div class="placeholder-glow">
                <span class="placeholder col-12 mb-2"></span>
                <span class="placeholder col-12 mb-2"></span>
                <span class="placeholder col-10 mb-2"></span>
            </div>
        </div>
    </div>
</div>
HTML;
    }
}
