<?php

namespace App\Http\Requests\Purchase;

use App\Http\Requests\BaseFormRequest;

/**
 * Form request validation for Purchase Order
 * Field names match the frontend form submission
 */
class StorePurchaseOrderRequest extends BaseFormRequest
{
    protected function prepareForValidation(): void
    {
        // Convert empty strings to null for nullable date and numeric fields
        $fieldsToNullify = [
            'quotationDate', 'rfqDate', 'soCompanyId', 'soCompanyEmail',
            'totalAmount', 'sgstA', 'cgstA', 'IgstA', 'roundUp',
            'additionalCharges', 'quotationNo2', 'quotationId',
        ];

        $data = [];
        foreach ($fieldsToNullify as $field) {
            if ($this->has($field) && $this->input($field) === '') {
                $data[$field] = null;
            }
        }

        // Also handle empty strings in tableProducts items
        if ($this->has('tableProducts') && is_array($this->input('tableProducts'))) {
            $products = $this->input('tableProducts');
            foreach ($products as $i => $item) {
                foreach ($item as $key => $value) {
                    if ($value === '') {
                        $products[$i][$key] = null;
                    }
                }
            }
            $data['tableProducts'] = $products;
        }

        if (!empty($data)) {
            $this->merge($data);
        }
    }

    public function rules(): array
    {
        return [
            // Main PO fields (matches frontend form names)
            'sOrderNo' => 'required|string|unique:purchase_orders,purchase_order_no',
            'sOrderDate' => 'required|date',
            'soCompanyName' => 'required|string|max:255',
            'soCompanyId' => 'nullable|exists:customer_vendors,id',
            'soCompanyAddress' => 'nullable|string|max:500',
            'soCompanyGSTN' => 'nullable|string|max:20',
            'soCompanyPhone' => 'nullable|string|max:20',
            'soCompanyEmail' => 'nullable|email|max:255',
            'quotationNo2' => 'nullable|string|max:100',
            'quotationDate' => 'nullable|date',
            'custRefNo' => 'nullable|string|max:100',
            'rfqNo' => 'nullable|string|max:100',
            'rfqDate' => 'nullable|date',
            'billAddress' => 'nullable|string|max:500',
            'shipAddress' => 'nullable|string|max:500',
            'projectDescription' => 'nullable|string|max:2000',
            'deliveryTerms' => 'nullable|string|max:1000',
            'note' => 'nullable|string|max:2000',

            // Amount fields
            'totalAmount' => 'nullable|numeric|min:0',
            'sgstA' => 'nullable|numeric|min:0',
            'cgstA' => 'nullable|numeric|min:0',
            'IgstA' => 'nullable|numeric|min:0',
            'additionalCharges' => 'nullable|string',
            'roundUp' => 'nullable|numeric',
            'grandTotal' => 'required|numeric|min:0',
            'inr_in_words' => 'nullable|string|max:500',

            // Items array
            'tableProducts' => 'required|array|min:1',
            'tableProducts.*.sl_no' => 'nullable|integer',
            'tableProducts.*.item' => 'nullable|string|max:255',
            'tableProducts.*.description' => 'nullable|string|max:500',
            'tableProducts.*.req_by_date' => 'nullable|date',
            'tableProducts.*.quantity' => 'nullable|numeric|min:0',
            'tableProducts.*.uom' => 'nullable|string|max:20',
            'tableProducts.*.unit_rate' => 'nullable|numeric|min:0',
            'tableProducts.*.tds' => 'nullable|numeric|min:0|max:100',
            'tableProducts.*.discount' => 'nullable|numeric|min:0|max:100',
            'tableProducts.*.sgst' => 'nullable|numeric|min:0|max:50',
            'tableProducts.*.cgst' => 'nullable|numeric|min:0|max:50',
            'tableProducts.*.igst' => 'nullable|numeric|min:0|max:50',
            'tableProducts.*.value' => 'nullable|numeric|min:0',
            'tableProducts.*.amount' => 'nullable|numeric|min:0',
        ];
    }

    public function attributes(): array
    {
        return [
            'sOrderNo' => 'Purchase Order Number',
            'sOrderDate' => 'PO Date',
            'soCompanyName' => 'Vendor Name',
            'grandTotal' => 'Grand Total',
            'tableProducts' => 'Items',
        ];
    }

    public function messages(): array
    {
        return [
            'sOrderNo.unique' => 'This Purchase Order number already exists.',
            'tableProducts.required' => 'At least one item is required.',
            'tableProducts.min' => 'At least one item is required.',
        ];
    }
}
