<?php

namespace App\Livewire\Customers;

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

#[Layout('layouts.dashboard')]
class Debts 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
    {
        $debts = Debt::query()
            ->where('customer_id', $this->customer->id)
            ->with(['sale'])
            ->when(request('search'), function ($query) {
                $query->whereHas('sale', function ($saleQuery) {
                    $saleQuery->where('sale_number', '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'));
            })
            ->orderByDesc('created_at')
            ->paginate(25);

        $statusOptions = collect([
            (object) ['value' => '', 'label' => 'Tous'],
            (object) ['value' => Debt::STATUS_PENDING, 'label' => 'En attente'],
            (object) ['value' => Debt::STATUS_PAID, 'label' => 'Payée'],
        ]);

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