<?php

namespace App\Livewire\Sales;

use App\Models\Sale;
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
    {
        $sales = Sale::query()
            ->with(['customer', 'paymentMethod', 'saleType', 'user'])
            ->when(request('search'), function ($query) {
                $query->where(function ($q) {
                    $q->where('sale_number', 'like', '%'.request('search').'%')
                        ->orWhereHas('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('sale_date', '>=', request('date_from'));
            })
            ->when(request('date_to'), function ($query) {
                $query->whereDate('sale_date', '<=', request('date_to'));
            })
            ->orderByDesc('sale_date')
            ->paginate(25);

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

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