<?php

namespace App\Livewire\Financial;

use App\Domain\Financial\Models\FacilityRentPayment;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('سجل إيجارات المنشآت')]
class FacilityRentList extends Component
{
    use WithPagination, UsesBranchScope, WithSorting;

    #[Url]
    public string $search = '';

    #[Url]
    public ?int $facility_filter = null;

    #[Url]
    public string $period_filter = '';

    public function mount(): void
    {
        if (!request()->has('sortBy')) {
            $this->sortBy = 'payment_date';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'desc';
        }
    }

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

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

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        $payments = FacilityRentPayment::with(['facility', 'creator'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->facility_filter, fn ($q) => $q->where('facility_id', $this->facility_filter))
            ->when($this->period_filter, fn ($q) => $q->where('period', $this->period_filter))
            ->when($this->search, fn ($q) => $q->where(function ($q) {
                $q->where('cheque_number', 'ilike', "%{$this->search}%")
                    ->orWhere('recipient_name', 'ilike', "%{$this->search}%")
                    ->orWhere('bank_name', 'ilike', "%{$this->search}%");
            }))
            ->orderBy($this->sortBy, $this->sortDir)
            ->paginate(20);

        $totalAmount = FacilityRentPayment::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->facility_filter, fn ($q) => $q->where('facility_id', $this->facility_filter))
            ->when($this->period_filter, fn ($q) => $q->where('period', $this->period_filter))
            ->sum('amount');

        return view('livewire.financial.facility-rent-list', [
            'payments' => $payments,
            'totalAmount' => $totalAmount,
        ]);
    }
}
