<?php
/**
 * Simple Interface Test for Certificate Reports
 * 
 * This script simulates the actual template-certificate-reports.php processing
 * by replicating the query logic for attendee search functionality.
 */

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

echo "===== CERTIFICATE REPORTS INTERFACE SIMULATION =====\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();

// Get current user ID (should be admin)
$current_user_id = get_current_user_id();
echo "Current user ID: {$current_user_id}\n";

// Simulate different search parameters
$test_cases = [
    ['event_id' => '', 'search_attendee' => 'Ben Tester', 'revoked' => ''],
    ['event_id' => '', 'search_attendee' => 'ben@tealmaker.com', 'revoked' => ''],
    ['event_id' => '', 'search_attendee' => 'Smith', 'revoked' => ''],
    ['event_id' => '', 'search_attendee' => '@gmail', 'revoked' => ''],
];

echo "Simulating certificate report page with different search parameters:\n";
echo "----------------------------------------------------------------\n\n";

foreach ($test_cases as $index => $args) {
    echo "Test Case #" . ($index + 1) . ":\n";
    echo "Event ID: " . (empty($args['event_id']) ? "All Events" : $args['event_id']) . "\n";
    echo "Search Attendee: " . $args['search_attendee'] . "\n";
    echo "Revoked: " . (isset($args['revoked']) && $args['revoked'] !== '' ? ($args['revoked'] ? "Yes" : "No") : "All") . "\n";
    
    // Get certificate count
    $count_args = $args;
    $certificate_count = $certificate_manager->get_user_certificate_count($current_user_id, $count_args);
    echo "Certificate count: {$certificate_count}\n";
    
    // Get certificates
    $certificates = $certificate_manager->get_user_certificates($current_user_id, $args);
    echo "Certificates returned: " . count($certificates) . "\n";
    
    // Show some sample certificates if any were found
    if (!empty($certificates)) {
        echo "Sample certificates:\n";
        
        $sample_count = min(count($certificates), 3);
        for ($i = 0; $i < $sample_count; $i++) {
            $cert = $certificates[$i];
            
            if (!$cert) continue;
            
            $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 "  Certificate #{$cert->certificate_number}\n";
            echo "    Event: {$event_title}\n";
            echo "    Attendee: {$name} ({$email})\n";
            echo "    Date: {$cert->date_generated}\n";
            echo "    Status: " . ($cert->revoked ? "Revoked" : "Active") . "\n";
        }
    }
    
    echo "\n";
}

// Now get a more detailed view of how the SQL is constructed
echo "Detailed SQL Construction Analysis:\n";
echo "--------------------------------\n\n";

// Simulate the search for 'Ben Tester'
$search_term = 'Ben Tester';

// Build the WHERE clause
global $wpdb;
    
echo "Search term: '{$search_term}'\n\n";

// Get all test events
$all_events = get_posts([
    'post_type' => 'tribe_events',
    'posts_per_page' => -1,
    'fields' => 'ids'
]);

if (empty($all_events)) {
    echo "No events found. Cannot continue SQL analysis.\n";
    exit;
}

// Create event ID string for SQL
$event_ids_string = implode(',', $all_events);

// Base SQL
$base_sql = "FROM {$wpdb->prefix}hvac_certificates WHERE event_id IN ($event_ids_string)";

// Attendee search SQL
$attendee_search_sql = " 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
    )
)";

// Complete SQL for count
$count_sql = "SELECT COUNT(*) " . $base_sql . $attendee_search_sql;
$prepared_count_sql = $wpdb->prepare(
    $count_sql,
    ['%' . $wpdb->esc_like($search_term) . '%', '%' . $wpdb->esc_like($search_term) . '%']
);

echo "Count SQL:\n{$prepared_count_sql}\n\n";

// Complete SQL for data retrieval
$data_sql = "SELECT * " . $base_sql . $attendee_search_sql . " ORDER BY date_generated DESC LIMIT 20";
$prepared_data_sql = $wpdb->prepare(
    $data_sql,
    ['%' . $wpdb->esc_like($search_term) . '%', '%' . $wpdb->esc_like($search_term) . '%']
);

echo "Data SQL:\n{$prepared_data_sql}\n\n";

// Execute the queries directly to verify SQL correctness
$count_result = $wpdb->get_var($prepared_count_sql);
echo "Direct SQL count result: {$count_result}\n";

$data_result = $wpdb->get_results($prepared_data_sql);
$data_count = count($data_result);
echo "Direct SQL data result count: {$data_count}\n\n";

// Display sample results
if ($data_count > 0) {
    echo "Sample results from direct SQL query:\n";
    $sample_count = min($data_count, 3);
    
    for ($i = 0; $i < $sample_count; $i++) {
        $cert = $data_result[$i];
        
        $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 "  Certificate #{$cert->certificate_number}\n";
        echo "    Event: {$event_title}\n";
        echo "    Attendee: {$name} ({$email})\n";
        echo "    Date: {$cert->date_generated}\n";
        echo "    Status: " . ($cert->revoked ? "Revoked" : "Active") . "\n";
    }
}

echo "\n===== INTERFACE SIMULATION COMPLETE =====\n";