<?php
/**
 * HVAC Zoho Direct Fix Script
 * 
 * This script creates all necessary files and enhances existing classes
 * to improve Zoho CRM integration error reporting.
 * 
 * Usage: Upload to the WordPress root directory and run via browser:
 * https://wordpress-974670-5399585.cloudwaysapps.com/zoho-direct-fix.php
 */

// Security - Only run in the browser with a confirmation parameter
if (php_sapi_name() === 'cli' || !isset($_GET['confirm']) || $_GET['confirm'] !== 'yes') {
    die('Access denied. This script must be run in a browser with ?confirm=yes parameter.');
}

// Set content type for better output
header('Content-Type: text/plain');

// Start output
echo "=============================================\n";
echo "HVAC Zoho CRM Integration Fix Script\n";
echo "=============================================\n";
echo "Started at: " . date('Y-m-d H:i:s') . "\n\n";

// Define the plugin path
$plugin_path = __DIR__ . '/wp-content/plugins/hvac-community-events';

// Step 1: Create necessary directories
echo "Step 1: Creating necessary directories...\n";
$dirs = [
    $plugin_path . '/includes/zoho',
    $plugin_path . '/includes/admin',
    $plugin_path . '/includes/logs',
    $plugin_path . '/assets/js',
    $plugin_path . '/assets/css'
];

foreach ($dirs as $dir) {
    if (!file_exists($dir)) {
        if (mkdir($dir, 0755, true)) {
            echo "  Created: $dir\n";
        } else {
            echo "  ERROR: Failed to create $dir\n";
        }
    } else {
        echo "  Already exists: $dir\n";
    }
}

// Make logs directory writable
chmod($plugin_path . '/includes/logs', 0777);
echo "  Made logs directory writable\n";

// Step 2: Create or update the zoho-config.php file
echo "\nStep 2: Creating zoho-config.php file...\n";
$zoho_config_path = $plugin_path . '/includes/zoho/zoho-config.php';
$zoho_config = <<<'EOT'
<?php
/**
 * Zoho CRM Configuration
 * 
 * This file contains the necessary constants for Zoho CRM integration.
 * Enhanced with environment variable loading and debugging.
 */

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

// Hard-code Zoho credentials for staging if not found in environment
if (!getenv('ZOHO_CLIENT_ID')) {
    putenv('ZOHO_CLIENT_ID=1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS');
    $_ENV['ZOHO_CLIENT_ID'] = '1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS';
}

if (!getenv('ZOHO_CLIENT_SECRET')) {
    putenv('ZOHO_CLIENT_SECRET=36913615664649dbf9198884bfd1096f7573c9ce2b');
    $_ENV['ZOHO_CLIENT_SECRET'] = '36913615664649dbf9198884bfd1096f7573c9ce2b';
}

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

// OAuth Client Credentials
define('ZOHO_CLIENT_ID', getenv('ZOHO_CLIENT_ID') ?: '1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS');
define('ZOHO_CLIENT_SECRET', getenv('ZOHO_CLIENT_SECRET') ?: '36913615664649dbf9198884bfd1096f7573c9ce2b');
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', getenv('ZOHO_REFRESH_TOKEN') ?: '');

// 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";
    
    // 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";
    
    // Log configuration details
    error_log($debug_info, 3, ZOHO_LOG_FILE);
}
EOT;

if (file_put_contents($zoho_config_path, $zoho_config)) {
    echo "  Created: zoho-config.php\n";
} else {
    echo "  ERROR: Failed to create zoho-config.php\n";
}

// Step 3: Create the diagnostics file
echo "\nStep 3: Creating diagnostics file...\n";
$diagnostics_path = $plugin_path . '/includes/zoho/diagnostics.php';
$diagnostics_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";
}

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_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";

// 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";

// Try to load .env file
if (function_exists('load_env_from_dotenv')) {
    echo "\nLoading .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";
} else {
    echo "\nload_env_from_dotenv() function not available!\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 20 lines of log file:\n";
    
    $log_lines = file(ZOHO_LOG_FILE);
    $last_lines = array_slice($log_lines, -20);
    
    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($diagnostics_path, $diagnostics_content)) {
    echo "  Created: diagnostics.php\n";
} else {
    echo "  ERROR: Failed to create diagnostics.php\n";
}

// Step 4: Create CSS file
echo "\nStep 4: Creating CSS file...\n";
$css_path = $plugin_path . '/assets/css/zoho-admin.css';
$css_content = <<<'EOT'
/* 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;
}
EOT;

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

// Step 5: Create JS file
echo "\nStep 5: Creating JS file...\n";
$js_path = $plugin_path . '/assets/js/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>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 {
                    // Create detailed error display
                    var errorHtml = '<div class="notice notice-error">';
                    errorHtml += '<p><strong>' + (response.data ? response.data.message : 'Connection failed') + ':</strong> ' + 
                                 (response.data ? response.data.error : 'Unknown error') + '</p>';
                    
                    // Add error code if available
                    if (response.data && 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 && response.data.details) {
                        errorHtml += '<p><strong>Details:</strong> ' + response.data.details + '</p>';
                    }
                    
                    // Add raw response data if available
                    if (response.data && response.data.raw) {
                        try {
                            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>';
                        } catch (e) {
                            errorHtml += '<p>Raw response data is available but could not be parsed: ' + e.message + '</p>';
                        }
                    }
                    
                    errorHtml += '</div>'; // Close debug info div
                    errorHtml += '</div>'; // Close notice div
                    
                    $result.html(errorHtml);
                }
            },
            error: function(response) {
                $button.prop('disabled', false);
                $result.empty();
                
                // Create detailed error display for AJAX errors
                var errorHtml = '<div class="notice notice-error">';
                errorHtml += '<p><strong>AJAX Error:</strong> The server returned an error or did not respond.</p>';
                
                // Add raw response if available
                if (response.responseText) {
                    errorHtml += '<div class="hvac-zoho-debug-info">';
                    errorHtml += '<details>';
                    errorHtml += '<summary>Error Response (click to expand)</summary>';
                    errorHtml += '<pre>' + response.responseText + '</pre>';
                    errorHtml += '</details>';
                    errorHtml += '</div>';
                }
                
                errorHtml += '</div>';
                
                $result.html(errorHtml);
            }
        });
    });
});
EOT;

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

// Step 6: Update or create the admin class
echo "\nStep 6: Updating admin class...\n";
$admin_class_path = $plugin_path . '/includes/admin/class-zoho-admin.php';

if (file_exists($admin_class_path)) {
    // Backup the existing file
    copy($admin_class_path, $admin_class_path . '.bak.' . date('YmdHis'));
    echo "  Created backup of admin class\n";
    
    // Read the current content
    $admin_content = file_get_contents($admin_class_path);
    
    // Check for test_connection method
    if (strpos($admin_content, 'public function test_connection') !== false) {
        // Replace the method
        $pattern = '/public function test_connection\(\) {.*?}/s';
        $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)
            ));
        }
    }';
        
        $admin_content = preg_replace($pattern, $replacement, $admin_content);
        
        if (file_put_contents($admin_class_path, $admin_content)) {
            echo "  Updated test_connection method in admin class\n";
        } else {
            echo "  ERROR: Failed to update admin class\n";
        }
    } else {
        echo "  WARNING: test_connection method not found in admin class\n";
    }
} else {
    echo "  WARNING: Admin class file not found - create a bare minimum version\n";
    
    // Create a minimal version of the admin class
    $admin_class_content = <<<'EOT'
<?php
/**
 * Zoho Admin
 *
 * @package HVAC Community Events
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * HVAC Zoho Admin class
 */
class HVAC_Zoho_Admin {
    /**
     * Instance
     *
     * @var HVAC_Zoho_Admin
     */
    protected static $instance = null;

    /**
     * Get instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    public function __construct() {
        // Register AJAX actions
        add_action('wp_ajax_hvac_zoho_test_connection', array($this, 'test_connection'));
        
        // Enqueue admin scripts
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }
    
    /**
     * Enqueue admin scripts
     */
    public function enqueue_scripts($hook) {
        // Only load on Zoho CRM admin page
        if (strpos($hook, 'hvac-zoho-crm') !== false) {
            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')
            ));
        }
    }

    /**
     * Test Zoho CRM 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
HVAC_Zoho_Admin::get_instance();
EOT;

    if (file_put_contents($admin_class_path, $admin_class_content)) {
        echo "  Created new admin class file\n";
    } else {
        echo "  ERROR: Failed to create admin class file\n";
    }
}

// Step 7: Update or create the auth class
echo "\nStep 7: Updating auth class...\n";
$auth_class_path = $plugin_path . '/includes/zoho/class-zoho-crm-auth.php';

if (file_exists($auth_class_path)) {
    // Backup the existing file
    copy($auth_class_path, $auth_class_path . '.bak.' . date('YmdHis'));
    echo "  Created backup of auth class\n";
    
    // Read the current content
    $auth_content = file_get_contents($auth_class_path);
    
    // Check if already has load_env_from_dotenv
    if (strpos($auth_content, 'load_env_from_dotenv') === false) {
        // Update the constructor to load environment variables
        $pattern = '/public function __construct\(\) {/';
        $replacement = 'public function __construct() {
        // Load environment variables from .env if available
        if (function_exists(\'load_env_from_dotenv\')) {
            load_env_from_dotenv();
        }';
        
        $auth_content = preg_replace($pattern, $replacement, $auth_content);
        
        // Add getter methods if they don't exist
        if (strpos($auth_content, 'get_client_id') === false) {
            $pattern = '/}(\s*)$/';
            $replacement = '
    /**
     * 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;
    }
}$1';
            
            $auth_content = preg_replace($pattern, $replacement, $auth_content);
        }
        
        if (file_put_contents($auth_class_path, $auth_content)) {
            echo "  Updated auth class\n";
        } else {
            echo "  ERROR: Failed to update auth class\n";
        }
    } else {
        echo "  Auth class already has environment variable loading - skipping update\n";
    }
} else {
    echo "  WARNING: Auth class file not found - create a bare minimum version\n";
    
    // Create a minimal version of the auth class
    $auth_class_content = <<<'EOT'
<?php
/**
 * Zoho CRM Auth
 *
 * @package HVAC Community Events
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * HVAC Zoho CRM Auth class
 */
class HVAC_Zoho_CRM_Auth {
    /**
     * Instance
     *
     * @var HVAC_Zoho_CRM_Auth
     */
    protected static $instance = null;

    /**
     * Client ID
     *
     * @var string
     */
    private $client_id;

    /**
     * Client Secret
     *
     * @var string
     */
    private $client_secret;

    /**
     * Redirect URI
     *
     * @var string
     */
    private $redirect_uri;

    /**
     * Refresh Token
     *
     * @var string
     */
    private $refresh_token;

    /**
     * Access Token
     *
     * @var string
     */
    private $access_token;

    /**
     * Access Token Expiry
     *
     * @var int
     */
    private $access_token_expiry;

    /**
     * Get instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    public function __construct() {
        // Load environment variables from .env if available
        if (function_exists('load_env_from_dotenv')) {
            load_env_from_dotenv();
        }
        
        // Include Zoho CRM config
        require_once dirname(__FILE__) . '/zoho-config.php';
        
        // Set credentials
        $this->client_id = defined('ZOHO_CLIENT_ID') ? ZOHO_CLIENT_ID : '';
        $this->client_secret = defined('ZOHO_CLIENT_SECRET') ? ZOHO_CLIENT_SECRET : '';
        $this->redirect_uri = defined('ZOHO_REDIRECT_URI') ? ZOHO_REDIRECT_URI : '';
        $this->refresh_token = defined('ZOHO_REFRESH_TOKEN') ? ZOHO_REFRESH_TOKEN : '';
        
        // Get access token if refresh token exists
        if (!empty($this->refresh_token)) {
            $this->get_access_token();
        }
    }

    /**
     * Get access token
     *
     * @return string
     */
    public function get_access_token() {
        // Check if we have a valid access token
        if (!empty($this->access_token) && $this->access_token_expiry > time()) {
            return $this->access_token;
        }
        
        // If we have a refresh token, try to get a new access token
        if (!empty($this->refresh_token)) {
            $response = $this->refresh_access_token();
            
            if (isset($response['access_token'])) {
                $this->access_token = $response['access_token'];
                $this->access_token_expiry = time() + $response['expires_in'];
                return $this->access_token;
            }
        }
        
        // Log the error
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            $log_message = "[" . date('Y-m-d H:i:s') . "] Failed to get access token\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Refresh token: " . (empty($this->refresh_token) ? 'EMPTY' : substr($this->refresh_token, 0, 5) . '...') . "\n";
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log($log_message, 3, ZOHO_LOG_FILE);
            }
        }
        
        return '';
    }

    /**
     * Refresh access token
     *
     * @return array
     */
    public function refresh_access_token() {
        $url = ZOHO_ACCOUNTS_URL . '/oauth/v2/token';
        $args = array(
            'method' => 'POST',
            'headers' => array(
                'Content-Type' => 'application/x-www-form-urlencoded'
            ),
            'body' => array(
                'refresh_token' => $this->refresh_token,
                'client_id' => $this->client_id,
                'client_secret' => $this->client_secret,
                'grant_type' => 'refresh_token'
            )
        );
        
        // Log the request
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            $log_message = "[" . date('Y-m-d H:i:s') . "] Refreshing access token\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] URL: $url\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Client ID: " . substr($this->client_id, 0, 5) . "...\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Client Secret: " . substr($this->client_secret, 0, 5) . "...\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Refresh Token: " . substr($this->refresh_token, 0, 5) . "...\n";
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log($log_message, 3, ZOHO_LOG_FILE);
            }
        }
        
        $response = wp_remote_post($url, $args);
        
        if (is_wp_error($response)) {
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                $log_message = "[" . date('Y-m-d H:i:s') . "] WP Error: " . $response->get_error_message() . "\n";
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log($log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            return array(
                'error' => $response->get_error_message()
            );
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['error'])) {
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                $log_message = "[" . date('Y-m-d H:i:s') . "] Zoho Error: " . $body['error'] . "\n";
                
                if (isset($body['error_description'])) {
                    $log_message .= "[" . date('Y-m-d H:i:s') . "] Error Description: " . $body['error_description'] . "\n";
                }
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log($log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            return array(
                'error' => isset($body['error_description']) ? $body['error_description'] : $body['error']
            );
        }
        
        return $body;
    }

    /**
     * Make API request
     *
     * @param string $endpoint
     * @param array $args
     * @return array
     */
    public function make_api_request($endpoint, $args = array()) {
        // Get access token
        $access_token = $this->get_access_token();
        
        if (empty($access_token)) {
            return array(
                'error' => 'No access token available'
            );
        }
        
        // Set default args
        $defaults = array(
            'method' => 'GET',
            'headers' => array(
                'Authorization' => 'Zoho-oauthtoken ' . $access_token,
                'Content-Type' => 'application/json'
            )
        );
        
        $args = wp_parse_args($args, $defaults);
        
        // Convert body to JSON if it's an array
        if (isset($args['body']) && is_array($args['body'])) {
            $args['body'] = json_encode($args['body']);
        }
        
        $url = ZOHO_API_BASE_URL . '/' . ltrim($endpoint, '/');
        
        // Log the request
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            $log_message = "[" . date('Y-m-d H:i:s') . "] Making API request\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] URL: $url\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Method: " . $args['method'] . "\n";
            
            if (isset($args['body'])) {
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Body: " . $args['body'] . "\n";
            }
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log($log_message, 3, ZOHO_LOG_FILE);
            }
        }
        
        $response = wp_remote_request($url, $args);
        
        if (is_wp_error($response)) {
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                $log_message = "[" . date('Y-m-d H:i:s') . "] WP Error: " . $response->get_error_message() . "\n";
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log($log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            return array(
                'error' => $response->get_error_message()
            );
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $status = wp_remote_retrieve_response_code($response);
        
        // Log the response
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            $log_message = "[" . date('Y-m-d H:i:s') . "] API Response\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Status: $status\n";
            $log_message .= "[" . date('Y-m-d H:i:s') . "] Body: " . wp_remote_retrieve_body($response) . "\n";
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log($log_message, 3, ZOHO_LOG_FILE);
            }
        }
        
        if ($status < 200 || $status >= 300) {
            return array(
                'error' => isset($body['message']) ? $body['message'] : 'API request failed with status ' . $status,
                'code' => $status,
                'details' => $body
            );
        }
        
        return $body;
    }

    /**
     * Get modules
     *
     * @return array
     */
    public function get_modules() {
        return $this->make_api_request('settings/modules');
    }
    
    /**
     * 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;

    if (file_put_contents($auth_class_path, $auth_class_content)) {
        echo "  Created new auth class file\n";
    } else {
        echo "  ERROR: Failed to create auth class file\n";
    }
}

// Step 8: Clear the WordPress cache
echo "\nStep 8: Attempting to clear WordPress cache...\n";
if (function_exists('wp_cache_flush')) {
    wp_cache_flush();
    echo "  Cleared WordPress object cache\n";
} else {
    echo "  WordPress functions not available - cache not cleared\n";
}

// Summary
echo "\n=============================================\n";
echo "Zoho CRM Integration Fix Complete\n";
echo "=============================================\n";
echo "The following files have been created or updated:\n";
echo "1. zoho-config.php - Added environment variable loading\n";
echo "2. diagnostics.php - Added diagnostic tools\n";
echo "3. zoho-admin.css - Added CSS for error display\n";
echo "4. zoho-admin.js - Enhanced error reporting in JS\n";
echo "5. class-zoho-admin.php - Enhanced test_connection method\n";
echo "6. class-zoho-crm-auth.php - Added environment variable loading\n";
echo "\nTo test the integration:\n";
echo "1. Go to Events > Zoho CRM Sync in the WordPress admin\n";
echo "2. Click the 'Test Connection' button\n";
echo "3. You should now see detailed error information\n";
echo "\nTo run diagnostics, visit:\n";
echo "https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true\n";
echo "\nCompleted at: " . date('Y-m-d H:i:s') . "\n";
echo "=============================================\n";