<?php
/**
 * Certificate System Test Script
 * 
 * This script tests the certificate system components and outputs diagnostic information.
 * Upload to the server and run via wp-cli or directly via PHP.
 *
 * Usage: php test-certificate-system.php
 */

// Load WordPress with full admin capabilities
define('WP_USE_THEMES', false);
require_once(dirname(__FILE__) . '/../wordpress/wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

echo "===== HVAC CERTIFICATE SYSTEM TEST =====\n\n";

// Check if certificate classes exist
function check_certificate_classes() {
    echo "Checking Certificate Classes:\n";

    $required_classes = [
        'HVAC_Certificate_Manager',
        'HVAC_Certificate_Installer',
        'HVAC_Certificate_Security',
        'HVAC_Certificate_Generator',
        'HVAC_Certificate_Template'
    ];

    foreach ($required_classes as $class) {
        echo " - Class {$class}: " . (class_exists($class) ? "Found ✓" : "Not Found ✗") . "\n";
    }
    
    echo "\n";
}

// Check certificate database tables
function check_certificate_tables() {
    global $wpdb;
    
    echo "Checking Certificate Tables:\n";
    
    // Define table name
    $table_name = $wpdb->prefix . 'hvac_certificates';
    
    // Check if the table exists
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
    echo " - Table {$table_name}: " . ($table_exists ? "Exists ✓" : "Not Found ✗") . "\n";
    
    if ($table_exists) {
        // Get columns
        $columns = $wpdb->get_results("DESCRIBE $table_name");
        $column_names = array_map(function($col) { return $col->Field; }, $columns);
        echo " - Found " . count($column_names) . " columns in table\n";
        
        // Expected columns
        $expected_columns = [
            'certificate_id',
            'event_id',
            'attendee_id',
            'user_id',
            'certificate_number',
            'file_path',
            'date_generated',
            'generated_by',
            'revoked',
            'revoked_date',
            'revoked_by',
            'revoked_reason',
            'email_sent',
            'email_sent_date'
        ];
        
        // Check for missing columns
        $missing_columns = array_diff($expected_columns, $column_names);
        if (empty($missing_columns)) {
            echo " - All expected columns found ✓\n";
        } else {
            echo " - Missing columns: " . implode(", ", $missing_columns) . " ✗\n";
        }
        
        // Get certificate count
        $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
        echo " - Certificates in database: " . $count . "\n";
    } else {
        echo " - Creating certificate table...\n";
        
        try {
            // Create installer and create tables
            require_once WP_PLUGIN_DIR . '/hvac-community-events/includes/certificates/class-certificate-installer.php';
            $installer = HVAC_Certificate_Installer::instance();
            $installer->create_tables();
            
            // Check if table was created
            $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
            if ($table_exists) {
                echo " - Table created successfully ✓\n";
            } else {
                echo " - Failed to create table ✗\n";
            }
        } catch (Exception $e) {
            echo " - Error creating table: " . $e->getMessage() . " ✗\n";
        }
    }
    
    echo "\n";
}

// Check certificate directory
function check_certificate_directory() {
    echo "Checking Certificate Directory:\n";
    
    $upload_dir = wp_upload_dir();
    $cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');
    
    echo " - Certificate directory path: " . $cert_dir . "\n";
    echo " - Directory exists: " . (file_exists($cert_dir) ? "Yes ✓" : "No ✗") . "\n";
    
    if (!file_exists($cert_dir)) {
        echo " - Creating certificate directory...\n";
        $result = wp_mkdir_p($cert_dir);
        echo " - Directory creation " . ($result ? "successful ✓" : "failed ✗") . "\n";
    } else {
        echo " - Directory is writable: " . (is_writable($cert_dir) ? "Yes ✓" : "No ✗") . "\n";
    }
    
    echo "\n";
}

// Check certificate template files
function check_certificate_templates() {
    echo "Checking Certificate Templates:\n";
    
    $template_dir = WP_PLUGIN_DIR . '/hvac-community-events/templates/certificates';
    echo " - Template directory: " . $template_dir . "\n";
    echo " - Directory exists: " . (file_exists($template_dir) ? "Yes ✓" : "No ✗") . "\n";
    
    if (file_exists($template_dir)) {
        $required_templates = [
            'template-certificate-reports.php',
            'template-generate-certificates.php'
        ];
        
        foreach ($required_templates as $template) {
            $template_path = $template_dir . '/' . $template;
            echo " - Template {$template}: " . (file_exists($template_path) ? "Found ✓" : "Not Found ✗") . "\n";
            
            if (file_exists($template_path)) {
                // Check for common issues
                $content = file_get_contents($template_path);
                echo "   - Size: " . strlen($content) . " bytes\n";
                echo "   - Invalid HTML comments: " . (strpos($content, '<\\!--') !== false ? "Found ✗" : "None ✓") . "\n";
                echo "   - PHP syntax: ";
                
                // Test PHP syntax
                $temp_file = sys_get_temp_dir() . '/test-' . rand(1000, 9999) . '.php';
                file_put_contents($temp_file, $content);
                exec("php -l " . escapeshellarg($temp_file) . " 2>&1", $output, $return_var);
                unlink($temp_file);
                
                if ($return_var === 0) {
                    echo "Valid ✓\n";
                } else {
                    echo "Invalid ✗\n";
                    echo "     " . implode("\n     ", $output) . "\n";
                }
            }
        }
    }
    
    echo "\n";
}

// Test running a certificate query
function test_certificate_query() {
    echo "Testing Certificate Queries:\n";
    
    if (!class_exists('HVAC_Certificate_Manager')) {
        echo " - HVAC_Certificate_Manager class not found ✗\n";
        return;
    }
    
    try {
        $certificate_manager = HVAC_Certificate_Manager::instance();
        echo " - Created certificate manager instance ✓\n";
        
        // Test getting certificate stats
        $stats = $certificate_manager->get_certificate_stats();
        echo " - Certificate stats query successful ✓\n";
        echo "   - Total certificates: " . $stats['total_certificates'] . "\n";
        echo "   - Total trainees: " . $stats['total_trainees'] . "\n";
        echo "   - Total events: " . $stats['total_events'] . "\n";
        
        // Test getting a user's certificates
        $user_id = get_current_user_id();
        echo " - Current user ID: " . $user_id . "\n";
        
        $user_certificates = $certificate_manager->get_user_certificates($user_id);
        if (is_array($user_certificates)) {
            echo " - User certificates query successful ✓\n";
            echo "   - User certificates count: " . count($user_certificates) . "\n";
        } else {
            echo " - User certificates query failed ✗\n";
        }
        
        // Test getting user certificate stats
        $user_stats = $certificate_manager->get_user_certificate_stats($user_id);
        echo " - User certificate stats query successful ✓\n";
        echo "   - User total certificates: " . $user_stats['total'] . "\n";
        echo "   - User active certificates: " . $user_stats['active'] . "\n";
        echo "   - User revoked certificates: " . $user_stats['revoked'] . "\n";
        
    } catch (Exception $e) {
        echo " - Error during certificate queries: " . $e->getMessage() . " ✗\n";
    }
    
    echo "\n";
}

// Run the tests
check_certificate_classes();
check_certificate_tables();
check_certificate_directory();
check_certificate_templates();
test_certificate_query();

echo "===== TEST COMPLETED =====\n";
echo "If any issues were found, run the Certificate Fix tool at /certificate-fix/\n";