<?php

namespace App\Http\Requests\Main;

use App\Models\Newsletter;
use App\Rules\Phone;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class NewsletterSubscribeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'email_or_phone' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
                        $validator = validator(
                            ['email_or_phone' => $value],
                            ['email_or_phone' => ['email', 'lowercase', 'max:255', Rule::unique(Newsletter::class, 'email')]]
                        );
                        if ($validator->fails()) {
                            $fail($validator->errors()->first('email_or_phone'));
                        }
                    } else {
                        $validator = validator(
                            ['email_or_phone' => $value],
                            ['email_or_phone' => [new Phone, Rule::unique(Newsletter::class, 'phone')]]
                        );
                        if ($validator->fails()) {
                            $fail('validation.email_or_phone_invalid')->translate();
                        }
                    }
                },
            ],
        ];
    }
}
