<?php

namespace App\Livewire\Expenses;

use App\Models\Expense;
use App\Models\ExpenseCategory;
use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\WithPagination;

#[Layout('layouts.dashboard')]
class Index extends Component
{
    use WithPagination;



    protected string $paginationTheme = 'tailwind';



    public function render(): \Illuminate\Contracts\View\View
    {
        $expenses = Expense::query()
            ->with(['category', 'user'])
            ->when(request('search'), function ($query) {
                $query->where('title', 'like', '%'.request('search').'%')
                    ->orWhere('description', 'like', '%'.request('search').'%');
            })
            ->when(request('status'), function ($query) {
                $statusValue = request('status') === '1';
                $query->where('status', $statusValue);
            })
            ->when(request('category_id'), function ($query) {
                $query->where('expense_category_id', request('category_id'));
            })
            ->when(request('start_date'), function ($query) {
                $query->where('expense_date', '>=', request('start_date'));
            })
            ->when(request('end_date'), function ($query) {
                $query->where('expense_date', '<=', request('end_date'));
            })
            ->orderByDesc('expense_date')
            ->paginate(25);

        $categories = ExpenseCategory::active()->orderBy('name')->get()->map(function ($category) {
                return (object) [
                    'value' => $category->id,
                    'label' => $category->name,
                ];
            })->toArray();

        $statuses = collect([
            (object) ['value' => '', 'label' => 'Tous'],
            (object) ['value' => '0', 'label' => 'Brouillon'],
            (object) ['value' => '1', 'label' => 'Approuvé'],
        ]);

        return view('livewire.expenses.index', [
            'expenses' => $expenses,
            'categories' => $categories,
            'statuses' => $statuses,
        ]);
    }
}
