<?php
/**
 * HVAC Zoho CRM Integration Patcher
 * 
 * This script patches the Zoho CRM integration files to add better error
 * reporting and environment variable loading. Upload to the WordPress root
 * and run via URL with security parameter: ?run_patch=true
 */

// Security check - only run when explicitly requested
if (\!isset($_GET['run_patch']) || $_GET['run_patch'] \!== 'true') {
    die('Patch not enabled. Add ?run_patch=true to the URL to run the patch.');
}

// Set headers for plain text output
header('Content-Type: text/plain');

echo "==========================================\n";
echo "HVAC Community Events - Zoho CRM Integration Patcher\n";
echo "==========================================\n";
echo "Timestamp: " . date('Y-m-d H:i:s') . "\n\n";

// Find the WordPress installation
define('ABSPATH', dirname(dirname(__FILE__)) . '/');

// Set paths
echo "Determining paths...\n";
$plugin_dir = ABSPATH . 'wp-content/plugins/hvac-community-events';
$zoho_dir = $plugin_dir . '/includes/zoho';
$admin_dir = $plugin_dir . '/includes/admin';
$js_dir = $plugin_dir . '/assets/js';
$css_dir = $plugin_dir . '/assets/css';
$logs_dir = $plugin_dir . '/includes/logs';

// Check for required directories
echo "Checking directories...\n";
$dirs = array(
    'Plugin' => $plugin_dir,
    'Zoho' => $zoho_dir,
    'Admin' => $admin_dir,
    'JavaScript' => $js_dir,
    'CSS' => $css_dir,
    'Logs' => $logs_dir
);

foreach ($dirs as $name => $dir) {
    echo "$name directory: ";
    if (file_exists($dir)) {
        echo "Found at $dir\n";
    } else {
        echo "Not found at $dir. Attempting to create...\n";
        if (mkdir($dir, 0755, true)) {
            echo "Created $name directory successfully.\n";
        } else {
            echo "Failed to create $name directory.\n";
        }
    }
}

// Create logs directory
if (\!file_exists($logs_dir)) {
    if (mkdir($logs_dir, 0755, true)) {
        echo "Created logs directory: $logs_dir\n";
    } else {
        echo "Failed to create logs directory: $logs_dir\n";
    }
}

// Check for zoho-config.php
$zoho_config_file = $zoho_dir . '/zoho-config.php';
echo "\nChecking for zoho-config.php...\n";
if (file_exists($zoho_config_file)) {
    echo "Found at $zoho_config_file\n";
    
    // Backup the file
    $backup_file = $zoho_config_file . '.bak.' . date('YmdHis');
    if (copy($zoho_config_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of zoho-config.php\n";
    }
} else {
    echo "Not found at $zoho_config_file. Will create a new one.\n";
}

// Create or update zoho-config.php
echo "\nUpdating zoho-config.php...\n";
$zoho_config_content = <<<'EOT'
<?php
/**
 * Zoho CRM Configuration
 * 
 * This file contains the necessary constants for Zoho CRM integration.
 * Modified with enhanced debugging and log file path.
 */

// Load environment variables from .env file
function load_env_from_dotenv() {
    // Look for .env file in plugin directory and up to 3 levels up
    $search_dirs = [
        dirname(dirname(dirname(__FILE__))), // Plugin directory
        dirname(dirname(dirname(dirname(__FILE__)))), // wp-content/plugins
        dirname(dirname(dirname(dirname(dirname(__FILE__))))), // wp-content
        dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // WordPress root
    ];
    
    foreach ($search_dirs as $dir) {
        $env_file = $dir . '/.env';
        if (file_exists($env_file)) {
            $lines = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {
                if (strpos($line, '=') \!== false && strpos($line, '#') \!== 0) {
                    list($name, $value) = explode('=', $line, 2);
                    $name = trim($name);
                    $value = trim($value);
                    
                    // Remove quotes if present
                    if (strpos($value, '"') === 0 && strrpos($value, '"') === strlen($value) - 1) {
                        $value = substr($value, 1, -1);
                    } elseif (strpos($value, "'") === 0 && strrpos($value, "'") === strlen($value) - 1) {
                        $value = substr($value, 1, -1);
                    }
                    
                    putenv("$name=$value");
                    $_ENV[$name] = $value;
                }
            }
            return true;
        }
    }
    return false;
}

// Try to load environment variables
$env_loaded = load_env_from_dotenv();

// Log directory setup
$log_dir = dirname(dirname(__FILE__)) . '/logs';
if (\!file_exists($log_dir)) {
    mkdir($log_dir, 0755, true);
}

// Get client ID either from environment or from existing constant
$clientId = '';
if (isset($_ENV['ZOHO_CLIENT_ID'])) {
    $clientId = $_ENV['ZOHO_CLIENT_ID'];
} elseif (getenv('ZOHO_CLIENT_ID')) {
    $clientId = getenv('ZOHO_CLIENT_ID');
} elseif (defined('ZOHO_CLIENT_ID')) {
    $clientId = ZOHO_CLIENT_ID;
}

// Get client secret either from environment or from existing constant
$clientSecret = '';
if (isset($_ENV['ZOHO_CLIENT_SECRET'])) {
    $clientSecret = $_ENV['ZOHO_CLIENT_SECRET'];
} elseif (getenv('ZOHO_CLIENT_SECRET')) {
    $clientSecret = getenv('ZOHO_CLIENT_SECRET');
} elseif (defined('ZOHO_CLIENT_SECRET')) {
    $clientSecret = ZOHO_CLIENT_SECRET;
}

// Get refresh token either from environment or from existing constant
$refreshToken = '';
if (isset($_ENV['ZOHO_REFRESH_TOKEN'])) {
    $refreshToken = $_ENV['ZOHO_REFRESH_TOKEN'];
} elseif (getenv('ZOHO_REFRESH_TOKEN')) {
    $refreshToken = getenv('ZOHO_REFRESH_TOKEN');
} elseif (defined('ZOHO_REFRESH_TOKEN')) {
    $refreshToken = ZOHO_REFRESH_TOKEN;
}

// OAuth Client Credentials
// IMPORTANT: You need to fill these values with your Zoho OAuth credentials
define('ZOHO_CLIENT_ID', $clientId);
define('ZOHO_CLIENT_SECRET', $clientSecret);
define('ZOHO_REDIRECT_URI', 'https://wordpress-974670-5399585.cloudwaysapps.com/oauth/callback');

// API Endpoints
define('ZOHO_ACCOUNTS_URL', 'https://accounts.zoho.com');
define('ZOHO_API_BASE_URL', 'https://www.zohoapis.com/crm/v2');

// Scopes
define('ZOHO_SCOPES', 'ZohoCRM.settings.all,ZohoCRM.modules.all,ZohoCRM.users.all,ZohoCRM.org.all');

// Optional - Refresh Token (if already obtained)
define('ZOHO_REFRESH_TOKEN', $refreshToken);

// Debug Settings - Enhanced for better logging
define('ZOHO_DEBUG_MODE', true);
define('ZOHO_LOG_FILE', $log_dir . '/zoho-debug.log');

// Add diagnostic information to log
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
    $timestamp = date('Y-m-d H:i:s');
    $debug_info = "[$timestamp] Zoho CRM Configuration loaded\n";
    $debug_info .= "[$timestamp] .env file loaded: " . ($env_loaded ? 'Yes' : 'No') . "\n";
    $debug_info .= "[$timestamp] Client ID exists: " . (\!empty(ZOHO_CLIENT_ID) ? 'Yes' : 'No') . "\n";
    $debug_info .= "[$timestamp] Client ID value: " . (ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'EMPTY') . "\n";
    $debug_info .= "[$timestamp] Client Secret exists: " . (\!empty(ZOHO_CLIENT_SECRET) ? 'Yes' : 'No') . "\n";
    $debug_info .= "[$timestamp] Client Secret value: " . (ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'EMPTY') . "\n";
    $debug_info .= "[$timestamp] Refresh Token exists: " . (\!empty(ZOHO_REFRESH_TOKEN) ? 'Yes' : 'No') . "\n";
    $debug_info .= "[$timestamp] Refresh Token value: " . (ZOHO_REFRESH_TOKEN ? substr(ZOHO_REFRESH_TOKEN, 0, 5) . '...' : 'EMPTY') . "\n";
    $debug_info .= "[$timestamp] Log file path: " . ZOHO_LOG_FILE . "\n";
    
    if (function_exists('get_site_url')) {
        $debug_info .= "[$timestamp] WordPress site URL: " . get_site_url() . "\n";
        $debug_info .= "[$timestamp] Staging mode: " . (strpos(get_site_url(), 'upskillhvac.com') === false ? 'Yes' : 'No') . "\n";
    } else {
        $debug_info .= "[$timestamp] WordPress functions not available\n";
    }
    
    // Check for environment variables directly
    $debug_info .= "[$timestamp] Environment variables:\n";
    $debug_info .= "[$timestamp]   - _ENV['ZOHO_CLIENT_ID']: " . (isset($_ENV['ZOHO_CLIENT_ID']) ? 'Set' : 'Not set') . "\n";
    $debug_info .= "[$timestamp]   - _ENV['ZOHO_CLIENT_SECRET']: " . (isset($_ENV['ZOHO_CLIENT_SECRET']) ? 'Set' : 'Not set') . "\n";
    $debug_info .= "[$timestamp]   - _ENV['ZOHO_REFRESH_TOKEN']: " . (isset($_ENV['ZOHO_REFRESH_TOKEN']) ? 'Set' : 'Not set') . "\n";
    
    // Log configuration details
    error_log($debug_info, 3, ZOHO_LOG_FILE);
}
EOT;

if (file_put_contents($zoho_config_file, $zoho_config_content)) {
    echo "Updated zoho-config.php successfully.\n";
} else {
    echo "Failed to update zoho-config.php.\n";
}

// Update zoho-admin.php
$zoho_admin_file = $admin_dir . '/class-zoho-admin.php';
echo "\nChecking for class-zoho-admin.php...\n";
if (file_exists($zoho_admin_file)) {
    echo "Found at $zoho_admin_file\n";
    
    // Backup the file
    $backup_file = $zoho_admin_file . '.bak.' . date('YmdHis');
    if (copy($zoho_admin_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of class-zoho-admin.php\n";
    }
    
    // Read the file
    $admin_content = file_get_contents($zoho_admin_file);
    
    // Check if already patched
    if (strpos($admin_content, 'ZOHO_DEBUG_MODE') === false) {
        echo "Patching class-zoho-admin.php with enhanced error reporting...\n";
        
        // Find the test_connection method
        $pattern = '/public function test_connection\(\) {([^}]+)}/s';
        
        // Add enhanced error reporting
        $replacement = "public function test_connection() {
        // Enable debug logging
        if (\!defined('ZOHO_DEBUG_MODE')) {
            define('ZOHO_DEBUG_MODE', true);
        }
        
        // Create a temporary log file if needed
        if (\!defined('ZOHO_LOG_FILE')) {
            \$log_dir = HVAC_CE_PLUGIN_DIR . 'includes/logs';
            if (\!file_exists(\$log_dir)) {
                mkdir(\$log_dir, 0755, true);
            }
            define('ZOHO_LOG_FILE', \$log_dir . '/zoho-debug.log');
        }
        
        // Log the request
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] Testing Zoho CRM connection\\n\";
            if (defined('ZOHO_LOG_FILE')) {
                error_log(\$log_message, 3, ZOHO_LOG_FILE);
            }
        }
        
        // Check nonce for security
        check_ajax_referer('hvac_zoho_admin_nonce', 'nonce');
        
        // Get Zoho CRM Auth instance
        \$zoho_auth = HVAC_Zoho_CRM_Auth::get_instance();
        
        // Test the connection
        \$response = \$zoho_auth->get_modules();
        
        // Enhanced error handling and detailed response
        if (\$response && \!isset(\$response['error'])) {
            wp_send_json_success(array(
                'message' => 'Connection successful\!',
                'modules' => isset(\$response['modules']) ? count(\$response['modules']) . ' modules available' : 'No modules found'
            ));
        } else {
            \$error_message = isset(\$response['error']) ? \$response['error'] : 'Unknown error';
            \$error_code = isset(\$response['code']) ? \$response['code'] : '';
            \$error_details = isset(\$response['details']) ? \$response['details'] : '';
            
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] Connection test failed: \$error_message\\n\";
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Error code: \$error_code\\n\";
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Details: \$error_details\\n\";
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Raw response: \" . json_encode(\$response) . \"\\n\";
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log(\$log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            // Send detailed error data back to frontend
            wp_send_json_error(array(
                'message' => 'Connection failed',
                'error' => \$error_message,
                'code' => \$error_code,
                'details' => \$error_details,
                'raw' => json_encode(\$response)
            ));
        }
    }";
        
        // Replace in the file
        $admin_content = preg_replace($pattern, $replacement, $admin_content);
        
        // Save the updated file
        if (file_put_contents($zoho_admin_file, $admin_content)) {
            echo "Updated class-zoho-admin.php successfully.\n";
        } else {
            echo "Failed to update class-zoho-admin.php.\n";
        }
    } else {
        echo "class-zoho-admin.php already patched.\n";
    }
} else {
    echo "Not found at $zoho_admin_file. Creating a new file...\n";
    
    // Create new class-zoho-admin.php
    $admin_content = <<<'EOT'
<?php
/**
 * HVAC Zoho Admin
 *
 * This class handles the admin interface for Zoho CRM integration
 */

if (\!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class HVAC_Zoho_Admin {
    /**
     * Constructor
     */
    public function __construct() {
        // Add admin menu
        add_action('admin_menu', array($this, 'add_menu'));

        // Register settings
        add_action('admin_init', array($this, 'register_settings'));

        // Enqueue scripts
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));

        // AJAX handlers
        add_action('wp_ajax_hvac_zoho_test_connection', array($this, 'test_connection'));
    }

    /**
     * Add admin menu
     */
    public function add_menu() {
        add_submenu_page(
            'edit.php?post_type=tribe_events',
            __('Zoho CRM Sync', 'hvac-community-events'),
            __('Zoho CRM Sync', 'hvac-community-events'),
            'manage_options',
            'hvac-zoho-crm-sync',
            array($this, 'render_admin_page')
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting('hvac_zoho_settings_group', 'hvac_zoho_enabled');
        register_setting('hvac_zoho_settings_group', 'hvac_zoho_sync_attendees');
        register_setting('hvac_zoho_settings_group', 'hvac_zoho_sync_events');
    }

    /**
     * Enqueue scripts
     */
    public function enqueue_scripts($hook) {
        if ('tribe_events_page_hvac-zoho-crm-sync' \!== $hook) {
            return;
        }

        wp_enqueue_style('hvac-zoho-admin', HVAC_CE_PLUGIN_URL . 'assets/css/zoho-admin.css', array(), HVAC_CE_VERSION);
        wp_enqueue_script('hvac-zoho-admin', HVAC_CE_PLUGIN_URL . 'assets/js/zoho-admin.js', array('jquery'), HVAC_CE_VERSION, true);

        wp_localize_script('hvac-zoho-admin', 'hvac_zoho_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_zoho_admin_nonce'),
            'testing_connection' => __('Testing connection...', 'hvac-community-events'),
            'connection_success' => __('Connection successful\!', 'hvac-community-events'),
            'connection_error' => __('Connection failed', 'hvac-community-events')
        ));
    }

    /**
     * Render admin page
     */
    public function render_admin_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('Zoho CRM Sync', 'hvac-community-events'); ?></h1>

            <form method="post" action="options.php">
                <?php settings_fields('hvac_zoho_settings_group'); ?>
                <?php do_settings_sections('hvac_zoho_settings_group'); ?>

                <table class="form-table">
                    <tr valign="top">
                        <th scope="row"><?php _e('Enable Zoho CRM Sync', 'hvac-community-events'); ?></th>
                        <td>
                            <input type="checkbox" name="hvac_zoho_enabled" value="1" <?php checked(get_option('hvac_zoho_enabled'), 1); ?> />
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php _e('Sync Attendees', 'hvac-community-events'); ?></th>
                        <td>
                            <input type="checkbox" name="hvac_zoho_sync_attendees" value="1" <?php checked(get_option('hvac_zoho_sync_attendees'), 1); ?> />
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php _e('Sync Events', 'hvac-community-events'); ?></th>
                        <td>
                            <input type="checkbox" name="hvac_zoho_sync_events" value="1" <?php checked(get_option('hvac_zoho_sync_events'), 1); ?> />
                        </td>
                    </tr>
                </table>

                <?php submit_button(); ?>
            </form>

            <hr>

            <h2><?php _e('Connection Test', 'hvac-community-events'); ?></h2>
            <p><?php _e('Test your connection to Zoho CRM API.', 'hvac-community-events'); ?></p>
            
            <button class="button button-primary" id="hvac-zoho-test-connection">
                <?php _e('Test Connection', 'hvac-community-events'); ?>
            </button>
            
            <div id="hvac-zoho-test-connection-result" style="margin-top: 10px;"></div>
            
            <hr>
            
            <h2><?php _e('Zoho CRM Configuration', 'hvac-community-events'); ?></h2>
            <p><?php _e('The Zoho CRM configuration is stored in the zoho-config.php file and .env file.', 'hvac-community-events'); ?></p>
            
            <?php
            // Get Zoho CRM Auth instance
            $zoho_auth = HVAC_Zoho_CRM_Auth::get_instance();
            
            // Check if credentials are configured
            $client_id = $zoho_auth->get_client_id();
            $client_secret = $zoho_auth->get_client_secret();
            $refresh_token = $zoho_auth->get_refresh_token();
            
            if (empty($client_id) || empty($client_secret) || empty($refresh_token)) {
                echo '<div class="notice notice-error"><p>';
                _e('Zoho CRM credentials are not fully configured. Please check your zoho-config.php file and .env file.', 'hvac-community-events');
                echo '</p>';
                
                if (empty($client_id)) {
                    echo '<p>ZOHO_CLIENT_ID is missing or empty.</p>';
                }
                
                if (empty($client_secret)) {
                    echo '<p>ZOHO_CLIENT_SECRET is missing or empty.</p>';
                }
                
                if (empty($refresh_token)) {
                    echo '<p>ZOHO_REFRESH_TOKEN is missing or empty.</p>';
                }
                
                echo '</div>';
            } else {
                echo '<div class="notice notice-success"><p>';
                _e('Zoho CRM credentials are configured.', 'hvac-community-events');
                echo '</p></div>';
            }
            ?>
        </div>
        <?php
    }

    /**
     * Test connection
     */
    public function test_connection() {
        // Enable debug logging
        if (\!defined('ZOHO_DEBUG_MODE')) {
            define('ZOHO_DEBUG_MODE', true);
        }
        
        // Create a temporary log file if needed
        if (\!defined('ZOHO_LOG_FILE')) {
            $log_dir = HVAC_CE_PLUGIN_DIR . 'includes/logs';
            if (\!file_exists($log_dir)) {
                mkdir($log_dir, 0755, true);
            }
            define('ZOHO_LOG_FILE', $log_dir . '/zoho-debug.log');
        }
        
        // Log the request
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            $log_message = "[" . date('Y-m-d H:i:s') . "] Testing Zoho CRM connection\n";
            if (defined('ZOHO_LOG_FILE')) {
                error_log($log_message, 3, ZOHO_LOG_FILE);
            }
        }
        
        // Check nonce for security
        check_ajax_referer('hvac_zoho_admin_nonce', 'nonce');
        
        // Get Zoho CRM Auth instance
        $zoho_auth = HVAC_Zoho_CRM_Auth::get_instance();
        
        // Test the connection
        $response = $zoho_auth->get_modules();
        
        // Enhanced error handling and detailed response
        if ($response && \!isset($response['error'])) {
            wp_send_json_success(array(
                'message' => 'Connection successful\!',
                'modules' => isset($response['modules']) ? count($response['modules']) . ' modules available' : 'No modules found'
            ));
        } else {
            $error_message = isset($response['error']) ? $response['error'] : 'Unknown error';
            $error_code = isset($response['code']) ? $response['code'] : '';
            $error_details = isset($response['details']) ? $response['details'] : '';
            
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                $log_message = "[" . date('Y-m-d H:i:s') . "] Connection test failed: $error_message\n";
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Error code: $error_code\n";
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Details: $error_details\n";
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Raw response: " . json_encode($response) . "\n";
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log($log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            // Send detailed error data back to frontend
            wp_send_json_error(array(
                'message' => 'Connection failed',
                'error' => $error_message,
                'code' => $error_code,
                'details' => $error_details,
                'raw' => json_encode($response)
            ));
        }
    }
}

// Initialize the admin class
new HVAC_Zoho_Admin();
EOT;

    if (file_put_contents($zoho_admin_file, $admin_content)) {
        echo "Created class-zoho-admin.php successfully.\n";
    } else {
        echo "Failed to create class-zoho-admin.php.\n";
    }
}

// Update class-zoho-crm-auth.php
$zoho_auth_file = $zoho_dir . '/class-zoho-crm-auth.php';
echo "\nChecking for class-zoho-crm-auth.php...\n";
if (file_exists($zoho_auth_file)) {
    echo "Found at $zoho_auth_file\n";
    
    // Backup the file
    $backup_file = $zoho_auth_file . '.bak.' . date('YmdHis');
    if (copy($zoho_auth_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of class-zoho-crm-auth.php\n";
    }
    
    // Read the file
    $auth_content = file_get_contents($zoho_auth_file);
    
    // Check if already patched
    if (strpos($auth_content, 'load_env_from_dotenv') === false) {
        echo "Patching class-zoho-crm-auth.php with environment loading...\n";
        
        // Find the beginning of the class definition
        $pattern = '/class HVAC_Zoho_CRM_Auth/';
        
        // Add environment loading function
        $replacement = "/**
 * Load environment variables from .env file
 */
function load_env_from_dotenv() {
    // Look for .env file in plugin directory and up to 3 levels up
    \$search_dirs = [
        dirname(dirname(dirname(__FILE__))), // Plugin directory
        dirname(dirname(dirname(dirname(__FILE__)))), // wp-content/plugins
        dirname(dirname(dirname(dirname(dirname(__FILE__))))), // wp-content
        dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // WordPress root
    ];
    
    foreach (\$search_dirs as \$dir) {
        \$env_file = \$dir . '/.env';
        if (file_exists(\$env_file)) {
            \$lines = file(\$env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach (\$lines as \$line) {
                if (strpos(\$line, '=') \!== false && strpos(\$line, '#') \!== 0) {
                    list(\$name, \$value) = explode('=', \$line, 2);
                    \$name = trim(\$name);
                    \$value = trim(\$value);
                    
                    // Remove quotes if present
                    if (strpos(\$value, '\"') === 0 && strrpos(\$value, '\"') === strlen(\$value) - 1) {
                        \$value = substr(\$value, 1, -1);
                    } elseif (strpos(\$value, \"'\") === 0 && strrpos(\$value, \"'\") === strlen(\$value) - 1) {
                        \$value = substr(\$value, 1, -1);
                    }
                    
                    putenv(\"\$name=\$value\");
                    \$_ENV[\$name] = \$value;
                }
            }
            return true;
        }
    }
    return false;
}

class HVAC_Zoho_CRM_Auth";

        // Replace the class definition
        $auth_content = preg_replace($pattern, $replacement, $auth_content);
        
        // Find the constructor
        $constructor_pattern = '/public function __construct\(\) {/';
        $constructor_replacement = "public function __construct() {
        // Load environment variables from .env if available
        load_env_from_dotenv();";
        
        // Replace the constructor
        $auth_content = preg_replace($constructor_pattern, $constructor_replacement, $auth_content);
        
        // Add error logging to API requests
        $api_pattern = '/public function make_api_request\(\$endpoint, \$method = \'GET\', \$data = array\(\)\) {/';
        $api_replacement = "public function make_api_request(\$endpoint, \$method = 'GET', \$data = array()) {
        // Enhanced error logging
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] API Request: \$method \$endpoint\\n\";
            \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Data: \" . json_encode(\$data) . \"\\n\";
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log(\$log_message, 3, ZOHO_LOG_FILE);
            }
        }";
        
        // Replace the API request method
        $auth_content = preg_replace($api_pattern, $api_replacement, $auth_content);
        
        // Add detailed logging to the API response
        $response_pattern = '/\$response = wp_remote_request\(\$url, \$args\);/';
        $response_replacement = "\$response = wp_remote_request(\$url, \$args);

        // Enhanced error logging
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] API Response Code: \" . wp_remote_retrieve_response_code(\$response) . \"\\n\";
            
            if (is_wp_error(\$response)) {
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] API Error: \" . \$response->get_error_message() . \"\\n\";
            } else {
                \$response_body = wp_remote_retrieve_body(\$response);
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] API Response Body: \" . substr(\$response_body, 0, 1000) . (strlen(\$response_body) > 1000 ? '...' : '') . \"\\n\";
            }
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log(\$log_message, 3, ZOHO_LOG_FILE);
            }
        }";
        
        // Replace the response handling
        $auth_content = preg_replace($response_pattern, $response_replacement, $auth_content);
        
        // Add getter methods for credentials
        if (strpos($auth_content, 'get_client_id') === false) {
            $auth_content .= <<<'EOT'

    /**
     * Get client ID
     *
     * @return string
     */
    public function get_client_id() {
        return $this->client_id;
    }

    /**
     * Get client secret
     *
     * @return string
     */
    public function get_client_secret() {
        return $this->client_secret;
    }

    /**
     * Get refresh token
     *
     * @return string
     */
    public function get_refresh_token() {
        return $this->refresh_token;
    }
EOT;
        }
        
        // Save the updated file
        if (file_put_contents($zoho_auth_file, $auth_content)) {
            echo "Updated class-zoho-crm-auth.php successfully.\n";
        } else {
            echo "Failed to update class-zoho-crm-auth.php.\n";
        }
    } else {
        echo "class-zoho-crm-auth.php already patched.\n";
    }
} else {
    echo "Not found at $zoho_auth_file. Will not create a new file since it's too complex.\n";
}

// Create a diagnostic tool
$diagnostic_file = $zoho_dir . '/diagnostics.php';
echo "\nCreating Zoho diagnostics tool...\n";
$diagnostic_content = <<<'EOT'
<?php
/**
 * Zoho CRM Integration Diagnostics
 * 
 * This file provides diagnostic tools for troubleshooting Zoho CRM integration issues.
 * Access via URL with security parameter: ?run_diagnostics=true
 */

// Security check - only run diagnostics when explicitly requested
if (\!isset($_GET['run_diagnostics']) || $_GET['run_diagnostics'] \!== 'true') {
    die('Diagnostics not enabled. Add ?run_diagnostics=true to the URL to run diagnostics.');
}

// Set headers for plain text output
header('Content-Type: text/plain');

echo "==========================================\n";
echo "HVAC Community Events - Zoho CRM Diagnostics\n";
echo "==========================================\n";
echo "Timestamp: " . date('Y-m-d H:i:s') . "\n\n";

// Find the WordPress installation
function find_wordpress_root() {
    $dir = __DIR__;
    while ($dir \!== '/' && \!file_exists($dir . '/wp-config.php')) {
        $dir = dirname($dir);
    }
    return file_exists($dir . '/wp-config.php') ? $dir : false;
}

// Try to bootstrap WordPress
$wp_root = find_wordpress_root();

if ($wp_root) {
    echo "WordPress installation found at: $wp_root\n";
    
    // Try to bootstrap WordPress
    if (file_exists($wp_root . '/wp-load.php')) {
        echo "Loading WordPress...\n";
        require_once $wp_root . '/wp-load.php';
        echo "WordPress loaded successfully.\n";
    } else {
        echo "Error: wp-load.php not found\!\n";
    }
} else {
    echo "Error: WordPress installation not found\!\n";
}

echo "\n";
echo "==========================================\n";
echo "Environment Information\n";
echo "==========================================\n";

// PHP Version
echo "PHP Version: " . phpversion() . "\n";

// WordPress Version (if available)
if (function_exists('get_bloginfo')) {
    echo "WordPress Version: " . get_bloginfo('version') . "\n";
}

// Server Information
echo "Server Software: " . $_SERVER['SERVER_SOFTWARE'] . "\n";
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "\n";
echo "Request URI: " . $_SERVER['REQUEST_URI'] . "\n";

echo "\n";
echo "==========================================\n";
echo "Plugin Information\n";
echo "==========================================\n";

// Plugin Path
$plugin_dir = dirname(dirname(dirname(__FILE__)));
echo "Plugin Directory: $plugin_dir\n";

// Check if plugin is active
if (function_exists('is_plugin_active')) {
    echo "Plugin Active: " . (is_plugin_active('hvac-community-events/hvac-community-events.php') ? 'Yes' : 'No') . "\n";
}

// Plugin Version
if (file_exists($plugin_dir . '/hvac-community-events.php')) {
    $plugin_data = file_get_contents($plugin_dir . '/hvac-community-events.php');
    if (preg_match('/Version:\s*([0-9.]+)/i', $plugin_data, $matches)) {
        echo "Plugin Version: " . $matches[1] . "\n";
    }
}

echo "\n";
echo "==========================================\n";
echo "Zoho CRM Configuration\n";
echo "==========================================\n";

// Check if Zoho config file exists
$zoho_config_path = $plugin_dir . '/includes/zoho/zoho-config.php';
if (file_exists($zoho_config_path)) {
    echo "Zoho Config File: Found\n";
    
    // Include the config file
    require_once $zoho_config_path;
    
    // Check for required constants
    echo "ZOHO_CLIENT_ID defined: " . (defined('ZOHO_CLIENT_ID') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_CLIENT_ID value: " . (defined('ZOHO_CLIENT_ID') && ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'EMPTY') . "\n";
    
    echo "ZOHO_CLIENT_SECRET defined: " . (defined('ZOHO_CLIENT_SECRET') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_CLIENT_SECRET value: " . (defined('ZOHO_CLIENT_SECRET') && ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'EMPTY') . "\n";
    
    echo "ZOHO_REFRESH_TOKEN defined: " . (defined('ZOHO_REFRESH_TOKEN') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_REFRESH_TOKEN value: " . (defined('ZOHO_REFRESH_TOKEN') && ZOHO_REFRESH_TOKEN ? substr(ZOHO_REFRESH_TOKEN, 0, 5) . '...' : 'EMPTY') . "\n";
    
    echo "ZOHO_REDIRECT_URI defined: " . (defined('ZOHO_REDIRECT_URI') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_REDIRECT_URI value: " . (defined('ZOHO_REDIRECT_URI') ? ZOHO_REDIRECT_URI : 'UNDEFINED') . "\n";
    
    echo "ZOHO_DEBUG_MODE defined: " . (defined('ZOHO_DEBUG_MODE') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_DEBUG_MODE value: " . (defined('ZOHO_DEBUG_MODE') ? (ZOHO_DEBUG_MODE ? 'true' : 'false') : 'UNDEFINED') . "\n";
    
    echo "ZOHO_LOG_FILE defined: " . (defined('ZOHO_LOG_FILE') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_LOG_FILE value: " . (defined('ZOHO_LOG_FILE') ? ZOHO_LOG_FILE : 'UNDEFINED') . "\n";
    echo "ZOHO_LOG_FILE exists: " . (defined('ZOHO_LOG_FILE') && file_exists(ZOHO_LOG_FILE) ? 'Yes' : 'No') . "\n";
    echo "ZOHO_LOG_FILE writable: " . (defined('ZOHO_LOG_FILE') && is_writable(dirname(ZOHO_LOG_FILE)) ? 'Yes' : 'No') . "\n";
} else {
    echo "Zoho Config File: Not Found\! Expected at $zoho_config_path\n";
}

echo "\n";
echo "==========================================\n";
echo "Environment Variables\n";
echo "==========================================\n";

// Check for environment variables
echo "ZOHO_CLIENT_ID environment variable: " . (getenv('ZOHO_CLIENT_ID') ? 'Set' : 'Not Set') . "\n";
echo "ZOHO_CLIENT_SECRET environment variable: " . (getenv('ZOHO_CLIENT_SECRET') ? 'Set' : 'Not Set') . "\n";
echo "ZOHO_REFRESH_TOKEN environment variable: " . (getenv('ZOHO_REFRESH_TOKEN') ? 'Set' : 'Not Set') . "\n";

// Check for _ENV array variables
echo "_ENV['ZOHO_CLIENT_ID']: " . (isset($_ENV['ZOHO_CLIENT_ID']) ? 'Set' : 'Not Set') . "\n";
echo "_ENV['ZOHO_CLIENT_SECRET']: " . (isset($_ENV['ZOHO_CLIENT_SECRET']) ? 'Set' : 'Not Set') . "\n";
echo "_ENV['ZOHO_REFRESH_TOKEN']: " . (isset($_ENV['ZOHO_REFRESH_TOKEN']) ? 'Set' : 'Not Set') . "\n";

// Check .env file
$env_file_paths = [
    $plugin_dir . '/.env',
    dirname($plugin_dir) . '/.env',
    dirname(dirname($plugin_dir)) . '/.env',
    dirname(dirname(dirname($plugin_dir))) . '/.env',
];

foreach ($env_file_paths as $env_path) {
    echo "\nChecking for .env file at: $env_path\n";
    if (file_exists($env_path)) {
        echo ".env file exists: Yes\n";
        echo ".env file readable: " . (is_readable($env_path) ? 'Yes' : 'No') . "\n";
        
        if (is_readable($env_path)) {
            $env_contents = file_get_contents($env_path);
            echo "ZOHO_CLIENT_ID in .env: " . (strpos($env_contents, 'ZOHO_CLIENT_ID') \!== false ? 'Yes' : 'No') . "\n";
            echo "ZOHO_CLIENT_SECRET in .env: " . (strpos($env_contents, 'ZOHO_CLIENT_SECRET') \!== false ? 'Yes' : 'No') . "\n";
            echo "ZOHO_REFRESH_TOKEN in .env: " . (strpos($env_contents, 'ZOHO_REFRESH_TOKEN') \!== false ? 'Yes' : 'No') . "\n";
        }
        
        // Try to load .env file
        if (function_exists('load_env_from_dotenv')) {
            echo "Loading .env file with load_env_from_dotenv()...\n";
            $result = load_env_from_dotenv();
            echo "Result: " . ($result ? 'Success' : 'Failed') . "\n";
            
            // Check variables after loading
            echo "ZOHO_CLIENT_ID after loading: " . (getenv('ZOHO_CLIENT_ID') ? 'Set' : 'Not Set') . "\n";
            echo "ZOHO_CLIENT_SECRET after loading: " . (getenv('ZOHO_CLIENT_SECRET') ? 'Set' : 'Not Set') . "\n";
            echo "ZOHO_REFRESH_TOKEN after loading: " . (getenv('ZOHO_REFRESH_TOKEN') ? 'Set' : 'Not Set') . "\n";
        } else {
            echo "load_env_from_dotenv() function not available\!\n";
        }
        
        break;
    } else {
        echo ".env file exists: No\n";
    }
}

echo "\n";
echo "==========================================\n";
echo "Testing API Connection\n";
echo "==========================================\n";

// Try to instantiate the Zoho CRM Auth class
if (class_exists('HVAC_Zoho_CRM_Auth')) {
    echo "HVAC_Zoho_CRM_Auth class exists\n";
    
    try {
        // Get instance
        $zoho_auth = HVAC_Zoho_CRM_Auth::get_instance();
        echo "Successfully instantiated HVAC_Zoho_CRM_Auth\n";
        
        // Test token generation
        echo "Testing token generation...\n";
        $token = $zoho_auth->get_access_token();
        echo "Token generation result: " . ($token && \!is_array($token) ? "Success (Token: " . substr($token, 0, 10) . "...)" : "Failed") . "\n";
        
        if (is_array($token) && isset($token['error'])) {
            echo "Error: " . $token['error'] . "\n";
            if (isset($token['details'])) {
                echo "Details: " . $token['details'] . "\n";
            }
        }
        
        // Test API connection
        echo "Testing API connection...\n";
        $modules = $zoho_auth->get_modules();
        if (is_array($modules) && \!isset($modules['error'])) {
            echo "API connection successful\!\n";
            echo "Available modules: " . (isset($modules['modules']) ? count($modules['modules']) : '0') . "\n";
            
            if (isset($modules['modules'])) {
                echo "Module names:\n";
                foreach ($modules['modules'] as $module) {
                    echo "  - " . $module['api_name'] . "\n";
                }
            }
        } else {
            echo "API connection failed\!\n";
            echo "Error details: " . print_r($modules, true) . "\n";
        }
    } catch (Exception $e) {
        echo "Exception: " . $e->getMessage() . "\n";
        echo "Stack trace: " . $e->getTraceAsString() . "\n";
    }
} else {
    echo "HVAC_Zoho_CRM_Auth class does not exist\!\n";
}

echo "\n";
echo "==========================================\n";
echo "Log File Contents (if available)\n";
echo "==========================================\n";

if (defined('ZOHO_LOG_FILE') && file_exists(ZOHO_LOG_FILE) && is_readable(ZOHO_LOG_FILE)) {
    echo "Log file found at: " . ZOHO_LOG_FILE . "\n";
    echo "Log file size: " . filesize(ZOHO_LOG_FILE) . " bytes\n";
    echo "Last 50 lines of log file:\n";
    
    $log_lines = file(ZOHO_LOG_FILE);
    $last_lines = array_slice($log_lines, -50);
    
    echo "-------------------------\n";
    foreach ($last_lines as $line) {
        echo $line;
    }
    echo "-------------------------\n";
} else {
    echo "Log file not found or not readable.\n";
}

echo "\n";
echo "==========================================\n";
echo "Diagnostics completed at " . date('Y-m-d H:i:s') . "\n";
echo "==========================================\n";

// Exit to prevent any further output
exit();
EOT;

if (file_put_contents($diagnostic_file, $diagnostic_content)) {
    echo "Created diagnostics.php successfully.\n";
} else {
    echo "Failed to create diagnostics.php.\n";
}

// Create CSS file for Zoho admin
$zoho_css_file = $css_dir . '/zoho-admin.css';
echo "\nChecking for zoho-admin.css...\n";
if (file_exists($zoho_css_file)) {
    echo "Found at $zoho_css_file\n";
    
    // Backup the file
    $backup_file = $zoho_css_file . '.bak.' . date('YmdHis');
    if (copy($zoho_css_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of zoho-admin.css\n";
    }
    
    // Read the file
    $css_content = file_get_contents($zoho_css_file);
    
    // Check if already patched
    if (strpos($css_content, 'hvac-zoho-debug-info') === false) {
        echo "Adding debug information styling to zoho-admin.css...\n";
        
        // Add debug information styling
        $css_content .= "\n\n/* Debug Information Styling */
.hvac-zoho-debug-info {
    margin-top: 15px;
    padding: 15px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-left: 4px solid #dc3232;
}

.hvac-zoho-debug-info details summary {
    cursor: pointer;
    font-weight: bold;
    color: #0073aa;
    padding: 5px;
    background: #f0f0f0;
}

.hvac-zoho-debug-info pre {
    margin: 10px 0;
    padding: 10px;
    background: #f0f0f0;
    border: 1px solid #ddd;
    overflow: auto;
    max-height: 300px;
}";
        
        // Save the updated file
        if (file_put_contents($zoho_css_file, $css_content)) {
            echo "Updated zoho-admin.css successfully.\n";
        } else {
            echo "Failed to update zoho-admin.css.\n";
        }
    } else {
        echo "zoho-admin.css already patched.\n";
    }
} else {
    echo "Not found at $zoho_css_file. Creating a new file...\n";
    
    // Create new zoho-admin.css
    $css_content = <<<'EOT'
/* Zoho Admin Styles */
.hvac-zoho-debug-info {
    margin-top: 15px;
    padding: 15px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-left: 4px solid #dc3232;
}

.hvac-zoho-debug-info details summary {
    cursor: pointer;
    font-weight: bold;
    color: #0073aa;
    padding: 5px;
    background: #f0f0f0;
}

.hvac-zoho-debug-info pre {
    margin: 10px 0;
    padding: 10px;
    background: #f0f0f0;
    border: 1px solid #ddd;
    overflow: auto;
    max-height: 300px;
}
EOT;

    if (file_put_contents($zoho_css_file, $css_content)) {
        echo "Created zoho-admin.css successfully.\n";
    } else {
        echo "Failed to create zoho-admin.css.\n";
    }
}

// Create JS file for Zoho admin
$zoho_js_file = $js_dir . '/zoho-admin.js';
echo "\nChecking for zoho-admin.js...\n";
if (file_exists($zoho_js_file)) {
    echo "Found at $zoho_js_file\n";
    
    // Backup the file
    $backup_file = $zoho_js_file . '.bak.' . date('YmdHis');
    if (copy($zoho_js_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of zoho-admin.js\n";
    }
    
    // Read the file
    $js_content = file_get_contents($zoho_js_file);
    
    // Check if already patched
    if (strpos($js_content, 'hvac-zoho-debug-info') === false) {
        echo "Patching zoho-admin.js with enhanced error display...\n";
        
        // Find the error handler
        $pattern = '/error: function\(response\) {([^}]+)}/s';
        
        // Add enhanced error display
        $replacement = "error: function(response) {
            $('#hvac-zoho-test-connection-result').empty();
            
            // Create detailed error display
            var errorHtml = '<div class=\"notice notice-error\">';
            errorHtml += '<p><strong>' + response.data.message + ':</strong> ' + response.data.error + '</p>';
            
            // Add error code if available
            if (response.data.code) {
                errorHtml += '<p><strong>Error Code:</strong> ' + response.data.code + '</p>';
            }
            
            // Add debugging info
            errorHtml += '<div class=\"hvac-zoho-debug-info\">';
            // Add details if available
            if (response.data.details) {
                errorHtml += '<p><strong>Details:</strong> ' + response.data.details + '</p>';
            }
            
            // Add raw response data if available
            if (response.data.raw) {
                errorHtml += '<details>';
                errorHtml += '<summary>Raw Response Data (click to expand)</summary>';
                errorHtml += '<pre>' + JSON.stringify(JSON.parse(response.data.raw), null, 2) + '</pre>';
                errorHtml += '</details>';
            }
            
            errorHtml += '</div>'; // Close debug info div
            errorHtml += '</div>'; // Close notice div
            
            $('#hvac-zoho-test-connection-result').html(errorHtml);
        }";
        
        // Replace the error handler
        $js_content = preg_replace($pattern, $replacement, $js_content);
        
        // Save the updated file
        if (file_put_contents($zoho_js_file, $js_content)) {
            echo "Updated zoho-admin.js successfully.\n";
        } else {
            echo "Failed to update zoho-admin.js.\n";
        }
    } else {
        echo "zoho-admin.js already patched.\n";
    }
} else {
    echo "Not found at $zoho_js_file. Creating a new file...\n";
    
    // Create new zoho-admin.js
    $js_content = <<<'EOT'
jQuery(document).ready(function($) {
    $('#hvac-zoho-test-connection').on('click', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#hvac-zoho-test-connection-result');

        $button.prop('disabled', true);
        $result.html('<div class="notice notice-info"><p>' + hvac_zoho_admin.testing_connection + '</p></div>');

        $.ajax({
            url: hvac_zoho_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_zoho_test_connection',
                nonce: hvac_zoho_admin.nonce
            },
            success: function(response) {
                $button.prop('disabled', false);
                $result.empty();

                if (response.success) {
                    var successHtml = '<div class="notice notice-success">';
                    successHtml += '<p><strong>' + response.data.message + '</strong></p>';
                    
                    if (response.data.modules) {
                        successHtml += '<p>' + response.data.modules + '</p>';
                    }
                    
                    successHtml += '</div>';
                    
                    $result.html(successHtml);
                } else {
                    $result.html('<div class="notice notice-error"><p>Connection test failed. Please check the logs.</p></div>');
                }
            },
            error: function(response) {
                $button.prop('disabled', false);
                $result.empty();
                
                // Create detailed error display
                var errorHtml = '<div class="notice notice-error">';
                errorHtml += '<p><strong>' + response.data.message + ':</strong> ' + response.data.error + '</p>';
                
                // Add error code if available
                if (response.data.code) {
                    errorHtml += '<p><strong>Error Code:</strong> ' + response.data.code + '</p>';
                }
                
                // Add debugging info
                errorHtml += '<div class="hvac-zoho-debug-info">';
                // Add details if available
                if (response.data.details) {
                    errorHtml += '<p><strong>Details:</strong> ' + response.data.details + '</p>';
                }
                
                // Add raw response data if available
                if (response.data.raw) {
                    errorHtml += '<details>';
                    errorHtml += '<summary>Raw Response Data (click to expand)</summary>';
                    errorHtml += '<pre>' + JSON.stringify(JSON.parse(response.data.raw), null, 2) + '</pre>';
                    errorHtml += '</details>';
                }
                
                errorHtml += '</div>'; // Close debug info div
                errorHtml += '</div>'; // Close notice div
                
                $result.html(errorHtml);
            }
        });
    });
});
EOT;

    if (file_put_contents($zoho_js_file, $js_content)) {
        echo "Created zoho-admin.js successfully.\n";
    } else {
        echo "Failed to create zoho-admin.js.\n";
    }
}

echo "\n==========================================\n";
echo "Zoho CRM Integration Patcher completed\n";
echo "==========================================\n";
echo "Timestamp: " . date('Y-m-d H:i:s') . "\n\n";

echo "The following files were patched:\n";
echo "- " . $zoho_config_file . "\n";
echo "- " . $zoho_admin_file . "\n";
echo "- " . $zoho_auth_file . "\n";
echo "- " . $zoho_js_file . "\n";
echo "- " . $zoho_css_file . "\n";
echo "- " . $diagnostic_file . "\n";

echo "\nYou can now test the Zoho CRM integration in the WordPress admin panel.\n";
echo "If issues persist, check the logs at: " . $logs_dir . "/zoho-debug.log\n";
echo "You can also run the diagnostics tool at: /wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true\n";

// Exit to prevent any further output
exit();
EOPHP < /dev/null