<?php
namespace WooNooW\Core\Mail;

/**
 * Async mail queue using Action Scheduler or wp-cron.
 * Emails are queued and sent in the background to avoid blocking API responses.
 */
class MailQueue {
    public static function init() {
        add_action('woonoow/mail/send', [__CLASS__, 'sendNow'], 10, 1);
    }

    /**
     * Queue an email to be sent asynchronously.
     * Stores payload in wp_options to avoid Action Scheduler's 8000 char limit.
     */
    public static function enqueue(array $payload) {
        // Generate unique ID for this email
        $email_id = 'woonoow_mail_' . uniqid() . '_' . time();
        
        // Store payload in wp_options (temporary, will be deleted after sending)
        update_option($email_id, $payload, false); // false = don't autoload
        

        if (function_exists('as_enqueue_async_action')) {
            // Use Action Scheduler - pass email_id as single argument
            // Action Scheduler will pass this as the first parameter to the callback
            as_enqueue_async_action('woonoow/mail/send', [$email_id], 'woonoow-mails');
        } else {
            // Fallback to wp-cron
            wp_schedule_single_event(time() + 5, 'woonoow/mail/send', [$email_id]);
        }
    }

    /**
     * Actually send the email (runs async via Action Scheduler or wp-cron).
     * Retrieves payload from wp_options and deletes it after sending.
     */
    public static function sendNow($email_id = null) {
        // Action Scheduler might pass an array, extract the first element
        if (is_array($email_id)) {
            $email_id = $email_id[0] ?? null;
        }
        
        // email_id should be a string
        if (empty($email_id)) {
            return;
        }
        
        // Retrieve payload from wp_options
        $p = get_option($email_id);
        
        if (!$p) {
            return;
        }
        
        // Temporarily disable WooEmailOverride to prevent infinite loop
        if (class_exists('WooNooW\Core\Mail\WooEmailOverride')) {
            WooEmailOverride::disable();
        }

        $result = wp_mail(
            $p['to'] ?? '',
            $p['subject'] ?? '',
            $p['html'] ?? '',
            $p['headers'] ?? [],
            $p['attachments'] ?? []
        );

        // Re-enable
        if (class_exists('WooNooW\Core\Mail\WooEmailOverride')) {
            WooEmailOverride::enable();
        }
        
        // Delete the temporary option after sending
        delete_option($email_id);
    }
}