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

/**
 * VMO Local Mailer (Brain #1)
 * 
 * Handles transactional and private emails using the user's local host.
 * Includes rate limiting to prevent host bans.
 * 
 * @package VMO_AI_Builder_Manager
 */

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

class VMO_Local_Mailer {
    
    private $hourly_limit = 50; // Safe default for shared hosting
    private $daily_limit = 500;
    
    public function __construct() {
        // Allow overriding limits via filters
        $this->hourly_limit = apply_filters('vmo_local_email_hourly_limit', 50);
        $this->daily_limit = apply_filters('vmo_local_email_daily_limit', 500);
    }
    
    /**
     * Send email using local wp_mail()
     */
    public function send($to, $subject, $message, $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)) {
            error_log("VMO Local Mailer: Blocked email to $to because user {$user_id} is service-locked.");
            return false;
        }
        
        if ($this->is_rate_limited()) {
            error_log("VMO Local Mailer: Rate limit exceeded. Email to $to queued or dropped.");
            return false; // In a full implementation, we would queue this.
        }
        
        $headers = isset($args['headers']) ? $args['headers'] : array('Content-Type: text/html; charset=UTF-8');
        $attachments = isset($args['attachments']) ? $args['attachments'] : array();

        // Respect explicit sender when available.
        $from_email = '';
        $from_name = '';
        if (is_array($args)) {
            $from_email = !empty($args['from_email']) ? sanitize_email((string) $args['from_email']) : '';
            $from_name = !empty($args['from_name']) ? sanitize_text_field((string) $args['from_name']) : '';
        }
        if ($from_email) {
            $from_header = $from_name ? sprintf('From: %s <%s>', $from_name, $from_email) : sprintf('From: %s', $from_email);
            $reply_header = sprintf('Reply-To: %s', $from_email);
            if (!is_array($headers)) {
                $headers = array((string) $headers);
            }
            $headers[] = $from_header;
            $headers[] = $reply_header;
        }

        // Optional SMTP override (best-effort) for sending as the selected account.
        $smtp = (is_array($args) && !empty($args['smtp']) && is_array($args['smtp'])) ? $args['smtp'] : null;
        $phpmailer_cb = null;
        if ($smtp && !empty($smtp['host']) && !empty($smtp['port']) && !empty($smtp['username']) && !empty($smtp['password'])) {
            $smtp_host = (string) $smtp['host'];
            $smtp_port = intval($smtp['port']);
            $smtp_user = (string) $smtp['username'];
            $smtp_pass = (string) $smtp['password'];
            $smtp_secure = !empty($smtp['secure']) ? (string) $smtp['secure'] : '';

            $phpmailer_cb = function($phpmailer) use ($smtp_host, $smtp_port, $smtp_user, $smtp_pass, $smtp_secure, $from_email, $from_name) {
                try {
                    $phpmailer->isSMTP();
                    $phpmailer->Host = $smtp_host;
                    $phpmailer->Port = $smtp_port;
                    $phpmailer->SMTPAuth = true;
                    $phpmailer->Username = $smtp_user;
                    $phpmailer->Password = $smtp_pass;
                    if ($smtp_secure === 'ssl' || $smtp_secure === 'tls') {
                        $phpmailer->SMTPSecure = $smtp_secure;
                    }
                    if ($from_email) {
                        $phpmailer->setFrom($from_email, $from_name ? $from_name : '', false);
                    }
                } catch (Throwable $e) {
                    // Best-effort. If SMTP config fails, wp_mail may still attempt default.
                }
            };
            add_action('phpmailer_init', $phpmailer_cb);
        }

        $charge_tokens = is_array($args) && !empty($args['charge_tokens']);
        if ($charge_tokens && function_exists('vmo_send_email_with_tokens')) {
            $sent = vmo_send_email_with_tokens($to, $subject, $message, $headers, $attachments);
        } else {
            $sent = wp_mail($to, $subject, $message, $headers, $attachments);
        }

        if ($phpmailer_cb) {
            remove_action('phpmailer_init', $phpmailer_cb);
        }
        
        if ($sent) {
            $this->log_send();
            $skip_storage = is_array($args) && !empty($args['skip_storage']);
            if (!$skip_storage) {
                $this->save_to_outbox($to, $subject, $message, $args);
            }
        } else {
            error_log("VMO Local Mailer: wp_mail failed for $to");
        }
        
        return $sent;
    }
    
    /**
     * Check if we have hit the sending limits
     */
    private function is_rate_limited() {
        $hour_count = get_transient('vmo_local_email_count_hour') ?: 0;
        $day_count = get_transient('vmo_local_email_count_day') ?: 0;
        
        if ($hour_count >= $this->hourly_limit) return true;
        if ($day_count >= $this->daily_limit) return true;
        
        return false;
    }
    
    /**
     * Log a successful send to update counters
     */
    private function log_send() {
        $hour_count = (get_transient('vmo_local_email_count_hour') ?: 0) + 1;
        $day_count = (get_transient('vmo_local_email_count_day') ?: 0) + 1;
        
        set_transient('vmo_local_email_count_hour', $hour_count, HOUR_IN_SECONDS);
        set_transient('vmo_local_email_count_day', $day_count, DAY_IN_SECONDS);
    }
    
    /**
     * Save to a local "Outbox" so the user can see what was sent
     */
    private function save_to_outbox($to, $subject, $message, $args = []) {
        if (!class_exists('VMO_Email_Storage')) {
            require_once dirname(__FILE__) . '/class-vmo-email-storage.php';
        }
        
        $user_id = get_current_user_id();
        $from_email = get_option('admin_email');
        $mailbox_id = null;
        if (is_array($args)) {
            if (!empty($args['from_email'])) {
                $from_email = sanitize_email((string) $args['from_email']);
            }
            if (array_key_exists('mailbox_id', $args) && $args['mailbox_id'] !== null && $args['mailbox_id'] !== '') {
                $mailbox_id = intval($args['mailbox_id']);
            }
        }

        $storage = new VMO_Email_Storage();
        $storage->save_email([
            'user_id' => $user_id,
            'folder' => 'sent',
            'type' => 'transactional',
            'to_email' => $to,
            'from_email' => $from_email,
            'mailbox_id' => $mailbox_id,
            'subject' => $subject,
            'message' => $message
        ]);
    }
}
