<?php
/**
 * Certificate Database Table Check and Repair Script
 *
 * This script checks if the certificate database tables exist and creates them if they don't.
 * It's meant to be run via WP-CLI or directly on the server.
 *
 * Usage (via WP-CLI):
 * wp eval-file check-and-fix-certificate-tables.php
 */

// Bootstrap WordPress
if (!defined('ABSPATH')) {
    // Try to find the WordPress config file
    $wp_load_paths = [
        // Running from plugin directory
        '../../../wp-load.php',
        // Running from wp-content directory
        '../../wp-load.php',
        // Running from WordPress root
        './wp-load.php',
        // Running from bin directory in plugin repo
        '../wordpress/wp-load.php'
    ];

    $wp_loaded = false;
    foreach ($wp_load_paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            $wp_loaded = true;
            break;
        }
    }

    if (!$wp_loaded) {
        echo "Error: Could not locate wp-load.php. Please run this script via WP-CLI or from the WordPress root directory.\n";
        exit(1);
    }
}

// Check if this is a WP-CLI request
$is_cli = defined('WP_CLI') && WP_CLI;

/**
 * Print status message
 */
function print_status($message, $status = 'info') {
    global $is_cli;
    
    $prefix = '';
    if ($is_cli) {
        switch ($status) {
            case 'success':
                $prefix = "\033[32m[SUCCESS]\033[0m ";
                break;
            case 'error':
                $prefix = "\033[31m[ERROR]\033[0m ";
                break;
            case 'warning':
                $prefix = "\033[33m[WARNING]\033[0m ";
                break;
            default:
                $prefix = "\033[34m[INFO]\033[0m ";
                break;
        }
    } else {
        switch ($status) {
            case 'success':
                $prefix = '<span style="color: green;">[SUCCESS]</span> ';
                break;
            case 'error':
                $prefix = '<span style="color: red;">[ERROR]</span> ';
                break;
            case 'warning':
                $prefix = '<span style="color: orange;">[WARNING]</span> ';
                break;
            default:
                $prefix = '<span style="color: blue;">[INFO]</span> ';
                break;
        }
    }
    
    echo $prefix . $message . ($is_cli ? "\n" : "<br>\n");
}

// Setup utility functions
if (!function_exists('hvac_get_certificate_table_name')) {
    function hvac_get_certificate_table_name() {
        global $wpdb;
        return $wpdb->prefix . 'hvac_certificates';
    }
}

// Check if hvac-community-events plugin is active
if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

if (!is_plugin_active('hvac-community-events/hvac-community-events.php')) {
    print_status("HVAC Community Events plugin is not active. Checking for plugin files...", 'warning');
    
    // Check if plugin files exist
    $plugin_file = WP_PLUGIN_DIR . '/hvac-community-events/hvac-community-events.php';
    if (!file_exists($plugin_file)) {
        print_status("HVAC Community Events plugin files not found. Cannot proceed.", 'error');
        exit(1);
    }
    
    print_status("Plugin files found. Proceeding with table check...", 'info');
} else {
    print_status("HVAC Community Events plugin is active. Proceeding with table check...", 'success');
}

// Check if certificate installer class exists
$certificate_installer_file = WP_PLUGIN_DIR . '/hvac-community-events/includes/certificates/class-certificate-installer.php';
if (!file_exists($certificate_installer_file)) {
    print_status("Certificate installer class not found. Cannot proceed.", 'error');
    exit(1);
}

// Load the certificate installer
require_once $certificate_installer_file;

// Get database object
global $wpdb;

// Get table name
$table_name = hvac_get_certificate_table_name();

// Check if the table exists
$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;

if ($table_exists) {
    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'
    ];
    
    $missing_columns = array_diff($expected_columns, $column_names);
    
    if (!empty($missing_columns)) {
        print_status("Table is missing columns: " . implode(', ', $missing_columns), 'warning');
        print_status("Attempting to recreate the table with the correct structure...", 'info');
        
        // Try to recreate the table
        $installer = HVAC_Certificate_Installer::instance();
        $installer->create_tables();
        
        // Check if recreation was successful
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        
        if ($table_exists) {
            // Recheck columns
            $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 successfully repaired!", 'success');
            } else {
                print_status("Failed to repair table structure. Still missing columns: " . implode(', ', $missing_columns), 'error');
            }
        } else {
            print_status("Failed to recreate the certificate table.", 'error');
        }
    } else {
        print_status("Table structure is correct.", 'success');
    }
} else {
    print_status("Certificate table does not exist. Creating table...", 'warning');
    
    // Create the table
    $installer = HVAC_Certificate_Installer::instance();
    $installer->create_tables();
    
    // Check if creation was successful
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
    
    if ($table_exists) {
        print_status("Certificate table created successfully!", 'success');
    } else {
        print_status("Failed to create certificate table.", 'error');
    }
}

// Check certificate storage directory
$upload_dir = wp_upload_dir();
$cert_storage_path = get_option('hvac_certificate_storage_path', 'hvac-certificates');
$cert_dir = $upload_dir['basedir'] . '/' . $cert_storage_path;

if (!file_exists($cert_dir)) {
    print_status("Certificate storage directory does not exist. Creating directory...", 'warning');
    
    // Create directory
    if (wp_mkdir_p($cert_dir)) {
        print_status("Certificate storage directory created: $cert_dir", 'success');
    } else {
        print_status("Failed to create certificate storage directory: $cert_dir", 'error');
    }
} else {
    print_status("Certificate storage directory exists: $cert_dir", 'success');
    
    // Check if directory is writable
    if (is_writable($cert_dir)) {
        print_status("Certificate storage directory is writable.", 'success');
    } else {
        print_status("Certificate storage directory is not writable!", 'error');
    }
}

// Check htaccess file
$htaccess_file = $cert_dir . '/.htaccess';
if (!file_exists($htaccess_file)) {
    print_status("Certificate storage .htaccess file does not exist. Creating file...", 'warning');
    
    // Create .htaccess file
    $htaccess_content = "# Disable directory browsing
Options -Indexes

# Deny access to php files
<FilesMatch \"\.(php|php5|phtml|php7)$\">
Order Allow,Deny
Deny from all
</FilesMatch>

# Allow PDF downloads only via WordPress
<FilesMatch \"\.(pdf)$\">
Order Allow,Deny
Deny from all
</FilesMatch>

# Restrict direct access
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^" . get_site_url() . " [NC]
RewriteRule \\.(pdf)$ - [NC,F,L]
</IfModule>";
    
    if (file_put_contents($htaccess_file, $htaccess_content)) {
        print_status("Certificate storage .htaccess file created.", 'success');
    } else {
        print_status("Failed to create certificate storage .htaccess file.", 'error');
    }
} else {
    print_status("Certificate storage .htaccess file exists.", 'success');
}

// Check certificate settings
if (false === get_option('hvac_certificate_counter')) {
    print_status("Certificate counter not set. Setting to 0...", 'warning');
    add_option('hvac_certificate_counter', 0);
}

if (false === get_option('hvac_certificate_prefix')) {
    print_status("Certificate prefix not set. Setting to default 'HVAC-'...", 'warning');
    add_option('hvac_certificate_prefix', 'HVAC-');
}

if (false === get_option('hvac_certificate_storage_path')) {
    print_status("Certificate storage path not set. Setting to default 'hvac-certificates'...", 'warning');
    add_option('hvac_certificate_storage_path', 'hvac-certificates');
}

// Final status
print_status("Certificate system check completed.", 'success');