<?php
/**
 * Emergency Certificate Fix Script
 * 
 * This script immediately fixes the certificate reports page by:
 * 1. Creating the certificate table if it doesn't exist
 * 2. Renaming the problematic template file
 * 3. Installing a simplified template file
 * 
 * Usage: Upload to staging server and run via browser or wp-cli
 */

// Set execution time to avoid timeouts
set_time_limit(300);

// Define error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load WordPress with admin capabilities
if (!defined('ABSPATH')) {
    // Find wp-load.php going up directory levels
    $path = dirname(__FILE__);
    for ($i = 0; $i < 10; $i++) {
        if (file_exists($path . '/wp-load.php')) {
            require_once($path . '/wp-load.php');
            break;
        }
        $path = dirname($path);
    }
    
    if (!defined('ABSPATH')) {
        die("Could not find WordPress installation. Upload this script to your WordPress site.");
    }
}

// Check admin privileges
if (!current_user_can('manage_options')) {
    die("You need to be an administrator to run this script.");
}

// Success/error messages
$messages = [];

// Create output function
function output_message($message, $type = 'info') {
    global $messages;
    $messages[] = ['type' => $type, 'message' => $message];
    
    // Output if running in browser
    if (php_sapi_name() !== 'cli') {
        $color = '';
        switch ($type) {
            case 'success': $color = 'green'; break;
            case 'error': $color = 'red'; break;
            case 'warning': $color = 'orange'; break;
            default: $color = 'blue';
        }
        echo "<div style='color: $color; margin: 5px 0;'><strong>" . strtoupper($type) . ":</strong> $message</div>";
    } else {
        // CLI output
        echo "[" . strtoupper($type) . "] $message\n";
    }
}

// Function to fix certificate database table
function fix_certificate_table() {
    global $wpdb;
    
    output_message("Checking certificate database table...");
    
    // Check if the table exists
    $table_name = $wpdb->prefix . 'hvac_certificates';
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
    
    if (!$table_exists) {
        output_message("Certificate table does not exist. Creating it now...", 'warning');
        
        // Make sure we have dbDelta function
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        
        // Create the certificate table
        $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;";
        
        dbDelta($sql);
        
        // Check if table was created
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        
        if ($table_exists) {
            output_message("Certificate table created successfully.", 'success');
            update_option('hvac_certificates_db_version', '1.0.0');
        } else {
            output_message("Failed to create certificate table.", 'error');
            return false;
        }
    } else {
        output_message("Certificate table exists.", 'success');
    }
    
    return true;
}

// Function to fix certificate template
function fix_certificate_template() {
    output_message("Fixing certificate template...");
    
    // Path to the problematic template
    $plugin_dir = WP_PLUGIN_DIR . '/hvac-community-events';
    $template_dir = $plugin_dir . '/templates/certificates';
    $template_file = $template_dir . '/template-certificate-reports.php';
    $simple_template_file = $template_dir . '/template-certificate-reports-simple.php';
    
    // Check if template directory exists
    if (!file_exists($template_dir)) {
        output_message("Template directory does not exist: $template_dir", 'error');
        return false;
    }
    
    // Check if the template file exists
    if (!file_exists($template_file)) {
        output_message("Original template file does not exist: $template_file", 'warning');
    } else {
        // Create backup of the original file
        $backup_file = $template_file . '.bak.' . date('YmdHis');
        if (copy($template_file, $backup_file)) {
            output_message("Created backup of original template at: $backup_file", 'success');
        } else {
            output_message("Failed to create backup of original template.", 'warning');
        }
    }
    
    // Check if simplified template exists (it should have been uploaded alongside this script)
    if (!file_exists($simple_template_file)) {
        output_message("Simplified template file not found: $simple_template_file", 'error');
        output_message("Please upload the simplified template file alongside this script.", 'error');
        return false;
    }
    
    // Replace the original template with the simplified version
    if (copy($simple_template_file, $template_file)) {
        output_message("Replaced original template with simplified version.", 'success');
    } else {
        output_message("Failed to replace template file.", 'error');
        return false;
    }
    
    return true;
}

// Function to check certificate directory
function check_certificate_directory() {
    output_message("Checking certificate storage directory...");
    
    // Get upload directory
    $upload_dir = wp_upload_dir();
    $cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');
    
    output_message("Certificate directory path: $cert_dir");
    
    // Check if directory exists
    if (!file_exists($cert_dir)) {
        output_message("Certificate directory does not exist. Creating it...", 'warning');
        
        // Create directory
        if (wp_mkdir_p($cert_dir)) {
            output_message("Certificate directory created successfully.", 'success');
        } else {
            output_message("Failed to create certificate directory.", 'error');
            return false;
        }
    } else {
        output_message("Certificate directory exists.", 'success');
    }
    
    // Check directory permissions
    if (!is_writable($cert_dir)) {
        output_message("Certificate directory is not writable. Fixing permissions...", 'warning');
        chmod($cert_dir, 0755);
        
        if (is_writable($cert_dir)) {
            output_message("Directory permissions fixed.", 'success');
        } else {
            output_message("Failed to fix directory permissions.", 'error');
            return false;
        }
    } else {
        output_message("Certificate directory is writable.", 'success');
    }
    
    return true;
}

// Function to fix certificate options
function fix_certificate_options() {
    output_message("Checking certificate options...");
    
    // Check and set certificate counter option
    if (false === get_option('hvac_certificate_counter')) {
        add_option('hvac_certificate_counter', 0);
        output_message("Added hvac_certificate_counter option.", 'success');
    }
    
    // Check and set certificate prefix option
    if (false === get_option('hvac_certificate_prefix')) {
        add_option('hvac_certificate_prefix', 'HVAC-');
        output_message("Added hvac_certificate_prefix option.", 'success');
    }
    
    // Check and set certificate storage path option
    if (false === get_option('hvac_certificate_storage_path')) {
        add_option('hvac_certificate_storage_path', 'hvac-certificates');
        output_message("Added hvac_certificate_storage_path option.", 'success');
    }
    
    // Check and set certificate db version
    if (false === get_option('hvac_certificates_db_version')) {
        add_option('hvac_certificates_db_version', '1.0.0');
        output_message("Added hvac_certificates_db_version option.", 'success');
    }
    
    return true;
}

// Function to clear cache
function clear_cache() {
    output_message("Clearing cache...");
    
    // Clear WordPress object cache
    wp_cache_flush();
    output_message("WordPress object cache cleared.", 'success');
    
    // Try to clear Breeze cache if it exists
    if (class_exists('Breeze_Admin')) {
        if (function_exists('breeze_flush_all_cache')) {
            breeze_flush_all_cache();
            output_message("Breeze cache cleared.", 'success');
        } else {
            output_message("Breeze class exists but flush function not found.", 'warning');
        }
    } else {
        output_message("Breeze cache plugin not detected.", 'info');
    }
    
    return true;
}

// Main execution
if (php_sapi_name() !== 'cli') {
    echo "<html><head><title>Emergency Certificate Fix</title>";
    echo "<style>body{font-family:sans-serif;max-width:800px;margin:0 auto;padding:20px;} h1{color:#0073aa;} div{margin:10px 0;padding:10px;border-radius:5px;} .success{background:#dff0d8;} .error{background:#f2dede;} .warning{background:#fcf8e3;} .info{background:#d9edf7;}</style>";
    echo "</head><body><h1>Emergency Certificate Fix</h1>";
}

output_message("Starting emergency certificate fix...");

// Run the fix functions
$table_fixed = fix_certificate_table();
$template_fixed = fix_certificate_template();
$directory_checked = check_certificate_directory();
$options_fixed = fix_certificate_options();
$cache_cleared = clear_cache();

// Summary
if ($table_fixed && $template_fixed && $directory_checked && $options_fixed) {
    output_message("All fixes applied successfully! The certificate reports page should now work properly.", 'success');
    output_message("Please try accessing the certificate reports page now: " . home_url('/certificate-reports/'), 'success');
} else {
    output_message("Some fixes failed to apply. Please check the logs above for details.", 'error');
}

// Output HTML footer if running in browser
if (php_sapi_name() !== 'cli') {
    echo "<hr><p>Fix completed at: " . date('Y-m-d H:i:s') . "</p>";
    echo "<p><a href='" . home_url('/certificate-reports/') . "'>Go to Certificate Reports</a></p>";
    echo "</body></html>";
}