<?php

namespace App\Http\Requests\Products\Plan;

use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;

class PlanUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        if (auth()->user()->hasRole('administrator')) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $rules = [
            'name' => 'required',
            'description' => 'required',
            'billing_type' => 'required',
            'features' => 'required|string',
            'pricing_tiers.id.*' => 'nullable|numeric|min:0',
            'pricing_tiers.price.*' => 'required|numeric|min:0',
            'pricing_tiers.setup_fee.*' => 'nullable|numeric|min:0',
            'is_licensable' => 'boolean',
            'license_validity' => 'required_if:is_licensable,1|in:' . implode(',', getConstantValues('license_validity')),
            'license_validity_unit' => 'required_if:license_validity,' . getConstant('LICENSE_VALIDITY_EXPIRY') . '|in:' . implode(',', getConstantValues('license_validity_unit')),
            'license_validity_duration' => [
                'required_if:license_validity,' . getConstant('LICENSE_VALIDITY_EXPIRY'),
                'integer',
                'min:1'
            ],
        ];

        if ($this->billing_type == getConstant('BILLING_SUBSCRIPTION')) {
            $rules['pricing_tiers.tier_name.*'] = 'nullable|string';
            $rules['pricing_tiers.billing_cycle.*'] = 'required|numeric|min:1';
            $rules['pricing_tiers.billing_cycle_count.*'] = 'nullable|numeric|min:0';
            $rules['pricing_tiers.trial_available.*'] = 'nullable|numeric';
            $rules['pricing_tiers.trial_duration.*'] = 'nullable|numeric';
            $rules['pricing_tiers.trial_duration_unit.*'] = 'nullable|numeric';
            $rules['pricing_tiers.is_default'] = 'required|numeric';
        }

        return $rules;
    }
}
