<?php

namespace App\Http\Requests;

use App\Models\OrganizationCompany;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                Rule::unique(User::class)->ignore($this->user()->id),
            ],
            'phone' => ['nullable', 'string', 'max:50'],
            'job_title' => ['nullable', 'string', 'max:255'],
            'manager_id' => [
                'nullable',
                'integer',
                'exists:users,id',
                Rule::notIn([(int) $this->user()->id]),
            ],
            'organization_company_id' => [
                'nullable',
                'integer',
                'exists:organization_companies,id',
                function (string $attribute, mixed $value, \Closure $fail): void {
                    if ($value === null || $value === '') {
                        return;
                    }

                    $hasChildCompanies = OrganizationCompany::query()
                        ->whereNotNull('parent_id')
                        ->exists();

                    if (! $hasChildCompanies) {
                        $fail('Company selection is disabled.');
                        return;
                    }

                    $isChild = OrganizationCompany::query()
                        ->whereKey((int) $value)
                        ->whereNotNull('parent_id')
                        ->exists();

                    if (! $isChild) {
                        $fail('Company selection is disabled.');
                    }
                },
            ],
            'birth_date' => ['nullable', 'date', 'before_or_equal:today'],
            'locale' => ['nullable', Rule::in(['ru', 'en'])],
            'profile_photo' => ['nullable', 'image', 'max:10240'],
            'remove_profile_photo' => ['nullable', 'boolean'],
            'profile_photo_zoom' => ['nullable', 'numeric', 'min:1', 'max:3'],
        ];
    }

    protected function prepareForValidation(): void
    {
        foreach (['profile_photo_zoom', 'phone', 'job_title', 'manager_id', 'organization_company_id', 'birth_date'] as $field) {
            if ($this->has($field) && trim((string) $this->input($field)) === '') {
                $this->merge([$field => null]);
            }
        }

        foreach (['phone', 'job_title'] as $field) {
            if ($this->filled($field)) {
                $this->merge([$field => trim((string) $this->input($field))]);
            }
        }
    }
}
