<?php

namespace GriffinForms\Includes\Mailer;

class ServerMail extends \GriffinForms\Includes\Mailer\Format
{
    public function sendEmail()
    {
        if (empty($this->recipient)) {
            return new \WP_Error('invalid_recipient', __('No recipient specified.', 'griffinforms-form-builder'));
        }

        // Set a valid "From" email if not already provided
        $default_from = $this->mail_options['sender_email'];
        $from_header = 'From: ' . $this->mail_options['sender_name'] . ' <' . $default_from . '>';
        
        // Prepare the headers array
        $headers = [];
        
        // Ensure the "From" header is set
        if (!array_filter($this->mail_options['email_headers'], function($header) { return strpos($header, 'From:') === 0; })) {
            $headers[] = $from_header;
        }

        // Process additional headers like Reply-To, CC, and BCC
        if (!empty($this->mail_options['email_headers']) && is_array($this->mail_options['email_headers'])) {
            foreach ($this->mail_options['email_headers'] as $header) {
                $header_parts = explode(':', $header, 2);
                if (count($header_parts) === 2) {
                    $header_name = trim($header_parts[0]);
                    $header_value = trim($header_parts[1]);

                    // Handle reserved headers
                    if (strcasecmp($header_name, 'Reply-To') === 0) {
                        $headers[] = 'Reply-To: ' . $header_value;
                    } elseif (strcasecmp($header_name, 'CC') === 0) {
                        $headers[] = 'CC: ' . $header_value;
                    } elseif (strcasecmp($header_name, 'BCC') === 0) {
                        $headers[] = 'BCC: ' . $header_value;
                    } else {
                        // Add other non-reserved headers
                        $headers[] = $header_name . ': ' . $header_value;
                    }
                }
            }
        }

        add_filter('wp_mail_content_type', function() { return 'text/html'; });

        $sent = wp_mail($this->recipient, $this->subject, $this->content, $headers);

        remove_filter('wp_mail_content_type', function() { return 'text/html'; });

        if ($sent) {
            $this->logSuccess();
            return true;
        } else {
            // Translators: %s is the recipient email address.
            $this->logError(__('ServerMail email failed to send', 'griffinforms-form-builder'));
            return new \WP_Error('email_failed', __('The email could not be sent using WordPress mail system.', 'griffinforms-form-builder'));
        }
    }

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

        $this->log->add(
            'info',
            $this->log_item_type,
            $this->log_item_id,
            get_current_user_id(),
            sprintf(__('ServerMail email successfully sent (%s)', 'griffinforms-form-builder'), $this->getRecipientDescriptor()),
            $this->getLogCategory()
        );
    }

    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->getRecipientDescriptor() . ')',
            $this->getLogCategory()
        );
    }
}
