<?php

namespace App\Livewire\Financial;

use App\Domain\Financial\Enums\ExpenseCategory;
use App\Domain\Financial\Models\Expense;
use App\Domain\Shared\Traits\UsesBranchScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('سجل المصروفات')]
class ExpenseList extends Component
{
    use WithPagination, UsesBranchScope;

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

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

    #[Url]
    public ?string $from_date = null;

    #[Url]
    public ?string $to_date = null;

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

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

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

        $expenses = Expense::with(['creator'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->category_filter, fn ($q) => $q->where('category', $this->category_filter))
            ->when($this->from_date, fn ($q) => $q->where('expense_date', '>=', $this->from_date))
            ->when($this->to_date, fn ($q) => $q->where('expense_date', '<=', $this->to_date))
            ->when($this->search, fn ($q) => $q->where(function ($q) {
                $q->where('description', 'ilike', "%{$this->search}%")
                    ->orWhere('recipient_name', 'ilike', "%{$this->search}%");
            }))
            ->orderByDesc('expense_date')
            ->paginate(20);

        $totalAmount = Expense::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->category_filter, fn ($q) => $q->where('category', $this->category_filter))
            ->when($this->from_date, fn ($q) => $q->where('expense_date', '>=', $this->from_date))
            ->when($this->to_date, fn ($q) => $q->where('expense_date', '<=', $this->to_date))
            ->sum('amount');

        return view('livewire.financial.expense-list', [
            'expenses' => $expenses,
            'totalAmount' => $totalAmount,
            'categories' => ExpenseCategory::cases(),
        ]);
    }
}
