<?php
/**
 * Test Enhanced CSV Import Script
 * This script tests the new CSV import functionality
 */

// WordPress bootstrap (adjust path as needed)
define('WP_USE_THEMES', false);
require_once('../../../wp-load.php');

// Include required files
require_once('includes/enhanced-csv-import-from-file.php');

echo "=== HVAC Enhanced CSV Import Test ===\n\n";

// Check if CSV file exists
$csv_file = __DIR__ . '/CSV_Trainers_Import_1Aug2025.csv';
echo "CSV File Path: $csv_file\n";
echo "CSV File Exists: " . (file_exists($csv_file) ? "✅ Yes" : "❌ No") . "\n\n";

if (!file_exists($csv_file)) {
    die("CSV file not found. Please ensure CSV_Trainers_Import_1Aug2025.csv is in the plugin directory.\n");
}

// Check required classes
$required_classes = [
    'HVAC_Trainer_Profile_Manager',
    'HVAC_Community_Events'
];

echo "=== Checking Required Classes ===\n";
foreach ($required_classes as $class) {
    echo "$class: " . (class_exists($class) ? "✅ Available" : "❌ Missing") . "\n";
}
echo "\n";

// Check taxonomies
echo "=== Checking Taxonomies ===\n";
$taxonomies = ['business_type', 'training_audience', 'training_formats', 'training_locations', 'training_resources'];
foreach ($taxonomies as $taxonomy) {
    $exists = taxonomy_exists($taxonomy);
    echo "$taxonomy: " . ($exists ? "✅ Registered" : "❌ Not registered") . "\n";
    
    if ($exists) {
        $terms = get_terms(['taxonomy' => $taxonomy, 'hide_empty' => false]);
        $count = is_wp_error($terms) ? 0 : count($terms);
        echo "  └─ Terms: $count\n";
    }
}
echo "\n";

// Test CSV parsing first
echo "=== Testing CSV Parsing ===\n";
$handle = fopen($csv_file, 'r');
if ($handle) {
    $headers = fgetcsv($handle, 0, ',', '"', '\\');
    $headers = array_map('trim', $headers);
    
    echo "Headers found: " . count($headers) . "\n";
    foreach ($headers as $index => $header) {
        echo sprintf("  %2d. %s\n", $index + 1, $header);
    }
    
    // Count total rows
    $row_count = 0;
    while (fgetcsv($handle) !== FALSE) {
        $row_count++;
    }
    echo "\nTotal data rows: $row_count\n\n";
    fclose($handle);
} else {
    die("Cannot open CSV file for parsing test.\n");
}

// Ask for confirmation before running import
echo "=== Ready to Run Import ===\n";
echo "This will:\n";
echo "- Import $row_count trainer profiles from CSV\n";
echo "- Create users and trainer profiles\n";
echo "- Assign taxonomy terms\n";
echo "- Create venues and organizers where requested\n\n";

echo "Proceed with import? (y/N): ";
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
fclose($handle);

if (trim(strtolower($line)) !== 'y') {
    echo "Import cancelled.\n";
    exit(0);
}

echo "\n=== Running Enhanced CSV Import ===\n";
$start_time = microtime(true);

try {
    $results = execute_enhanced_csv_import();
    
    $end_time = microtime(true);
    $execution_time = round($end_time - $start_time, 2);
    
    echo "\n=== Import Results ===\n";
    echo "Execution time: {$execution_time} seconds\n";
    echo "Total rows processed: " . ($results['total_rows'] ?? 0) . "\n";
    echo "Users created: " . ($results['users_created'] ?? 0) . "\n";
    echo "Users updated: " . ($results['users_updated'] ?? 0) . "\n";
    echo "Profiles created: " . ($results['profiles_created'] ?? 0) . "\n";
    echo "Profiles updated: " . ($results['profiles_updated'] ?? 0) . "\n";
    echo "Taxonomies assigned: " . ($results['taxonomies_assigned'] ?? 0) . "\n";
    echo "Venues created: " . ($results['venues_created'] ?? 0) . "\n";
    echo "Organizers created: " . ($results['organizers_created'] ?? 0) . "\n";
    echo "Errors: " . ($results['errors'] ?? 0) . "\n";
    
    if (isset($results['fatal_error'])) {
        echo "\n❌ Fatal Error: " . $results['fatal_error'] . "\n";
    }
    
    if (!empty($results['details'])) {
        echo "\n=== Import Details ===\n";
        foreach (array_slice($results['details'], 0, 10) as $detail) {
            echo "  $detail\n";
        }
        
        if (count($results['details']) > 10) {
            echo "  ... and " . (count($results['details']) - 10) . " more entries\n";
        }
    }
    
    echo "\n=== Verification ===\n";
    
    // Count trainer profiles
    $profile_count = wp_count_posts('trainer_profile')->publish ?? 0;
    echo "Total trainer profiles in database: $profile_count\n";
    
    // Count users with hvac_trainer role
    $trainer_users = get_users(['role' => 'hvac_trainer']);
    echo "Total HVAC trainers: " . count($trainer_users) . "\n";
    
    // Check taxonomy assignments
    echo "\nTaxonomy assignments:\n";
    foreach ($taxonomies as $taxonomy) {
        if (taxonomy_exists($taxonomy)) {
            $profiles_with_taxonomy = get_posts([
                'post_type' => 'trainer_profile',
                'tax_query' => [
                    [
                        'taxonomy' => $taxonomy,
                        'operator' => 'EXISTS'
                    ]
                ],
                'posts_per_page' => -1,
                'fields' => 'ids'
            ]);
            echo "  $taxonomy: " . count($profiles_with_taxonomy) . " profiles\n";
        }
    }
    
    echo "\n✅ Import completed successfully!\n";
    
} catch (Exception $e) {
    echo "\n❌ Import failed: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}

echo "\n=== Test Complete ===\n";
?>