<?php
/**
 * Verify Attendee Search Functionality
 * 
 * This script performs detailed tests of the attendee search functionality
 * to ensure it works correctly with different search terms.
 */

// Load WordPress
require_once('wp-load.php');

echo "===== VERIFYING ATTENDEE SEARCH FUNCTIONALITY =====\n\n";

// Check for certificate manager
if (!class_exists('HVAC_Certificate_Manager')) {
    die("Certificate Manager class not found. Please ensure the plugin is active.\n");
}

// Initialize certificate manager
$certificate_manager = HVAC_Certificate_Manager::instance();

// Define test search terms
$search_tests = [
    // Full name searches
    'Ben Tester' => 'Full name search',
    'John Smith' => 'Common full name search',
    
    // Partial name searches
    'Ben' => 'First name only search',
    'Smith' => 'Last name only search',
    'son' => 'Partial substring in last name',
    
    // Email searches
    'ben@tealmaker.com' => 'Exact email search',
    'tealmaker.com' => 'Email domain search',
    '@gmail' => 'Partial email domain search',
    'john.' => 'Partial email username search',
    
    // Case insensitive searches
    'BEN' => 'Uppercase first name search',
    'SMITH' => 'Uppercase last name search',
    'TEALMAKER.COM' => 'Uppercase domain search',
    
    // Mixed search terms
    'J@gmail' => 'Mixed character search',
    'T gmail' => 'Space-separated search',
    
    // Special characters
    'Smith.' => 'Name with trailing period',
    '.com' => 'Domain TLD search',
];

echo "Running search tests for attendee names and emails:\n";
echo "-------------------------------------------------\n\n";

global $wpdb;
$total_passes = 0;
$total_tests = count($search_tests);

foreach ($search_tests as $search_term => $description) {
    echo "Test: {$description}\n";
    echo "Search term: '{$search_term}'\n";
    
    // SQL for name search
    $name_sql = $wpdb->prepare(
        "SELECT c.certificate_id 
         FROM {$wpdb->prefix}hvac_certificates c
         JOIN {$wpdb->postmeta} pm ON c.attendee_id = pm.post_id 
         WHERE pm.meta_key = '_tribe_tickets_full_name' AND pm.meta_value LIKE %s",
        '%' . $wpdb->esc_like($search_term) . '%'
    );
    
    // SQL for email search
    $email_sql = $wpdb->prepare(
        "SELECT c.certificate_id 
         FROM {$wpdb->prefix}hvac_certificates c
         JOIN {$wpdb->postmeta} pm ON c.attendee_id = pm.post_id 
         WHERE pm.meta_key = '_tribe_tickets_email' AND pm.meta_value LIKE %s",
        '%' . $wpdb->esc_like($search_term) . '%'
    );
    
    // Combined query from the certificate manager style
    $combined_sql = "SELECT DISTINCT certificate_id FROM (
        ({$name_sql})
        UNION
        ({$email_sql})
    ) AS combined_results";
    
    // Get results
    $results = $wpdb->get_col($combined_sql);
    $result_count = count($results);
    
    echo "Results found: {$result_count}\n";
    
    // Verify with certificate manager API
    $args = [
        'search_attendee' => $search_term
    ];
    
    // Get current user
    $admin_user = get_user_by('login', 'admin');
    if ($admin_user) {
        $user_id = $admin_user->ID;
    } else {
        $user_id = 1; // Default to ID 1 if admin not found
    }
    
    // Get certificates with the attendee search
    $certificates = $certificate_manager->get_user_certificates($user_id, $args);
    $api_count = count($certificates);
    
    echo "API method results: {$api_count}\n";
    
    // Compare SQL and API results
    if ($result_count === $api_count) {
        echo "✅ PASS: SQL and API results match\n";
        $total_passes++;
    } else {
        echo "❌ FAIL: SQL and API results don't match!\n";
        echo "SQL found {$result_count} results, API found {$api_count} results\n";
    }
    
    // Include some information about the found certificates if any
    if ($result_count > 0) {
        // Get certificate details for the first result
        $cert = $certificate_manager->get_certificate($results[0]);
        
        if ($cert) {
            $event = get_post($cert->event_id);
            $event_title = $event ? $event->post_title : "Unknown Event";
            
            $attendee_id = $cert->attendee_id;
            $name = get_post_meta($attendee_id, '_tribe_tickets_full_name', true);
            $email = get_post_meta($attendee_id, '_tribe_tickets_email', true);
            
            echo "Sample result: Certificate #{$cert->certificate_number}\n";
            echo "  Event: {$event_title}\n";
            echo "  Attendee: {$name} ({$email})\n";
        }
    }
    
    echo "\n";
}

// Test with ACTUAL IMPLEMENTATION from the template
echo "Testing actual template implementation:\n";
echo "-------------------------------------\n\n";

function simulate_template_query($search_term) {
    global $wpdb;
    
    // Get a test user ID
    $user = get_user_by('login', 'admin');
    $user_id = $user ? $user->ID : 1;
    
    // We'll simulate the get_user_certificates function with search_attendee parameter
    // Get all user's events first
    $events_query = new WP_Query([
        'post_type' => 'tribe_events',
        'author' => $user_id,
        'posts_per_page' => -1,
        'fields' => 'ids',
    ]);
    
    $event_ids = $events_query->posts;
    
    if (empty($event_ids)) {
        return [];
    }
    
    // Build the base query
    $event_ids_string = implode(',', array_map('intval', $event_ids));
    $where = "WHERE event_id IN ($event_ids_string)";
    $params = [];
    
    // Add attendee search
    if (!empty($search_term)) {
        $search_term_sql = '%' . $wpdb->esc_like($search_term) . '%';
        
        $where .= " AND (
            certificate_id IN (
                SELECT c.certificate_id 
                FROM {$wpdb->prefix}hvac_certificates c
                JOIN {$wpdb->postmeta} pm ON c.attendee_id = pm.post_id 
                WHERE pm.meta_key = '_tribe_tickets_full_name' AND pm.meta_value LIKE %s
            )
            OR
            certificate_id IN (
                SELECT c.certificate_id 
                FROM {$wpdb->prefix}hvac_certificates c
                JOIN {$wpdb->postmeta} pm ON c.attendee_id = pm.post_id 
                WHERE pm.meta_key = '_tribe_tickets_email' AND pm.meta_value LIKE %s
            )
        )";
        
        $params[] = $search_term_sql;
        $params[] = $search_term_sql;
    }
    
    // Final query
    $query = "SELECT * FROM {$wpdb->prefix}hvac_certificates $where ORDER BY date_generated DESC";
    
    // Prepare with parameters if we have attendee search
    if (!empty($params)) {
        $query = $wpdb->prepare($query, $params);
    }
    
    // Execute the query
    return $wpdb->get_results($query);
}

// Test some key search terms with the actual template implementation
$template_tests = [
    'Ben Tester',
    'ben@tealmaker.com',
    'Smith',
    '@gmail.com'
];

foreach ($template_tests as $search_term) {
    echo "Template search test: '{$search_term}'\n";
    
    // Get results from our simulated template function
    $template_results = simulate_template_query($search_term);
    $template_count = count($template_results);
    
    // Get results from the certificate manager API
    $args = [
        'search_attendee' => $search_term
    ];
    
    $user = get_user_by('login', 'admin');
    $user_id = $user ? $user->ID : 1;
    
    $api_results = $certificate_manager->get_user_certificates($user_id, $args);
    $api_count = count($api_results);
    
    echo "Template function results: {$template_count}\n";
    echo "API method results: {$api_count}\n";
    
    // Compare results
    if ($template_count === $api_count) {
        echo "✅ PASS: Template and API results match\n";
    } else {
        echo "❌ FAIL: Template and API results don't match!\n";
        echo "Template found {$template_count} results, API found {$api_count} results\n";
    }
    
    echo "\n";
}

// Summary
echo "===== ATTENDEE SEARCH TEST SUMMARY =====\n\n";
echo "Total Tests: {$total_tests}\n";
echo "Tests Passed: {$total_passes}\n";
echo "Success Rate: " . round(($total_passes / $total_tests) * 100, 2) . "%\n\n";

if ($total_passes === $total_tests) {
    echo "✅ ALL TESTS PASSED!\n";
    echo "The attendee search functionality is working as expected.\n";
} else {
    echo "❌ SOME TESTS FAILED!\n";
    echo "Review the results above to identify issues with the attendee search functionality.\n";
}

echo "\n===== ATTENDEE SEARCH VERIFICATION COMPLETE =====\n";