<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class ReplyToMessageRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'reply.to' => ['required', 'email:rfc', 'max:180'],
            'reply.cc' => ['nullable', 'email:rfc', 'max:180'],
            'reply.subject' => ['required', 'string', 'max:180'],
            'reply.content' => ['required', 'string', 'max:10000'],
            'reply.signature' => ['nullable', 'string', 'max:1000'],
            'send' => ['nullable', 'boolean'],
        ];
    }

    public function replyData(): array
    {
        $reply = $this->validated('reply');

        return [
            'to_email' => $reply['to'],
            'cc_email' => $reply['cc'] ?? null,
            'subject' => $reply['subject'],
            'body' => $this->sanitizeHtml($reply['content']),
            'signature' => $reply['signature'] ?? null,
        ];
    }

    private function sanitizeHtml(string $html): string
    {
        $html = preg_replace('/<\s*(script|iframe|object|embed)[^>]*>.*?<\s*\/\s*\1\s*>/is', '', $html) ?? '';
        $html = preg_replace('/\son[a-z]+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html) ?? '';
        $html = preg_replace('/javascript\s*:/i', '', $html) ?? '';

        return strip_tags($html, '<p><br><strong><b><em><i><u><ul><ol><li><a><blockquote><h3>');
    }
}
