<?php
/**
 * Verify Certificate Test Data
 * 
 * This script verifies that the certificate test data was created correctly
 * by querying the database directly.
 */

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

echo "===== VERIFYING CERTIFICATE TEST DATA =====\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 overall certificate statistics
$stats = $certificate_manager->get_certificate_stats();

echo "Certificate Database Statistics:\n";
echo "--------------------------------\n";
echo "Total certificates: {$stats['total_certificates']}\n";
echo "Total events with certificates: {$stats['total_events']}\n";
echo "Total trainees with certificates: {$stats['total_trainees']}\n";
echo "Total revoked certificates: {$stats['total_revoked']}\n";
echo "Total emailed certificates: {$stats['total_emailed']}\n";
echo "Average certificates per attendee: {$stats['avg_per_attendee']}\n\n";

// Verify our specific test events
$test_events = [
    'HVAC System Design Fundamentals',
    'Advanced Refrigeration Technology',
    'Building Automation Systems Workshop'
];

echo "Verifying Test Events:\n";
echo "---------------------\n";

global $wpdb;

// Verify each test event
foreach ($test_events as $event_title) {
    // Get the event by title
    $event = get_page_by_title($event_title, OBJECT, 'tribe_events');
    
    if (!$event) {
        echo "❌ Event '{$event_title}' not found in database\n";
        continue;
    }
    
    $event_id = $event->ID;
    echo "✅ Found event '{$event_title}' (ID: {$event_id})\n";
    
    // Get attendees for this event
    $attendees = get_posts([
        'post_type' => 'tribe_tpp_attendees',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_event',
                'value' => $event_id,
            ]
        ],
        'posts_per_page' => -1
    ]);
    
    $total_attendees = count($attendees);
    echo "  - Total attendees: {$total_attendees}\n";
    
    // Count checked-in attendees
    $checked_in = 0;
    foreach ($attendees as $attendee) {
        $checkin_status = get_post_meta($attendee->ID, '_tribe_tpp_checkin', true);
        if (!empty($checkin_status)) {
            $checked_in++;
        }
    }
    echo "  - Checked-in attendees: {$checked_in}\n";
    
    // Check certificates for this event
    $certificates = $certificate_manager->get_certificates_by_event($event_id, true);
    $cert_count = count($certificates);
    echo "  - Certificates generated: {$cert_count}\n";
    
    // Count revoked and emailed
    $revoked = 0;
    $emailed = 0;
    foreach ($certificates as $cert) {
        if ($cert->revoked) {
            $revoked++;
        }
        if ($cert->email_sent) {
            $emailed++;
        }
    }
    echo "  - Revoked certificates: {$revoked}\n";
    echo "  - Emailed certificates: {$emailed}\n";
    
    // Verify Ben Tester attendee and certificate
    $ben_attendee = null;
    foreach ($attendees as $attendee) {
        $name = get_post_meta($attendee->ID, '_tribe_tickets_full_name', true);
        if ($name === 'Ben Tester') {
            $ben_attendee = $attendee;
            break;
        }
    }
    
    if ($ben_attendee) {
        echo "  - ✅ Found 'Ben Tester' attendee (ID: {$ben_attendee->ID})\n";
        
        // Check if Ben has a certificate
        $ben_cert = $certificate_manager->get_certificate_by_attendee($event_id, $ben_attendee->ID);
        if ($ben_cert) {
            echo "  - ✅ 'Ben Tester' has a certificate (ID: {$ben_cert->certificate_id})\n";
            echo "    - Certificate #: {$ben_cert->certificate_number}\n";
            echo "    - Generated on: {$ben_cert->date_generated}\n";
            echo "    - Revoked: " . ($ben_cert->revoked ? 'Yes' : 'No') . "\n";
            echo "    - Emailed: " . ($ben_cert->email_sent ? 'Yes' : 'No') . "\n";
        } else {
            echo "  - ❌ 'Ben Tester' does not have a certificate\n";
        }
    } else {
        echo "  - ❌ 'Ben Tester' attendee not found for this event\n";
    }
    
    echo "\n";
}

// Verify attendee search functionality
echo "Verifying Attendee Search:\n";
echo "------------------------\n";

// Test searching by 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",
    '%Ben%'
);

$ben_cert_ids = $wpdb->get_col($sql);
echo "Search for 'Ben' in attendee names: Found " . count($ben_cert_ids) . " certificates\n";

// Test searching by 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",
    '%@tealmaker.com%'
);

$email_cert_ids = $wpdb->get_col($sql);
echo "Search for '@tealmaker.com' in attendee emails: Found " . count($email_cert_ids) . " certificates\n\n";

// Verify pagination would work by checking certificate count
$per_page = 20; // Default per page in template
$pages = ceil($stats['total_certificates'] / $per_page);

echo "Pagination Check:\n";
echo "----------------\n";
echo "With {$stats['total_certificates']} total certificates and {$per_page} per page,\n";
echo "the certificate reports page would have {$pages} pages\n\n";

echo "===== CERTIFICATE TEST DATA VERIFICATION COMPLETE =====\n";

if ($stats['total_certificates'] >= 47 &&
    $stats['total_events'] >= 3 &&
    $stats['total_trainees'] >= 47 &&
    count($ben_cert_ids) >= 1 &&
    count($email_cert_ids) >= 1 &&
    $pages >= 1) {
    echo "\n✅ TEST DATA VERIFICATION PASSED\n";
    echo "The certificate test data appears to be correctly created and accessible.\n";
    echo "You can now manually test the certificate reports page at:\n";
    echo home_url('/certificate-reports/') . "\n";
} else {
    echo "\n❌ TEST DATA VERIFICATION FAILED\n";
    echo "Some of the expected test data could not be verified. Review the results above.\n";
}