<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Email Router
 * 
 * The "Traffic Cop" that decides whether an email goes through:
 * 1. Brain #1: Local Engine (Transactional, Private)
 * 2. Brain #2: Marketing Engine (Bulk Provider / SMTP)
 * 
 * @package VMO_AI_Builder_Manager
 */

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

class VMO_Email_Router {
    
    private static $instance = null;
    private $local_mailer;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        require_once dirname(__FILE__) . '/class-vmo-local-mailer.php';
        
        $this->local_mailer = new VMO_Local_Mailer();
    }
    
    /**
     * Route and send an email based on its type
     * 
     * @param string $to Recipient email
     * @param string $subject Subject line
     * @param string $message Email body (HTML)
     * @param string $type 'transactional' or 'marketing'
     * @param array $args Additional arguments (headers, attachments, etc.)
     * @return array ['success' => bool, 'method' => string, 'message' => string]
     */
    public function send_email($to, $subject, $message, $type = 'transactional', $args = []) {
        $user_id = (is_array($args) && !empty($args['user_id'])) ? (int) $args['user_id'] : get_current_user_id();
        if ($user_id && function_exists('vmo_is_user_service_locked') && vmo_is_user_service_locked($user_id)) {
            return [
                'success' => false,
                'method' => 'blocked',
                'message' => 'Email service is paused until billing is resolved.',
                'code' => 'service_locked',
            ];
        }

        // Legacy cloud sender has been removed. All email sending routes through the local/SMTP mailer.
        // The caller may still pass $type ('transactional'|'marketing') for storage/reporting purposes.
        return $this->send_via_local($to, $subject, $message, $args);
    }
    
    /**
     * Send via Brain #1: Local Engine (Local Host)
     */
    private function send_via_local($to, $subject, $message, $args) {
        $result = $this->local_mailer->send($to, $subject, $message, $args);

        $method = (!empty($args) && is_array($args) && !empty($args['smtp'])) ? 'smtp' : 'local_host';
        
        return [
            'success' => $result,
            'method' => $method,
            'message' => $result ? 'Sent via Local Host' : 'Failed Local Send'
        ];
    }
}
