<?php

namespace App\Http\Requests\Admin;

use App\Rules\ValidPhoneNumber;
use App\Rules\ValidPostcode;
use Illuminate\Foundation\Http\FormRequest;

class ClientUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $client = $this->route('client');

        return $this->user()->can('update', $client);
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $clientId = $this->route('client')->id ?? null;

        $optionalFields = setting('optional_client_profile_fields', []);

        // String ise array'e çevir
        if (is_string($optionalFields)) {
            $optionalFields = json_decode($optionalFields, true) ?? [];
        }

        if (!is_array($optionalFields)) {
            $optionalFields = [];
        }

        $isOptional = function ($field) use ($optionalFields) {
            return in_array($field, $optionalFields);
        };

        $rules = [
            'type' => 'required|in:individual,company',
            'first_name' => ($isOptional('firstname') ? 'nullable' : 'required').'|string|max:255',
            'last_name' => 'required_if:type,individual|nullable|string|max:255',
            'company_name' => 'required_if:type,company|nullable|string|max:255',
            'email' => 'required|email|unique:clients,email,'.$clientId,
            'phone' => [$isOptional('phone') ? 'nullable' : 'required', 'string', 'max:20', new ValidPhoneNumber],
            'password' => ['nullable', 'confirmed', ...\App\Services\Auth\PasswordPolicy::rules()],
            'language_id' => 'required|exists:languages,id',
            'group_id' => 'nullable|exists:client_groups,id',
            'country_id' => ($isOptional('country') ? 'nullable' : 'required').'|exists:countries,id',
            // PRC-470: always nullable to match ClientStoreRequest (create
            // never requires city). A client created with city_id=NULL must
            // remain editable; config-based `required` here silently blocked it.
            'city_id' => 'nullable|exists:cities,id',
            'currency_id' => 'required|exists:currencies,id',
            'address' => ($isOptional('address') ? 'nullable' : 'required').'|string',
            'postcode' => [$isOptional('postcode') ? 'nullable' : 'required', 'string', 'max:20', new ValidPostcode],
            'state' => ($isOptional('state') ? 'nullable' : 'required').'|string|max:255',
            'payment_method' => 'nullable|string|max:50',
            'billing_contact' => 'nullable|string',
            'notes' => 'nullable|string',
            'late_fee_override' => 'nullable|numeric|min:0',
            // Boolean alanlar
            'late_fees' => 'boolean',
            'separate_invoices' => 'boolean',
            'overdue_notices' => 'boolean',
            'disable_cc_processing' => 'boolean',
            'allow_sso' => 'boolean',
            'tax_exempt' => ['nullable','in:0,1,true,false'],
            'marketing_emails' => 'boolean',
            'general_emails' => 'boolean',
            'invoice_emails' => 'boolean',
            'support_emails' => 'boolean',
            'product_emails' => 'boolean',
            'domain_emails' => 'boolean',
            'affiliate_emails' => 'boolean',
        ];

        // Custom field validation
        $customFields = \App\Models\ClientCustomField::all();
        foreach ($customFields as $field) {
            $fieldRules = [];

            if ($field->is_required) {
                $fieldRules[] = 'required';
            } else {
                $fieldRules[] = 'nullable';
            }

            // Type-based validation
            if ($field->type === 'input') {
                $fieldRules[] = 'string';
                $fieldRules[] = 'max:255';
            } elseif ($field->type === 'textbox') {
                $fieldRules[] = 'string';
            } elseif ($field->type === 'checkboxes') {
                $fieldRules[] = 'array';
            }

            $rules['custom_fields.'.$field->id] = implode('|', $fieldRules);
        }

        return $rules;
    }

    /**
     * Get custom error messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'type.required' => __('admin/clients.validation_type_required'),
            'first_name.required' => __('admin/clients.validation_first_name_required'),
            'last_name.required_if' => __('admin/clients.validation_last_name_required_for_individual'),
            'company_name.required_if' => __('admin/clients.validation_company_name_required_for_company'),
            'email.required' => __('admin/clients.validation_email_required'),
            'email.email' => __('admin/clients.validation_email_format'),
            'email.unique' => __('admin/clients.validation_email_unique'),
            'password.min' => __('admin/clients.validation_password_min'),
            'password.confirmed' => __('admin/clients.validation_password_confirmed'),
            'language_id.required' => __('admin/clients.validation_language_required'),
            'country_id.required' => __('admin/clients.validation_country_required'),
            'currency_id.required' => __('admin/clients.validation_currency_required'),
        ];
    }
}
