<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PaymentUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $providerId = auth()->user()->provider->id;

        return [
            'payment_date' => 'required|date',
            'amount' => 'required|numeric|min:0',
            'method' => 'required|in:cash,card,bank_transfer,other',
            'client_id' => [
                'nullable',
                'exists:clients,id',
                function ($attribute, $value, $fail) use ($providerId) {
                    if ($value && !\App\Models\Client::where('id', $value)->where('provider_id', $providerId)->exists()) {
                        $fail('Le client sélectionné ne vous appartient pas.');
                    }
                },
            ],
            'appointment_ids' => 'nullable|array',
            'appointment_ids.*' => [
                'exists:appointments,id',
                function ($attribute, $value, $fail) use ($providerId) {
                    if ($value && !\App\Models\Appointment::where('id', $value)->where('provider_id', $providerId)->exists()) {
                        $fail('Un des rendez-vous sélectionnés ne vous appartient pas.');
                    }
                },
            ],
            'notes' => 'nullable|string',
        ];
    }
}
