<?php

namespace GriffinForms\Includes\Mailer;

use SendGrid;
use SendGrid\Mail\Mail;

class SendGridMail extends \GriffinForms\Includes\Mailer\Format
{
    // Function to send email via SendGrid API
    public function sendEmail()
    {
        $mail = new Mail();
        $mail->setFrom($this->mail_options['sender_email'], $this->mail_options['sender_name']);
        $mail->setSubject($this->subject);
        $mail->addTo($this->recipient);
        $mail->addContent("text/html", $this->content);

        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 with the appropriate SendGrid methods
                    if (strcasecmp($header_name, 'Reply-To') === 0) {
                        $mail->setReplyTo($header_value);
                    } elseif (strcasecmp($header_name, 'CC') === 0) {
                        $mail->addCc($header_value);
                    } elseif (strcasecmp($header_name, 'BCC') === 0) {
                        $mail->addBcc($header_value);
                    } else {
                        // Add other non-reserved headers
                        $mail->addHeader($header_name, $header_value);
                    }
                }
            }
        }

        // Initialize the SendGrid API client
        $sendgrid = new SendGrid($this->mail_options['sendgrid_api_key']);

        try {
            // Send the email
            $response = $sendgrid->send($mail);

            // Check if the response indicates success (status code 202)
            if ($response->statusCode() == 202) {
                if (isset($this->log) && is_object($this->log)) {
                    $this->log->add(
                        'info',
                        $this->log_item_type,
                        $this->log_item_id,
                        get_current_user_id(),
                        sprintf(__('SendGrid email successfully sent (%s)', 'griffinforms-form-builder'), $this->getRecipientDescriptor()),
                        $this->getLogCategory()
                    );
                }
                return true;
            } else {
                if (isset($this->log) && is_object($this->log)) {
                    $this->log->add(
                        'error',
                        $this->log_item_type,
                        $this->log_item_id,
                        get_current_user_id(),
                        sprintf(__('SendGrid email failed with status code: %s', 'griffinforms-form-builder'), $response->statusCode()),
                        $this->getLogCategory()
                    );
                }
                return new \WP_Error('email_failed', __('SendGrid email could not be sent. Status Code: ', 'griffinforms-form-builder') . $response->statusCode());
            }
        } catch (\Exception $e) {
            if (isset($this->log) && is_object($this->log)) {
                $this->log->add(
                    'error',
                    $this->log_item_type,
                    $this->log_item_id,
                    get_current_user_id(),
                    sprintf(__('SendGrid exception: %s', 'griffinforms-form-builder'), $e->getMessage()),
                    $this->getLogCategory()
                );
            }
            // Log any exceptions that occur during the API request
            return new \WP_Error('email_failed', __('SendGrid error: ', 'griffinforms-form-builder') . $e->getMessage());
        }
    }
}
