<?php
/**
 * Direct Email Test - Bypass Action Scheduler
 * 
 * Usage: wp eval-file test-email-direct.php
 * Or visit: /wp-content/plugins/woonoow/test-email-direct.php
 */

// Load WordPress if not already loaded
if (!defined('ABSPATH')) {
    require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/wp-load.php';
}

if (!current_user_can('manage_options')) {
    die('Access denied');
}

echo "=== WooNooW Email Direct Test ===\n\n";

// Test 1: Check if MailQueue hook is registered
echo "1. Checking hook registration...\n";
global $wp_filter;
if (isset($wp_filter['woonoow/mail/send'])) {
    echo "   ✓ Hook 'woonoow/mail/send' is registered\n";
    echo "   Callbacks: " . count($wp_filter['woonoow/mail/send']->callbacks[10]) . "\n";
} else {
    echo "   ✗ Hook 'woonoow/mail/send' is NOT registered!\n";
    echo "   This means MailQueue::init() was not called.\n";
}

// Test 2: Queue a test email
echo "\n2. Queuing test email...\n";
$test_payload = [
    'to' => get_option('admin_email'),
    'subject' => 'Direct Test - ' . date('H:i:s'),
    'html' => '<h1>Direct Test</h1><p>This is a direct test email.</p>',
    'headers' => ['Content-Type: text/html; charset=UTF-8'],
    'attachments' => [],
];

\WooNooW\Core\Mail\MailQueue::enqueue($test_payload);
echo "   ✓ Email queued\n";

// Test 3: Check wp_options for queued email
echo "\n3. Checking wp_options for queued emails...\n";
global $wpdb;
$queued = $wpdb->get_results(
    "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'woonoow_mail_%' ORDER BY option_id DESC LIMIT 5"
);

if (empty($queued)) {
    echo "   ✗ No emails found in wp_options!\n";
} else {
    echo "   ✓ Found " . count($queued) . " queued email(s):\n";
    foreach ($queued as $row) {
        echo "     - " . $row->option_name . "\n";
    }
}

// Test 4: Check Action Scheduler
echo "\n4. Checking Action Scheduler...\n";
if (function_exists('as_enqueue_async_action')) {
    $pending = $wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions 
        WHERE hook = 'woonoow/mail/send' AND status = 'pending'"
    );
    echo "   ✓ Action Scheduler available\n";
    echo "   Pending actions: $pending\n";
    
    // Get the most recent action
    $recent = $wpdb->get_row(
        "SELECT * FROM {$wpdb->prefix}actionscheduler_actions 
        WHERE hook = 'woonoow/mail/send' 
        ORDER BY action_id DESC LIMIT 1"
    );
    
    if ($recent) {
        echo "   Most recent action:\n";
        echo "     ID: " . $recent->action_id . "\n";
        echo "     Status: " . $recent->status . "\n";
        echo "     Args: " . $recent->args . "\n";
        echo "     Scheduled: " . $recent->scheduled_date_gmt . "\n";
    }
} else {
    echo "   ✗ Action Scheduler not available\n";
}

// Test 5: Manually trigger sendNow() with the queued email
echo "\n5. Manually triggering sendNow()...\n";
if (!empty($queued)) {
    $email_id = $queued[0]->option_name;
    echo "   Using email_id: $email_id\n";
    echo "   Calling MailQueue::sendNow()...\n";
    
    \WooNooW\Core\Mail\MailQueue::sendNow($email_id);
    
    echo "   ✓ sendNow() called\n";
    echo "   Check debug.log for detailed output\n";
} else {
    echo "   ✗ No email to send\n";
}

// Test 6: Check if email was sent
echo "\n6. Checking if email was sent...\n";
$still_queued = $wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE 'woonoow_mail_%'"
);

if ($still_queued == 0) {
    echo "   ✓ All emails sent (queue is empty)\n";
} else {
    echo "   ⚠ Still $still_queued email(s) in queue\n";
}

// Test 7: Direct wp_mail test
echo "\n7. Testing wp_mail() directly...\n";
$direct_result = wp_mail(
    get_option('admin_email'),
    'Direct wp_mail Test - ' . date('H:i:s'),
    '<h1>Direct Test</h1><p>This bypasses the queue entirely.</p>',
    ['Content-Type: text/html; charset=UTF-8']
);

echo "   wp_mail() returned: " . ($direct_result ? 'TRUE (success)' : 'FALSE (failed)') . "\n";

if (!$direct_result) {
    echo "   ✗ wp_mail() failed - check your SMTP configuration\n";
} else {
    echo "   ✓ wp_mail() succeeded - check your inbox\n";
}

echo "\n=== Test Complete ===\n";
echo "Check /wp-content/debug.log for detailed logs\n";
echo "Check Email Log plugin for sent emails\n";
