<?php

namespace App\Components\PensionCase;

use App\Models\PensionCase\PensionCase;
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 string $settlementStatus = '';
    public string $bankStatus = '';
    public string $fosStatus = '';
    public string $fscsStatus = '';
    public string $priority = '';
    public string $vulnerable = '';
    public int $perPage = 25;

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

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

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

        if ($this->search) {
            $term = '%' . $this->search . '%';
            $query->where(function ($q) use ($term) {
                $q->where('sf_case_id', 'like', $term)
                  ->orWhere('case_number', 'like', $term)
                  ->orWhere('national_insurance', 'like', $term)
                  ->orWhere('cmc_client_reference', '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();
        }

        if ($this->settlementStatus) {
            $query->where('settlement_status', $this->settlementStatus);
        }

        if ($this->bankStatus) {
            $query->where('bank_claim_status', $this->bankStatus);
        }

        if ($this->fosStatus) {
            $query->where('fos_claim_status', $this->fosStatus);
        }

        if ($this->fscsStatus) {
            $query->where('fscs_claim_status', $this->fscsStatus);
        }

        if ($this->priority) {
            $query->where('priority', $this->priority);
        }

        if ($this->vulnerable === '1') {
            $query->vulnerable();
        }

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

        return view('components.pension-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;
    }
}
