<?php

namespace App\Livewire\Customers;

use App\Models\Customer;
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
    {
        $customers = Customer::query()
            ->with(['contact', 'sales' => function ($query) {
                $query->latest()->limit(1);
            }])
            ->when(request('search'), function ($query) {
                $query->where(function ($q) {
                    $q->where('name', 'like', '%'.request('search').'%')
                        ->orWhereHas('contact', function ($contactQuery) {
                            $contactQuery->where('phone', 'like', '%'.request('search').'%')
                                ->orWhere('email', 'like', '%'.request('search').'%');
                        });
                });
            })
            ->when(request('status'), function ($query) {
                $query->where('status', request('status'));
            })
            ->orderByDesc('created_at')
            ->paginate(25);

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

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