<?php

namespace App\Livewire\Debts;

use App\Models\Debt;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

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

    protected string $paginationTheme = 'tailwind';

    public function render(): \Illuminate\Contracts\View\View
    {
        $debts = Debt::query()
            ->with(['customer'])
            ->when(request('search'), function ($query) {
                $query->whereHas('customer', function ($customerQuery) {
                    $customerQuery->where('name', 'like', '%'.request('search').'%');
                });
            })
            ->when(request('status'), function ($query) {
                $query->where('status', request('status'));
            })
            ->when(request('date_from'), function ($query) {
                $query->whereDate('created_at', '>=', request('date_from'));
            })
            ->when(request('date_to'), function ($query) {
                $query->whereDate('created_at', '<=', request('date_to'));
            })
            ->when(request('overdue') === '1', function ($query) {
                $query->where('due_date', '<', now())
                    ->where('status', '!=', Debt::STATUS_PAID);
            })
            ->orderByDesc('created_at')
            ->paginate(25);

        $statusOptions = collect([
            (object) ['value' => '', 'label' => 'Tous'],
            ...collect(Debt::DEBT_STATUSES)->map(function ($status) {
                return (object) [
                    'value' => $status['id'],
                    'label' => $status['name'],
                ];
            }),
        ]);

        return view('livewire.debts.index', [
            'debts' => $debts,
            'statusOptions' => $statusOptions,
        ]);
    }
}