#!/bin/bash

# Test Data Verification Script
# Checks what test data exists in staging environment
# Use this before/after cleanup to verify the process

source .env

echo "========================================="
echo "🔍 TEST DATA VERIFICATION"
echo "========================================="
echo "Target: $UPSKILL_STAGING_IP"
echo ""

# Upload and execute verification PHP script
sshpass -p "$UPSKILL_STAGING_PASS" scp -o StrictHostKeyChecking=no /dev/stdin $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:tmp/verify-test-data.php << 'PHPEOF'
<?php
/**
 * Test Data Verification Script
 * 
 * Checks for presence of test data in the system
 */

require_once('wp-load.php');

echo "=== Test Data Verification Report ===\n\n";

// 1. CHECK TEST USERS
echo "👥 TEST USERS:\n";
echo "================\n";

$test_users = [
    'test_trainer' => 'login',
    'joemedosch' => 'login', 
    'JoeMedosch@gmail.com' => 'email'
];

$found_users = 0;
foreach ($test_users as $identifier => $type) {
    $user = ($type === 'email') ? get_user_by('email', $identifier) : get_user_by('login', $identifier);
    
    if ($user) {
        echo "✅ Found: {$user->user_login} ({$user->user_email}) - Roles: " . implode(', ', $user->roles) . "\n";
        $found_users++;
    } else {
        echo "❌ Not found: {$identifier}\n";
    }
}

// Check joe@measurequick.com for HVAC roles
$joe_mq = get_user_by('email', 'joe@measurequick.com');
if ($joe_mq) {
    $hvac_roles = array_intersect(['hvac_trainer', 'hvac_master_trainer'], $joe_mq->roles);
    if (!empty($hvac_roles)) {
        echo "⚠️  joe@measurequick.com has HVAC roles: " . implode(', ', $hvac_roles) . "\n";
        $found_users++;
    } else {
        echo "✅ joe@measurequick.com has no HVAC roles\n";
    }
} else {
    echo "❌ joe@measurequick.com not found\n";
}

echo "\nTotal test users found: {$found_users}\n\n";

// 2. CHECK TEST EVENTS
echo "📅 TEST EVENTS:\n";
echo "================\n";

$test_event_patterns = [
    'HVAC System Diagnostics',
    'Commercial Refrigeration',
    'Energy Efficient HVAC',
    'Advanced HVAC Troubleshooting',
    'HVAC Energy Efficiency Workshop',
    'Commercial Refrigeration Systems',
    'Residential HVAC Installation Best Practices',
    'HVAC Controls and Automation'
];

$all_events = get_posts([
    'post_type' => 'tribe_events',
    'post_status' => 'any',
    'posts_per_page' => -1
]);

$found_test_events = 0;
$recent_events = 0;
$six_months_ago = strtotime('-6 months');

foreach ($all_events as $event) {
    $is_test_event = false;
    
    // Check against known test patterns
    foreach ($test_event_patterns as $pattern) {
        if (stripos($event->post_title, $pattern) !== false) {
            $is_test_event = true;
            break;
        }
    }
    
    // Check for test-like indicators
    $test_indicators = ['test', 'training center', 'example', 'dummy', 'sample'];
    $event_content = strtolower($event->post_title . ' ' . $event->post_content);
    
    foreach ($test_indicators as $indicator) {
        if (strpos($event_content, $indicator) !== false) {
            $is_test_event = true;
            break;
        }
    }
    
    if ($is_test_event) {
        $event_date = date('Y-m-d', strtotime($event->post_date));
        echo "⚠️  Test Event: '{$event->post_title}' (ID: {$event->ID}, Created: {$event_date})\n";
        $found_test_events++;
    }
    
    // Count recent events (created in last 6 months)
    if (strtotime($event->post_date) > $six_months_ago) {
        $recent_events++;
    }
}

echo "\nTotal test events found: {$found_test_events}\n";
echo "Total recent events (last 6 months): {$recent_events}\n\n";

// 3. CHECK TEST ATTENDEES
echo "🎟️  TEST ATTENDEES:\n";
echo "===================\n";

$test_attendees = get_posts([
    'post_type' => 'tribe_tpp_attendees',
    'posts_per_page' => -1,
    'meta_query' => [
        'relation' => 'OR',
        [
            'key' => '_tribe_tickets_email',
            'value' => '@example.com',
            'compare' => 'LIKE'
        ],
        [
            'key' => '_tribe_tickets_email',
            'value' => 'ben@tealmaker.com',
            'compare' => '='
        ],
        [
            'key' => '_tribe_tickets_full_name',
            'value' => 'Test',
            'compare' => 'LIKE'
        ]
    ]
]);

echo "Test attendees found: " . count($test_attendees) . "\n";

if (count($test_attendees) > 0) {
    echo "Sample test attendees:\n";
    foreach (array_slice($test_attendees, 0, 5) as $attendee) {
        $name = get_post_meta($attendee->ID, '_tribe_tickets_full_name', true);
        $email = get_post_meta($attendee->ID, '_tribe_tickets_email', true);
        $event_id = get_post_meta($attendee->ID, '_tribe_tpp_event', true);
        $event = get_post($event_id);
        $event_title = $event ? $event->post_title : 'Unknown Event';
        
        echo "  - {$name} ({$email}) for '{$event_title}'\n";
    }
    if (count($test_attendees) > 5) {
        echo "  ... and " . (count($test_attendees) - 5) . " more\n";
    }
}
echo "\n";

// 4. CHECK TEST CERTIFICATES
echo "🏆 TEST CERTIFICATES:\n";
echo "=====================\n";

if (class_exists('HVAC_Certificate_Manager')) {
    global $wpdb;
    $certificate_table = $wpdb->prefix . 'hvac_certificates';
    
    if ($wpdb->get_var("SHOW TABLES LIKE '$certificate_table'") === $certificate_table) {
        $total_certificates = $wpdb->get_var("SELECT COUNT(*) FROM {$certificate_table}");
        echo "Total certificates in database: {$total_certificates}\n";
        
        // Check for test certificate files
        $test_certificates = $wpdb->get_results("
            SELECT * FROM {$certificate_table} 
            WHERE file_path LIKE '%test%' 
               OR file_path LIKE '%example%' 
               OR file_path LIKE '%demo%'
        ");
        
        echo "Test certificates found: " . count($test_certificates) . "\n";
        
        // Check for orphaned certificates (event doesn't exist)
        $orphaned_certificates = $wpdb->get_results("
            SELECT c.* FROM {$certificate_table} c
            LEFT JOIN {$wpdb->posts} p ON c.event_id = p.ID
            WHERE p.ID IS NULL
        ");
        
        echo "Orphaned certificates (event deleted): " . count($orphaned_certificates) . "\n";
    } else {
        echo "Certificate table does not exist\n";
    }
} else {
    echo "HVAC Certificate Manager not available\n";
}
echo "\n";

// 5. CHECK TEST VENUES AND ORGANIZERS
echo "🏢 TEST VENUES & ORGANIZERS:\n";
echo "=============================\n";

$test_venues = get_posts([
    'post_type' => 'tribe_venue',
    'posts_per_page' => -1,
]);

$test_venue_count = 0;
foreach ($test_venues as $venue) {
    $test_indicators = ['training center', 'test', 'example', 'demo'];
    $venue_content = strtolower($venue->post_title . ' ' . $venue->post_content);
    
    foreach ($test_indicators as $indicator) {
        if (strpos($venue_content, $indicator) !== false) {
            echo "⚠️  Test Venue: '{$venue->post_title}' (ID: {$venue->ID})\n";
            $test_venue_count++;
            break;
        }
    }
}

$test_organizers = get_posts([
    'post_type' => 'tribe_organizer',
    'posts_per_page' => -1,
]);

$test_organizer_count = 0;
foreach ($test_organizers as $organizer) {
    $test_indicators = ['test', 'example', 'demo', 'training', 'sample'];
    $organizer_content = strtolower($organizer->post_title . ' ' . $organizer->post_content);
    
    foreach ($test_indicators as $indicator) {
        if (strpos($organizer_content, $indicator) !== false) {
            echo "⚠️  Test Organizer: '{$organizer->post_title}' (ID: {$organizer->ID})\n";
            $test_organizer_count++;
            break;
        }
    }
}

echo "Test venues found: {$test_venue_count}\n";
echo "Test organizers found: {$test_organizer_count}\n\n";

// SUMMARY
echo "========================================\n";
echo "📊 VERIFICATION SUMMARY\n";
echo "========================================\n";
echo "Test users: {$found_users}\n";
echo "Test events: {$found_test_events}\n";
echo "Test attendees: " . count($test_attendees) . "\n";
echo "Test venues: {$test_venue_count}\n";
echo "Test organizers: {$test_organizer_count}\n";

if (class_exists('HVAC_Certificate_Manager') && isset($test_certificates)) {
    echo "Test certificates: " . count($test_certificates) . "\n";
    echo "Orphaned certificates: " . count($orphaned_certificates) . "\n";
}

$total_test_items = $found_users + $found_test_events + count($test_attendees) + $test_venue_count + $test_organizer_count;
if (isset($test_certificates)) {
    $total_test_items += count($test_certificates);
}

echo "========================================\n";

if ($total_test_items > 0) {
    echo "⚠️  TEST DATA FOUND: {$total_test_items} items need cleanup\n";
    echo "Run scripts/cleanup-test-data.sh to clean up before production.\n";
} else {
    echo "✅ NO TEST DATA FOUND: Ready for production deployment!\n";
}

echo "========================================\n";
?>
PHPEOF

# Execute the verification script on the server
echo "Executing verification script on staging server..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP "cd $UPSKILL_STAGING_PATH && php ../tmp/verify-test-data.php && rm ../tmp/verify-test-data.php"

echo ""
echo "✅ Test data verification completed!"