<?php
/**
 * EmailTransport — configures WordPress PHPMailer based on TitanCart email settings.
 *
 * Hooks into `phpmailer_init` to apply SMTP / Sendmail configuration
 * from Settings → E-mails. Without this, wp_mail() defaults to PHP's
 * built-in mail() function regardless of what's saved in the admin.
 *
 * Also sets the From name/address from Company settings when available.
 *
 * @package TitanCart\Services
 */

namespace TitanCart\Services;

defined( 'ABSPATH' ) || exit;

class EmailTransport {

    /** @var bool Prevents double-hooking. */
    private static bool $booted = false;

    /**
     * Register the phpmailer_init hook. Called once during plugin boot.
     */
    public static function init(): void {
        if ( self::$booted ) {
            return;
        }
        self::$booted = true;

        add_action( 'phpmailer_init', [ self::class, 'configure' ], 10, 1 );
    }

    /**
     * Configure PHPMailer instance based on tc_settings → emails section.
     *
     * @param \PHPMailer\PHPMailer\PHPMailer $phpmailer
     */
    public static function configure( $phpmailer ): void {
        $method = SettingsService::get( 'emails', 'email_method', 'php_mail' );

        // ── From name / address ──────────────────────────────────────────────
        // Mirror Modules\Orders\Mailer::__construct so that EVERY wp_mail() —
        // including WordPress core paths that pass NO From header (admin
        // email-change verification, password resets, comment notices) — goes
        // out with a deliverable sender. Without the admin_email fallback below,
        // those core sends keep WordPress's default `wordpress@<domain>` From,
        // which strict SMTP providers (e.g. IONOS) reject as an unauthorized
        // sender — so they silently bounce even though the SMTP transport is
        // configured correctly and TitanCart's own mail (which sets its own
        // From header) delivers fine.
        $company_name = SettingsService::get( 'company', 'company_name', '' );
        $order_email  = SettingsService::get( 'company', 'email_order_dept', '' );

        $from_name  = $company_name !== '' ? $company_name : get_bloginfo( 'name' );
        $from_email = ( $order_email !== '' && is_email( $order_email ) )
            ? $order_email
            : get_option( 'admin_email' );

        if ( $from_name !== '' ) {
            $phpmailer->FromName = $from_name;
        }
        if ( is_string( $from_email ) && is_email( $from_email ) ) {
            $phpmailer->From   = $from_email;
            $phpmailer->Sender = $from_email;
        }

        // ── Transport method ─────────────────────────────────────────────────
        if ( $method === 'smtp' ) {
            $phpmailer->isSMTP();

            $host = SettingsService::get( 'emails', 'smtp_host', '' );
            $port = 587; // sensible default

            // Support host:port syntax  (e.g. "smtp.example.com:465").
            if ( str_contains( $host, ':' ) ) {
                [ $host, $port_str ] = explode( ':', $host, 2 );
                $port = (int) $port_str;
            }

            $phpmailer->Host = $host;
            $phpmailer->Port = $port;

            $encryption = SettingsService::get( 'emails', 'smtp_encryption', 'none' );
            if ( $encryption === 'ssl' ) {
                $phpmailer->SMTPSecure = 'ssl';
                if ( $port === 587 ) {
                    $phpmailer->Port = 465; // auto-correct common misconfiguration
                }
            } elseif ( $encryption === 'tls' ) {
                $phpmailer->SMTPSecure = 'tls';
            } else {
                $phpmailer->SMTPSecure = '';
                $phpmailer->SMTPAutoTLS = false;
            }

            $use_auth = SettingsService::bool( 'emails', 'smtp_auth', false );
            if ( $use_auth ) {
                $phpmailer->SMTPAuth = true;
                $phpmailer->Username = SettingsService::get( 'emails', 'smtp_username', '' );
                $phpmailer->Password = SettingsService::get( 'emails', 'smtp_password', '' );
            } else {
                $phpmailer->SMTPAuth = false;
            }

        } elseif ( $method === 'sendmail' ) {
            $phpmailer->isSendmail();
            $path = SettingsService::get( 'emails', 'sendmail_path', '/usr/sbin/sendmail' );
            if ( $path !== '' ) {
                $phpmailer->Sendmail = $path;
            }
        }
        // 'php_mail' (default) — no configuration needed, PHPMailer uses mail().
    }
}
