<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'customer_id' => ['required', 'exists:customers,id'],
            'invoice_date' => ['required', 'date_format:Y-m-d'],
            'local_invoice_no' => ['nullable', 'string', 'max:255'],
            'scenario_id' => ['nullable', 'string', 'regex:/^SN0\d{2}$/'],
            'notes' => ['nullable', 'string', 'max:2000'],

            'items' => ['required', 'array', 'min:1'],

            // Either item_id (pulls defaults from Item master) or a fully
            // manual line is accepted — manual fields override item defaults
            // when both are present.
            'items.*.item_id' => ['nullable', 'exists:items,id'],
            'items.*.hs_code' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.product_description' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.rate' => ['required_without:items.*.item_id', 'nullable'],
            'items.*.uom' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.quantity' => ['required', 'numeric'],
            'items.*.value_sales_excluding_st' => ['nullable', 'numeric', 'min:0'],
            'items.*.fixed_notified_value_or_retail_price' => ['nullable', 'numeric', 'min:0'],
            'items.*.sales_tax_applicable' => ['nullable', 'numeric', 'min:0'],
            'items.*.sales_tax_withheld_at_source' => ['nullable', 'numeric', 'min:0'],
            'items.*.extra_tax' => ['nullable', 'numeric', 'min:0'],
            'items.*.further_tax' => ['nullable', 'numeric', 'min:0'],
            'items.*.sro_schedule_no' => ['nullable', 'string'],
            'items.*.fed_payable' => ['nullable', 'numeric', 'min:0'],
            'items.*.discount' => ['nullable', 'numeric', 'min:0'],
            'items.*.discount_type' => ['nullable', 'string', 'in:fixed,percent'],
            'items.*.discount_value' => ['nullable', 'numeric', 'min:0'],
            'items.*.sale_type' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.sro_item_serial_no' => ['nullable', 'string'],

            // Auto-sync immediately after saving as draft, instead of a separate call.
            'sync_immediately' => ['boolean'],
        ];
    }
}
