<?php

namespace App\Livewire\Customers;

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

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

    protected string $paginationTheme = 'tailwind';

    public Customer $customer;

    public function mount(Customer $customer)
    {
        // Ensure customer belongs to current merchant
        // No merchant filtering needed for single-tenant app
        
        $this->customer = $customer;
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        $sales = Sale::query()
            ->where('customer_id', $this->customer->id)
            ->with(['paymentMethod', 'saleType', 'user'])
            ->when(request('search'), function ($query) {
                $query->where('sale_number', '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.customers.sales', [
            'sales' => $sales,
            'statusOptions' => $statusOptions,
        ]);
    }
}
