<?php

declare(strict_types=1);

namespace App\Http\Requests\Catalog;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'project_id' => ['required_without:product_id', 'nullable', 'integer', 'exists:projects,id'],
            'product_id' => ['required_without:project_id', 'nullable', 'integer', 'exists:products,id'],
            'offer_to' => ['nullable', 'integer', 'exists:users,id'],
            'name' => ['nullable', 'string', 'min:2', 'max:255'],
            'description' => ['nullable', 'string', 'max:10000'],
            'amount' => ['nullable', 'numeric', 'min:0'],
            'price' => ['nullable', 'numeric', 'min:0'],
            'quantity' => ['nullable', 'integer', 'min:1'],
            'unit' => ['nullable', 'string', 'max:50'],
            'offer_type' => ['nullable', 'string', 'max:50'],
            'contract_type' => ['nullable', 'string', 'max:50'],
            'expiry_date' => ['nullable', 'date'],
            'contract_start_date' => ['nullable', 'date'],
            'contract_end_date' => ['nullable', 'date', 'after_or_equal:contract_start_date'],
            'duration_days' => ['nullable', 'integer', 'min:1'],
            'notes' => ['nullable', 'string', 'max:5000'],
            'specifications' => ['nullable', 'array'],
        ];
    }

    public function messages(): array
    {
        return [
            'project_id.required_without' => 'انتخاب پروژه یا محصول الزامی است.',
            'product_id.required_without' => 'انتخاب پروژه یا محصول الزامی است.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->filled('amount') && ! $this->filled('price')) {
            $this->merge(['price' => $this->input('amount')]);
        }
    }
}
