<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SaleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true; // Set to true to allow all authenticated users
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'customer_id' => 'required|exists:customers,id',
            'sale_type' => 'required|in:cash,installment',
            'sale_date' => 'required|date',
            'payment_method' => 'required|string|max:50',
            'vat_rate' => 'nullable|numeric|min:0|max:100',
            
            // Items validation
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|integer|min:1',
            'items.*.unit_price' => 'nullable|numeric|min:0',
            
            // Installment fields
            'down_payment' => 'required_if:sale_type,installment|nullable|numeric|min:0',
            'installment_months' => 'required_if:sale_type,installment|nullable|integer|min:1|max:60',
            'interest_rate' => 'nullable|numeric|min:0|max:100',
            
            // Discount
            'discount_amount' => 'nullable|numeric|min:0',
            
            // Notes
            'notes' => 'nullable|string|max:1000',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'customer_id.required' => 'Please select a customer.',
            'customer_id.exists' => 'Selected customer does not exist.',
            
            'sale_type.required' => 'Please select sale type.',
            'sale_type.in' => 'Invalid sale type selected.',
            
            'sale_date.required' => 'Sale date is required.',
            'sale_date.date' => 'Invalid sale date format.',
            
            'payment_method.required' => 'Payment method is required.',
            
            'items.required' => 'Please add at least one product.',
            'items.min' => 'Please add at least one product.',
            
            'items.*.product_id.required' => 'Please select a product.',
            'items.*.product_id.exists' => 'Selected product does not exist.',
            
            'items.*.quantity.required' => 'Quantity is required.',
            'items.*.quantity.min' => 'Quantity must be at least 1.',
            
            'down_payment.required_if' => 'Down payment is required for installment sales.',
            'down_payment.numeric' => 'Down payment must be a number.',
            'down_payment.min' => 'Down payment cannot be negative.',
            
            'installment_months.required_if' => 'Installment months is required for installment sales.',
            'installment_months.min' => 'Installment months must be at least 1.',
            'installment_months.max' => 'Installment months cannot exceed 60.',
            
            'interest_rate.max' => 'Interest rate cannot exceed 100%.',
            
            'discount_amount.min' => 'Discount cannot be negative.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Set default values
        $this->merge([
            'vat_rate' => $this->vat_rate ?? 0,
            'discount_amount' => $this->discount_amount ?? 0,
            'interest_rate' => $this->interest_rate ?? 0,
            'down_payment' => $this->down_payment ?? 0,
        ]);
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if any product is selected
            if (!$this->has('items') || empty($this->items)) {
                $validator->errors()->add('items', 'Please add at least one product.');
                return;
            }

            // Validate each item
            foreach ($this->items as $index => $item) {
                if (empty($item['product_id'])) {
                    $validator->errors()->add("items.{$index}.product_id", 'Please select a product.');
                }
                
                if (isset($item['quantity']) && $item['quantity'] < 1) {
                    $validator->errors()->add("items.{$index}.quantity", 'Quantity must be at least 1.');
                }
            }

            // Additional validation for installment sales
            if ($this->sale_type === 'installment') {
                if (empty($this->down_payment) || $this->down_payment <= 0) {
                    $validator->errors()->add('down_payment', 'Down payment is required for installment sales.');
                }
                
                if (empty($this->installment_months) || $this->installment_months < 1) {
                    $validator->errors()->add('installment_months', 'Installment months is required for installment sales.');
                }
            }
        });
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'customer_id' => 'customer',
            'sale_type' => 'sale type',
            'sale_date' => 'sale date',
            'payment_method' => 'payment method',
            'vat_rate' => 'VAT rate',
            'items' => 'products',
            'items.*.product_id' => 'product',
            'items.*.quantity' => 'quantity',
            'down_payment' => 'down payment',
            'installment_months' => 'installment months',
            'interest_rate' => 'interest rate',
            'discount_amount' => 'discount',
            'notes' => 'notes',
        ];
    }
}