<?php

namespace Daylight\Core\Modules\FormBuilder\Http\Requests;

use Closure;
use Illuminate\Foundation\Http\FormRequest;

class UpdateFormRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->can('update:pages');
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'recipient_email' => ['required', 'string', 'max:500', $this->commaEmailRule()],
            'cc' => ['nullable', 'string', 'max:500', $this->commaEmailRule()],
            'bcc' => ['nullable', 'string', 'max:500', $this->commaEmailRule()],
            'is_active' => ['boolean'],
            'fields_json' => ['required', 'string'],
            'success_type' => ['required', 'in:message,redirect'],
            'success_message' => ['nullable', 'string', 'max:1000'],
            'success_redirect_url' => ['nullable', 'required_if:success_type,redirect', 'url', 'max:500'],
            'auto_reply_enabled' => ['boolean'],
            'auto_reply_subject' => ['nullable', 'string', 'max:500'],
            'auto_reply_message' => ['nullable', 'string', 'max:2000'],
        ];
    }

    protected function commaEmailRule(): Closure
    {
        return function (string $attribute, mixed $value, Closure $fail): void {
            $emails = array_map('trim', explode(',', $value));

            foreach ($emails as $email) {
                if ($email !== '' && ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $fail(__('validation.email', ['attribute' => $attribute]));

                    return;
                }
            }
        };
    }
}
