<?php

namespace GriffinForms\Admin\Secure;

use GriffinForms\Includes\Integrations\Categories\Mailer as MailerRegistry;

class Mail extends \GriffinForms\Admin\Secure\Settings
{
    /**
     * Registry reference for validating selected providers.
     *
     * @var \GriffinForms\Includes\Integrations\Categories\Mailer
     */
    protected $mailer_registry;

    /**
     * Initialize registry dependency for Singleton bootstrapping.
     */
    protected function setMailerregistry()
    {
        $this->mailer_registry = MailerRegistry::getInstance();
    }

    // Secure Sender Name (applies to all systems)
    protected function secureSenderName($value)
    {
        $secured_value = sanitize_text_field($value);
        if (empty($secured_value)) {
            $this->errors['sender_name'] = $this->lang->getText('sender_name_required');
        }
        return $secured_value;
    }

    // Secure Sender Email (applies to all systems)
    protected function secureSenderEmail($value)
    {
        $secured_value = sanitize_email($value);
        if (empty($secured_value) || !is_email($secured_value)) {
            $this->errors['sender_email'] = $this->lang->getText('sender_email_invalid');
        }
        return $secured_value;
    }

    protected function secureMailingSystem($value)
    {
        $secured_value = sanitize_key($value);

        $allowed = array_map(
            static function ($option) {
                return $option['id'];
            },
            $this->mailer_registry->getProviderOptions()
        );

        if (!in_array($secured_value, $allowed, true)) {
            $this->errors['mailing_system'] = $this->lang->getText('invalid_mailing_system');
            return $secured_value;
        }

        if ($secured_value !== 'server_mail' && !$this->mailer_registry->providerIsConfigured($secured_value)) {
            $this->errors['mailing_system'] = $this->lang->getText('mailing_provider_not_configured');
        }

        $this->options_data['mailing_system'] = $secured_value;

        return $secured_value;
    }

    // Secure Server Mail fields
    protected function secureEmailHeaders($value)
    {
            $headers = explode("\n", $value);
            $sanitized_headers = array_map('sanitize_textarea_field', $headers);
            // Remove any empty elements (in case the user added extra newlines)
            return array_filter($sanitized_headers);
    }

    protected function secureCustomHeader($value)
    {
        return wp_kses_post($value);
    }

    protected function secureCustomFooter($value)
    {
        return wp_kses_post($value);
    }

    // Legacy provider fields are managed through the integrations modal now.
}
