<?php
/**
 * Global SMTP & Sender Override Engine.
 * Intercepts all wp_mail() calls to authenticate via Google Workspace, SendGrid, SES, Mailgun, or Custom SMTP.
 */

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

class PexEmail_SMTP {

    public function init() {
        add_action( 'phpmailer_init', [ $this, 'configure_smtp' ], 999 );
        add_filter( 'wp_mail_from', [ $this, 'override_from_email' ], 999 );
        add_filter( 'wp_mail_from_name', [ $this, 'override_from_name' ], 999 );
    }

    public function configure_smtp( $phpmailer ) {
        $settings = get_option( 'pexemail_settings', [] );

        if ( empty( $settings['smtp_enabled'] ) || $settings['smtp_enabled'] !== 'yes' ) {
            return;
        }

        if ( empty( $settings['smtp_host'] ) ) {
            return;
        }

        $phpmailer->isSMTP();

        $phpmailer->Host       = sanitize_text_field( $settings['smtp_host'] );
        $phpmailer->SMTPAuth   = true;
        
        $smtp_user             = ! empty( $settings['smtp_username'] ) ? $settings['smtp_username'] : ( ! empty( $settings['sender_email'] ) ? $settings['sender_email'] : '' );
        $phpmailer->Username   = sanitize_text_field( $smtp_user );
        
        $phpmailer->Password   = isset( $settings['smtp_password'] ) ? $settings['smtp_password'] : '';
        
        $phpmailer->Port       = ! empty( $settings['smtp_port'] ) ? intval( $settings['smtp_port'] ) : 587;

        $encryption            = ! empty( $settings['smtp_secure'] ) ? strtolower( sanitize_text_field( $settings['smtp_secure'] ) ) : 'tls';
        
        if ( $encryption === 'ssl' ) {
            $phpmailer->SMTPSecure = 'ssl'; 
        } elseif ( $encryption === 'tls' ) {
            $phpmailer->SMTPSecure = 'tls'; 
        } else {
            $phpmailer->SMTPSecure = '';    
            $phpmailer->SMTPAutoTLS = false;
        }

        if ( ! empty( $settings['sender_email'] ) && is_email( $settings['sender_email'] ) ) {
            $phpmailer->From = sanitize_email( $settings['sender_email'] );
        }
        if ( ! empty( $settings['sender_name'] ) ) {
            $phpmailer->FromName = sanitize_text_field( $settings['sender_name'] );
        }
    }

    public function override_from_email( $original_email ) {
        $settings = get_option( 'pexemail_settings', [] );
        if ( ! empty( $settings['sender_email'] ) && is_email( $settings['sender_email'] ) ) {
            return sanitize_email( $settings['sender_email'] );
        }
        return $original_email;
    }

    public function override_from_name( $original_name ) {
        $settings = get_option( 'pexemail_settings', [] );
        if ( ! empty( $settings['sender_name'] ) ) {
            return sanitize_text_field( $settings['sender_name'] );
        }
        return $original_name;
    }
}