<?php
/**
 * Plugin Name: WP Mail Logger Pro
 * Version: 1.5.0
 * Requires at least: 5.0
 * Requires PHP: 8.1
 * Plugin URI: https://www.wpmail.nl/
 * Description: Catches every mail sent with the <code>wp_mail()</code> function and saves it to the database. This plugin also allows you to set up an <strong>SMTP connection</strong>
 * Author: RTM Business
 * Author URI: https://www.wpmail.nl/
 * Text Domain: rtm-mail
 */

// When the file is called directly exit the code
use RtmMail\CustomMailer;

if (!defined('ABSPATH')) {
    exit;
}

if (!function_exists('get_plugin_data')) {
    require_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

// Define the plugin path when it isn't     defined yet
if (!defined('RTM_MAIL_PLUGIN_PATH')) {
    define('RTM_MAIL_PLUGIN_PATH', plugin_dir_path(__FILE__));
}

// Define the plugin path when it isn't     defined yet
if (!defined('RTM_MAIL_PLUGIN_URL')) {
    define('RTM_MAIL_PLUGIN_URL', plugin_dir_url(__FILE__));
}

// Define the plugin version (Don't change this, it's needed for the migration check)
if (!defined('RTM_MAIL_VERSION')) {
    $plugin_data = get_plugin_data(__FILE__);
    define('RTM_MAIL_VERSION', $plugin_data['Version']);
}

// Define the plugin database table prefix
if (!defined('RTM_MAIL_TABLE_PREFIX')) {
    define('RTM_MAIL_TABLE_PREFIX', $GLOBALS['wpdb']->prefix . 'rtm_mail_');
}

// Define the website
if (!defined('RTM_MAIL_PRO_SITE')) {
    define('RTM_MAIL_PRO_SITE', 'https://wpmail.nl/');
}

// Require the autoloader for prefixed namespaces
require_once RTM_MAIL_PLUGIN_PATH . 'vendor/autoload.php';
require_once RTM_MAIL_PLUGIN_PATH . 'vendor-prefixed/autoload.php';

/**
 * Add `getallheaders` function for nginx servers
 */
if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        if (!is_array($_SERVER)) {
            return [];
        }
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
                $headers[$key] = $value;
            }
        }
        return $headers;
    }
}

// Load the core class
$core = new RtmMail\Core();
// register activation and deactivation hook
register_activation_hook(__FILE__, [$core, 'activate']);
register_deactivation_hook(__FILE__, [$core, 'deactivate']);

add_filter('pre_wp_mail', 'use_custom_mailer', 10, 2);

function use_custom_mailer($null, $atts) {
    if (!class_exists('RtmMail\\CustomMailer')) {
        return $null;
    }
    $to = $atts['to'];
    $subject = $atts['subject'];
    $message = $atts['message'];
    $headers = isset($atts['headers']) ? $atts['headers'] : '';
    $attachments = isset($atts['attachments']) ? $atts['attachments'] : [];

    $result = CustomMailer::send($to, $subject, $message, $headers, $attachments);

    return $result;
}
