<?php

namespace GriffinForms\Includes\Mailer;

class MailHandler extends \GriffinForms\Includes\Mailer\Format
{
    public function sendMail()
    {
        // Ensure logs are tied to the submission when available.
        if ($this->submission_id > 0) {
            $this->setLogContext('submission', $this->submission_id);
        }

        $mailer = $this->getMailer($this->mail_options['mailing_system']);
        if (is_wp_error($mailer)) {
            return $mailer;
        }

        $mailer->setEmailSubject($this->subject);

        $content  = $this->mail_options['custom_header'] ?? '';
        $content .= $this->content;
        $content .= $this->mail_options['custom_footer'] ?? '';

        $mailer->setEmailContent($content);
        $mailer->setEmailRecipient($this->recipient);

        $result = $mailer->sendEmail();
        if (is_wp_error($result)) {
            $this->logError($result->get_error_message());
        }

        return $result;
    }

    private function getMailer($mailing_system)
    {
        $mailer = null;
        switch ($mailing_system) {
            case 'server_mail':
                $mailer = new ServerMail();
                break;
            case 'custom_smtp':
                $mailer = new SmtpMail();
                break;
            case 'sendgrid':
                $mailer = new SendGridMail();
                break;
            case 'mailgun':
                $mailer = new \GriffinForms\Includes\Mailer\MailgunMail();
                break;
            default:
                $this->logError(__('Invalid mailing system selected.', 'griffinforms-form-builder'));
                return new \WP_Error('invalid_mailing_system', __('Invalid mailing system selected.', 'griffinforms-form-builder'));
        }

        // Propagate logging context and submission id to the underlying mailer.
        if ($this->submission_id > 0) {
            $mailer->setSubmissionId($this->submission_id);
            $mailer->setLogContext('submission', $this->submission_id);
        } else {
            $mailer->setLogContext($this->log_item_type, $this->log_item_id);
        }

        return $mailer;
    }

    private function logError($message)
    {
        if (!isset($this->log) || !is_object($this->log)) {
            return;
        }

        $this->log->add(
            'error',
            $this->log_item_type,
            $this->log_item_id,
            get_current_user_id(),
            $message,
            $this->getLogCategory()
        );
    }
}
