<?php

namespace EasyLinkAutomations\Actions\Core;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that sends an email.
 */
final class SendEmailAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'core/send_email';
    }

    public static function getName(): string
    {
        return __('Send Email', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Send an email to specified recipients', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return '';
    }

    public static function getIcon(): string
    {
        return 'mail';
    }

    public static function getConfigFields(): array
    {
        return [
            'to' => [
                'label'            => 'To',
                'type'             => 'email',
                'supports_mapping' => true,
                'required'         => true,
                'placeholder'      => '{{author_email}} or email@example.com',
            ],
            'subject' => [
                'label'            => 'Subject',
                'type'             => 'text',
                'supports_mapping' => true,
                'required'         => true,
                'placeholder'      => 'New post: {{post_title}}',
            ],
            'body' => [
                'label'            => 'Body',
                'type'             => 'richtext',
                'supports_mapping' => true,
                'required'         => true,
            ],
            'from_name' => [
                'label'            => 'From Name',
                'type'             => 'text',
                'supports_mapping' => true,
                'default'          => '',
            ],
            'from_email' => [
                'label'            => 'From Email',
                'type'             => 'email',
                'supports_mapping' => true,
                'default'          => '',
            ],
            'reply_to' => [
                'label'            => 'Reply To',
                'type'             => 'email',
                'supports_mapping' => true,
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $missing = $this->validateRequired($config);
        if ($missing) {
            return [
                'success' => false,
                'message' => 'Missing required fields: ' . implode(', ', $missing),
            ];
        }

        $mapped  = $this->mapConfig($config, $triggerData);
        $to      = $mapped['to'];
        $subject = $mapped['subject'];
        $body    = $mapped['body'];

        $fromName  = (string) (($mapped['from_name'] ?? '') ?: get_bloginfo('name'));
        $fromEmail = sanitize_email((string) (($mapped['from_email'] ?? '') ?: get_option('admin_email')));
        $fromName  = str_replace(["\r", "\n"], '', $fromName);

        if (!$fromEmail || !is_email($fromEmail)) {
            return [
                'success' => false,
                'message' => 'From Email must be a valid email address',
            ];
        }

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            "From: {$fromName} <{$fromEmail}>",
        ];

        if (!empty($mapped['reply_to'])) {
            $replyTo = sanitize_email((string) $mapped['reply_to']);
            if (!$replyTo || !is_email($replyTo)) {
                return [
                    'success' => false,
                    'message' => 'Reply To must be a valid email address',
                ];
            }
            $headers[] = "Reply-To: {$replyTo}";
        }

        $sent = wp_mail($to, $subject, $body, $headers);

        return [
            'success' => $sent,
            'message' => $sent ? 'Email sent successfully' : 'Failed to send email',
            'data'    => [
                'to'      => $to,
                'subject' => $subject,
            ],
        ];
    }
}
