<?php

namespace App\Traits\Product;

use Illuminate\Http\Request;

trait ValidatesProductData
{
    protected function validateProductRequest(Request $request, bool $isUpdate = false)
    {
        $rules = [
            'title'          => 'required|string|max:255',
            'category_id'    => 'required|exists:categories,id',
            'subcategory_id' => 'nullable|exists:categories,id',
            'description'    => 'nullable|string',
            'currency_code'  => 'required|string|exists:currencies,code',
            'price'          => 'required|numeric|min:0',
            'stock'          => 'required|integer|min:0',
            'moq'            => 'required|integer|min:1',
            'shipping_time'  => 'required|string|max:100',
            'delivery_via'   => 'nullable|string|max:255',
            'refund_policy'  => 'nullable|string|max:1000',
            'customization_options' => 'nullable|array',
            'specifications' => 'nullable|array',
            
            // --- NEW: DYNAMIC VARIATIONS VALIDATION ---
            'variations' => 'nullable|array',
            'variations.*.name' => 'required_with:variations|string|max:100',
            'variations.*.options' => 'required_with:variations|array',
            'variations.*.options.*.value' => 'required_with:variations.*.options|string|max:100',
            'variations.*.options.*.additional_price' => 'nullable|numeric|min:0',
            // STRICT 100KB LIMIT for variation images
            'variations.*.options.*.image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:100', 
            'variations.*.options.*.existing_image' => 'nullable|string',
            // ------------------------------------------

            'coupon_code'                   => 'nullable|string|max:50',
            'discount_percentage'           => 'nullable|numeric|min:0|max:100',
            'max_discount_percentage'       => 'nullable|numeric|min:0',
            'min_order_amount_for_discount' => 'nullable|numeric|min:0',
            'is_free_shipping'              => 'boolean',
            'shipping_charge'               => 'nullable|numeric|min:0',
            'shipping_charge_type'          => 'required|in:flat_rate,per_item',
        ];

        if ($isUpdate) {
            $rules['existing_images'] = 'nullable|array';
            $rules['existing_images.*'] = 'integer|exists:product_images,id';
            $rules['images'] = 'nullable|array|max:10';
            $rules['images.*'] = 'image|mimes:jpeg,png,jpg,webp|max:5120';
        } else {
            $rules['images'] = 'required|array|min:1|max:10';
            $rules['images.*'] = 'image|mimes:jpeg,png,jpg,webp|max:5120';
        }

        return $request->validate($rules);
    }
}