<?php

namespace GriffinForms\Includes\Mailer;

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

class Format extends \GriffinForms\Format
{
    protected $settings;
    protected $subject;
    protected $content;
    protected $recipient;
    protected $mail_options = [];
    protected $log_item_type = 'form';
    protected $log_item_id = 0;
    protected $submission_id = 0;

    protected function setSettings()
    {
        $this->settings = \GriffinForms\Settings::getInstance();
    }

    protected function setMailOptions()
    {
        $options = $this->settings->getOptionsByGroup('mail');
        if (!is_array($options)) {
            $options = [];
        }

        // Hydrate commonly used mail settings if the group query missed them (legacy installs).
        $fallback_keys = [
            'sender_name',
            'sender_email',
            'custom_header',
            'custom_footer',
            'email_headers',
            'smtp_host',
            'smtp_port',
            'smtp_encryption',
            'smtp_username',
            'smtp_password',
            'sendgrid_api_key',
            'sendgrid_from_email',
            'sendgrid_from_name',
            'sendgrid_reply_to_email',
        ];

        foreach ($fallback_keys as $key) {
            if (!array_key_exists($key, $options)) {
                $options[$key] = $this->settings->getOption($key, '');
            }
        }

        if (!is_array($options['email_headers'])) {
            $options['email_headers'] = [];
        }

        if (empty($options['sender_email'])) {
            $options['sender_email'] = get_bloginfo('admin_email');
        }

        if (empty($options['sender_name'])) {
            $options['sender_name'] = get_bloginfo('name');
        }

        $registry = MailerRegistry::getInstance();
        $active_provider = $registry->getActiveProviderId();
        $options['mailing_system'] = $active_provider ?: 'server_mail';

        $this->mail_options = $options;
    }

    /**
     * Set logging context so downstream logs can include correct item references.
     */
    public function setLogContext(string $item_type, int $item_id): void
    {
        $item_type = trim($item_type);
        if ($item_type !== '') {
            $this->log_item_type = $item_type;
        }

        $this->log_item_id = max(0, $item_id);
    }

    /**
     * Track associated submission for logging context.
     */
    public function setSubmissionId(int $submission_id = 0): void
    {
        $this->submission_id = max(0, $submission_id);
    }

    /**
     * Build the log category for the active mail provider.
     */
    protected function getLogCategory(): string
    {
        $provider = $this->mail_options['mailing_system'] ?? 'server_mail';
        return sprintf('Mail Integration (%s)', $provider);
    }

    /**
     * Return anonymized descriptor for the current recipient.
     */
    protected function getRecipientDescriptor(): string
    {
        if (empty($this->recipient)) {
            return __('recipient not set', 'griffinforms-form-builder');
        }

        $hash = substr(hash('sha256', strtolower(trim((string) $this->recipient))), 0, 10);
        return sprintf(__('recipient #%s', 'griffinforms-form-builder'), $hash);
    }

    public function setEmailSubject($subject)
    {
        $this->subject = sanitize_text_field($subject);
    }

    public function setEmailContent($content)
    {
        $this->content = wp_kses_post($content);;
    }

    public function setEmailRecipient($recipient)
    {
        $this->recipient = sanitize_email($recipient);
    }

    public function sendMail()
    {

    }

    public function __construct()
    {
        $this->setAll();
    }
}
