<?php
/**
 * Certificate Reports Diagnostic and Fix Script
 *
 * This script analyzes and fixes issues with the certificate reports page
 * by ensuring proper table creation, error handling, and data validation.
 */

// 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');

// Function to print colorful status messages
function print_status($message, $type = 'info') {
    $colors = [
        'success' => "\033[32m", // Green
        'error'   => "\033[31m", // Red
        'warning' => "\033[33m", // Yellow
        'info'    => "\033[36m", // Cyan
        'reset'   => "\033[0m",  // Reset
    ];
    
    echo $colors[$type] . "[" . strtoupper($type) . "] " . $message . $colors['reset'] . PHP_EOL;
}

// Function to check and create certificate tables
function check_and_create_certificate_tables() {
    global $wpdb;
    
    print_status("Checking certificate tables...");
    
    // 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;
    
    if (!$table_exists) {
        print_status("Certificate table does not exist. Creating it now...", 'warning');
        
        // Create the table with proper schema
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            certificate_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            event_id BIGINT(20) UNSIGNED NOT NULL,
            attendee_id BIGINT(20) UNSIGNED NOT NULL,
            user_id BIGINT(20) UNSIGNED DEFAULT NULL,
            certificate_number VARCHAR(50) NOT NULL,
            file_path VARCHAR(255) NOT NULL,
            date_generated DATETIME NOT NULL,
            generated_by BIGINT(20) UNSIGNED NOT NULL,
            revoked TINYINT(1) NOT NULL DEFAULT 0,
            revoked_date DATETIME DEFAULT NULL,
            revoked_by BIGINT(20) UNSIGNED DEFAULT NULL,
            revoked_reason TEXT DEFAULT NULL,
            email_sent TINYINT(1) NOT NULL DEFAULT 0,
            email_sent_date DATETIME DEFAULT NULL,
            PRIMARY KEY (certificate_id),
            UNIQUE KEY event_attendee (event_id, attendee_id),
            KEY event_id (event_id),
            KEY attendee_id (attendee_id),
            KEY user_id (user_id),
            KEY certificate_number (certificate_number),
            KEY revoked (revoked)
        ) $charset_collate;";
        
        // Use dbDelta to create or update table
        $result = dbDelta($sql);
        
        // Check if table was created
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        
        if ($table_exists) {
            print_status("Table created successfully!", 'success');
            update_option('hvac_certificates_db_version', '1.0.0');
        } else {
            print_status("Failed to create table. Error: " . $wpdb->last_error, 'error');
            return false;
        }
    } else {
        print_status("Certificate table exists: $table_name", 'success');
        
        // Check if the table has the expected structure
        print_status("Checking table structure...", 'info');
        
        // Get columns
        $columns = $wpdb->get_results("DESCRIBE $table_name");
        $column_names = array_map(function($col) { return $col->Field; }, $columns);
        
        // 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)) {
            print_status("Table is missing columns: " . implode(", ", $missing_columns), 'warning');
            
            // Create migration to add missing columns
            print_status("Attempting to fix missing columns...", 'info');
            
            // Use dbDelta to update table structure
            $charset_collate = $wpdb->get_charset_collate();
            
            $sql = "CREATE TABLE $table_name (
                certificate_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                event_id BIGINT(20) UNSIGNED NOT NULL,
                attendee_id BIGINT(20) UNSIGNED NOT NULL,
                user_id BIGINT(20) UNSIGNED DEFAULT NULL,
                certificate_number VARCHAR(50) NOT NULL,
                file_path VARCHAR(255) NOT NULL,
                date_generated DATETIME NOT NULL,
                generated_by BIGINT(20) UNSIGNED NOT NULL,
                revoked TINYINT(1) NOT NULL DEFAULT 0,
                revoked_date DATETIME DEFAULT NULL,
                revoked_by BIGINT(20) UNSIGNED DEFAULT NULL,
                revoked_reason TEXT DEFAULT NULL,
                email_sent TINYINT(1) NOT NULL DEFAULT 0,
                email_sent_date DATETIME DEFAULT NULL,
                PRIMARY KEY (certificate_id),
                UNIQUE KEY event_attendee (event_id, attendee_id),
                KEY event_id (event_id),
                KEY attendee_id (attendee_id),
                KEY user_id (user_id),
                KEY certificate_number (certificate_number),
                KEY revoked (revoked)
            ) $charset_collate;";
            
            $result = dbDelta($sql);
            
            // Check if fix was successful
            $columns = $wpdb->get_results("DESCRIBE $table_name");
            $column_names = array_map(function($col) { return $col->Field; }, $columns);
            $missing_columns = array_diff($expected_columns, $column_names);
            
            if (empty($missing_columns)) {
                print_status("Table structure fixed successfully!", 'success');
                update_option('hvac_certificates_db_version', '1.0.0');
            } else {
                print_status("Failed to fix all columns. Still missing: " . implode(", ", $missing_columns), 'error');
                return false;
            }
        } else {
            print_status("Table structure is correct.", 'success');
        }
    }
    
    // Check and create certificate directory
    print_status("Checking certificate directory...", 'info');
    
    $upload_dir = wp_upload_dir();
    $cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');
    
    if (!file_exists($cert_dir)) {
        print_status("Certificate directory does not exist. Creating it now...", 'warning');
        wp_mkdir_p($cert_dir);
        
        if (file_exists($cert_dir)) {
            print_status("Certificate directory created: $cert_dir", 'success');
        } else {
            print_status("Failed to create certificate directory.", 'error');
            return false;
        }
    } else {
        print_status("Certificate directory exists: $cert_dir", 'success');
    }
    
    // Check and set certificate options
    print_status("Checking certificate options...", 'info');
    
    if (false === get_option('hvac_certificate_counter')) {
        add_option('hvac_certificate_counter', 0);
        print_status("Added hvac_certificate_counter option", 'success');
    }
    
    if (false === get_option('hvac_certificate_prefix')) {
        add_option('hvac_certificate_prefix', 'HVAC-');
        print_status("Added hvac_certificate_prefix option", 'success');
    }
    
    if (false === get_option('hvac_certificate_storage_path')) {
        add_option('hvac_certificate_storage_path', 'hvac-certificates');
        print_status("Added hvac_certificate_storage_path option", 'success');
    }
    
    return true;
}

// Fix certificate template closing PHP tag issue
function fix_template_closing_tags() {
    print_status("Checking template-certificate-reports.php for syntax issues...", 'info');
    
    $plugin_dir = WP_CONTENT_DIR . '/plugins/hvac-community-events/';
    $template_file = $plugin_dir . 'templates/certificates/template-certificate-reports.php';
    
    if (file_exists($template_file)) {
        $content = file_get_contents($template_file);
        
        // Find and fix HTML comment tags (<!-- to <!--)
        if (strpos($content, '<\!--') !== false) {
            print_status("Found invalid HTML comment tags. Fixing them...", 'warning');
            $content = str_replace('<\!--', '<!--', $content);
            file_put_contents($template_file, $content);
            print_status("Fixed HTML comment tags", 'success');
        }
        
        // Check if there's a try-catch block that isn't properly closed
        if (substr_count($content, 'try {') !== substr_count($content, '} catch')) {
            print_status("Found unmatched try-catch blocks. This is likely causing PHP syntax errors.", 'warning');
            
            // This is a more complex fix that might require manual intervention
            print_status("Please check the template file manually for proper try-catch block closure", 'warning');
        }
        
        print_status("Template file checked", 'success');
    } else {
        print_status("Template file not found: $template_file", 'error');
        return false;
    }
    
    return true;
}

// Main execution
print_status("Certificate Reports Page Fix Script", 'info');
print_status("====================================", 'info');

// Step 1: Check and create tables
$tables_ok = check_and_create_certificate_tables();
if (!$tables_ok) {
    print_status("Failed to fix certificate tables. Exiting.", 'error');
    exit(1);
}

// Step 2: Check template files
$templates_ok = fix_template_closing_tags();
if (!$templates_ok) {
    print_status("Failed to fix template files. Exiting.", 'error');
    exit(1);
}

// Step 3: Verify all certificate components are loaded correctly
print_status("Verifying certificate components...", 'info');

// Check if all required classes are loaded
$required_classes = [
    'HVAC_Certificate_Manager' => HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-manager.php',
    'HVAC_Certificate_Installer' => HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-installer.php',
    'HVAC_Certificate_Security' => HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-security.php'
];

foreach ($required_classes as $class_name => $file_path) {
    if (!class_exists($class_name)) {
        print_status("Class $class_name not found. Loading from $file_path", 'warning');
        require_once $file_path;
        
        if (class_exists($class_name)) {
            print_status("Class $class_name loaded successfully", 'success');
        } else {
            print_status("Failed to load class $class_name", 'error');
        }
    } else {
        print_status("Class $class_name already loaded", 'success');
    }
}

// Force certificate table creation one more time to ensure it's properly set up
$installer = new HVAC_Certificate_Installer();
$installer->create_tables();
print_status("Forced certificate table creation", 'success');

// Get a simple certificate count to verify functionality
print_status("Testing certificate query functionality...", 'info');
global $wpdb;
$table_name = $wpdb->prefix . 'hvac_certificates';
$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");

if ($wpdb->last_error) {
    print_status("Query error: " . $wpdb->last_error, 'error');
} else {
    print_status("Certificate count: $count", 'success');
}

// Create a test certificate record if none exist
if ($count == 0) {
    print_status("No certificates found. Creating a test certificate record...", 'info');
    
    // Get an event ID to use for the test
    $event = get_posts([
        'post_type' => 'tribe_events',
        'posts_per_page' => 1,
        'post_status' => 'publish'
    ]);
    
    if (!empty($event)) {
        $event_id = $event[0]->ID;
        
        // Create a test attendee record if not present
        // This is a simplified approach - in reality, attendee creation would be more complex
        $attendee_id = 99999;
        
        // Current date/time
        $date_generated = current_time('mysql');
        
        // Create certificate record
        $result = $wpdb->insert(
            $table_name,
            array(
                'event_id' => $event_id,
                'attendee_id' => $attendee_id,
                'user_id' => get_current_user_id(),
                'certificate_number' => 'TEST-' . date('Y') . '-00001',
                'file_path' => 'hvac-certificates/test-certificate.pdf',
                'date_generated' => $date_generated,
                'generated_by' => get_current_user_id(),
                'revoked' => 0,
                'email_sent' => 0
            ),
            array(
                '%d', // event_id
                '%d', // attendee_id
                '%d', // user_id
                '%s', // certificate_number
                '%s', // file_path
                '%s', // date_generated
                '%d', // generated_by
                '%d', // revoked
                '%d'  // email_sent
            )
        );
        
        if ($result) {
            $certificate_id = $wpdb->insert_id;
            print_status("Test certificate created with ID $certificate_id", 'success');
        } else {
            print_status("Failed to create test certificate: " . $wpdb->last_error, 'error');
        }
    } else {
        print_status("No events found to create a test certificate", 'warning');
    }
}

print_status("Fix script completed successfully!", 'success');
print_status("You should now be able to access the Certificate Reports page.", 'success');
print_status("If issues persist, please contact the developer for further assistance.", 'info');