<?php

namespace App\Http\Requests;

use App\Support\EmailNormalizer;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;

trait PartnerAccountRules
{
    protected function prepareForValidation(): void
    {
        $fields = ['email', 'official_email', 'second_contact_email'];
        $merge = [];

        foreach ($fields as $field) {
            if ($this->exists($field)) {
                $merge[$field] = EmailNormalizer::normalize($this->input($field));
            }
        }

        if ($merge !== []) {
            $this->merge($merge);
        }
    }

    protected function accountRules(?int $ignoreUserId = null): array
    {
        $email = ['required', 'email', 'max:255', 'lowercase', Rule::unique('users', 'email')->ignore($ignoreUserId)];
        $password = $ignoreUserId
            ? ['nullable', 'confirmed', Password::defaults()]
            : ['required', 'confirmed', Password::defaults()];

        return [
            'applicant_name' => ['required', 'string', 'max:255'],
            'designation' => ['nullable', 'string', 'max:255'],
            'building' => ['nullable', 'string', 'max:255'],
            'street' => ['nullable', 'string', 'max:255'],
            'city' => ['nullable', 'string', 'max:255'],
            'state' => ['nullable', 'string', 'max:255'],
            'postal_code' => ['nullable', 'string', 'max:50'],
            'country' => ['nullable', 'string', 'max:255'],
            'email' => $email,
            'phone' => ['nullable', 'string', 'max:50'],
            'password' => $password,
            'photo' => ['nullable', 'image', 'max:2048'],
            'id_proof' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:4096'],
        ];
    }

    protected function officialRules(): array
    {
        return [
            'institute_name' => ['nullable', 'string', 'max:255'],
            'firm_type' => ['nullable', 'string', 'max:255'],
            'official_building' => ['nullable', 'string', 'max:255'],
            'official_street' => ['nullable', 'string', 'max:255'],
            'official_city' => ['nullable', 'string', 'max:255'],
            'official_state' => ['nullable', 'string', 'max:255'],
            'official_postal_code' => ['nullable', 'string', 'max:50'],
            'official_country' => ['nullable', 'string', 'max:255'],
            'official_email' => ['nullable', 'email', 'max:255', 'lowercase'],
            'official_phone' => ['nullable', 'string', 'max:50'],
            'operational_area' => ['nullable', 'string', 'max:255'],
            'experience' => ['nullable', 'string', 'max:255'],
            'second_contact_name' => ['nullable', 'string', 'max:255'],
            'second_contact_email' => ['nullable', 'email', 'max:255', 'lowercase'],
            'second_contact_phone' => ['nullable', 'string', 'max:50'],
        ];
    }
}
