<?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);
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[WooNooW MailQueue] Hook registered: woonoow/mail/send -> MailQueue::sendNow');
        }
    }

    /**
     * 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
        
        // Debug log in dev mode
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[WooNooW MailQueue] Queued email ID: ' . $email_id . ' to: ' . ($payload['to'] ?? 'unknown'));
        }

        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) {
        error_log('[WooNooW MailQueue] sendNow() called with args: ' . print_r(func_get_args(), true));
        error_log('[WooNooW MailQueue] email_id type: ' . gettype($email_id));
        error_log('[WooNooW MailQueue] email_id value: ' . var_export($email_id, true));
        
        // Action Scheduler might pass an array, extract the first element
        if (is_array($email_id)) {
            error_log('[WooNooW MailQueue] email_id is array, extracting first element');
            $email_id = $email_id[0] ?? null;
        }
        
        // email_id should be a string
        if (empty($email_id)) {
            error_log('[WooNooW MailQueue] ERROR: No email_id provided after extraction. Received: ' . print_r(func_get_args(), true));
            return;
        }
        
        error_log('[WooNooW MailQueue] Processing email_id: ' . $email_id);
        
        // Retrieve payload from wp_options
        $p = get_option($email_id);
        
        if (!$p) {
            error_log('[WooNooW MailQueue] ERROR: Email payload not found for ID: ' . $email_id);
            error_log('[WooNooW MailQueue] Checking if option exists in database...');
            global $wpdb;
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name = %s",
                $email_id
            ));
            error_log('[WooNooW MailQueue] Option exists in DB: ' . ($exists ? 'yes' : 'no'));
            return;
        }
        
        error_log('[WooNooW MailQueue] Payload retrieved - To: ' . ($p['to'] ?? 'unknown') . ', Subject: ' . ($p['subject'] ?? 'unknown'));
        
        // Temporarily disable WooEmailOverride to prevent infinite loop
        if (class_exists('WooNooW\Core\Mail\WooEmailOverride')) {
            error_log('[WooNooW MailQueue] Disabling WooEmailOverride to prevent loop');
            WooEmailOverride::disable();
        }

        error_log('[WooNooW MailQueue] Calling wp_mail() now...');
        
        $result = wp_mail(
            $p['to'] ?? '',
            $p['subject'] ?? '',
            $p['html'] ?? '',
            $p['headers'] ?? [],
            $p['attachments'] ?? []
        );
        
        error_log('[WooNooW MailQueue] wp_mail() returned: ' . ($result ? 'TRUE (success)' : 'FALSE (failed)'));

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

        error_log('[WooNooW MailQueue] Sent and deleted email ID: ' . $email_id . ' to: ' . ($p['to'] ?? 'unknown'));
    }
}