<?php
/**
 * Standalone Zoho CRM integration patcher
 * 
 * This script patches the Zoho CRM integration files to fix environment
 * variable loading and enhance debug reporting.
 */

// Set up paths
$plugin_path = __DIR__ . '/../wordpress/wp-content/plugins/hvac-community-events';
$zoho_admin_path = $plugin_path . '/includes/admin/class-zoho-admin.php';
$zoho_auth_path = $plugin_path . '/includes/zoho/class-zoho-crm-auth.php';
$zoho_config_path = $plugin_path . '/includes/zoho/zoho-config.php';
$zoho_js_path = $plugin_path . '/assets/js/zoho-admin.js';
$zoho_css_path = $plugin_path . '/assets/css/zoho-admin.css';
$log_dir = $plugin_path . '/includes/logs';

// Create log directory if it doesn't exist
if (!file_exists($log_dir)) {
    mkdir($log_dir, 0755, true);
    echo "Created log directory: $log_dir\n";
}

// Update Zoho CRM Auth class to add environment loading
if (file_exists($zoho_auth_path)) {
    $auth_content = file_get_contents($zoho_auth_path);
    
    // Check if already patched
    if (strpos($auth_content, 'load_env_from_dotenv') === false) {
        // Make a backup
        file_put_contents($zoho_auth_path . '.bak.' . date('YmdHis'), $auth_content);
        
        // Find the class definition
        $pattern = '/class HVAC_Zoho_CRM_Auth/';
        
        // Add method to load environment variables from .env file
        $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 in the file
        $auth_content = preg_replace($pattern, $replacement, $auth_content);
        
        // Add environment loading call in the constructor
        $constructor_pattern = '/public function __construct\(\) {/';
        $constructor_replacement = "public function __construct() {
        // Load environment variables from .env if available
        load_env_from_dotenv();";
        
        $auth_content = preg_replace($constructor_pattern, $constructor_replacement, $auth_content);
        
        // Add enhanced 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);
            }
        }";
        
        $auth_content = preg_replace($api_pattern, $api_replacement, $auth_content);
        
        // Add error handling for 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);
            }
        }";
        
        $auth_content = preg_replace($response_pattern, $response_replacement, $auth_content);
        
        // Save the updated file
        file_put_contents($zoho_auth_path, $auth_content);
        echo "Updated Zoho CRM Auth class with environment loading and enhanced logging.\n";
    } else {
        echo "Zoho CRM Auth class already patched.\n";
    }
} else {
    echo "Warning: Zoho CRM Auth class file not found at $zoho_auth_path\n";
}

// Update Zoho Admin class to add better error reporting
if (file_exists($zoho_admin_path)) {
    $admin_content = file_get_contents($zoho_admin_path);
    
    // Check if already patched
    if (strpos($admin_content, 'ZOHO_DEBUG_MODE') === false) {
        // Make a backup
        file_put_contents($zoho_admin_path . '.bak.' . date('YmdHis'), $admin_content);
        
        // 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
        file_put_contents($zoho_admin_path, $admin_content);
        echo "Updated Zoho Admin class with enhanced error reporting.\n";
    } else {
        echo "Zoho Admin class already patched.\n";
    }
} else {
    echo "Warning: Zoho Admin class file not found at $zoho_admin_path\n";
}

// Update Zoho Admin JavaScript to display detailed error information
if (file_exists($zoho_js_path)) {
    $js_content = file_get_contents($zoho_js_path);
    
    // Check if already patched
    if (strpos($js_content, 'hvac-zoho-debug-info') === false) {
        // Make a backup
        file_put_contents($zoho_js_path . '.bak.' . date('YmdHis'), $js_content);
        
        // Find the error handling section
        $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 in the file
        $js_content = preg_replace($pattern, $replacement, $js_content);
        
        // Save the updated file
        file_put_contents($zoho_js_path, $js_content);
        echo "Updated Zoho Admin JavaScript with enhanced error display.\n";
    } else {
        echo "Zoho Admin JavaScript already patched.\n";
    }
} else {
    echo "Warning: Zoho Admin JavaScript file not found at $zoho_js_path\n";
}

// Add CSS styling for the debug information
if (file_exists($zoho_css_path)) {
    $css_content = file_get_contents($zoho_css_path);
    
    // Check if already patched
    if (strpos($css_content, 'hvac-zoho-debug-info') === false) {
        // Make a backup
        file_put_contents($zoho_css_path . '.bak.' . date('YmdHis'), $css_content);
        
        // Add styling for debug information
        $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
        file_put_contents($zoho_css_path, $css_content);
        echo "Updated Zoho Admin CSS with debug information styling.\n";
    } else {
        echo "Zoho Admin CSS already patched.\n";
    }
} else {
    echo "Warning: Zoho Admin CSS file not found at $zoho_css_path\n";
}

// Update Zoho config file to add environment loading
if (file_exists($zoho_config_path)) {
    $config_content = file_get_contents($zoho_config_path);
    
    // Check if already patched
    if (strpos($config_content, 'load_env_from_dotenv') === false) {
        // Make a backup
        file_put_contents($zoho_config_path . '.bak.' . date('YmdHis'), $config_content);
        
        // Extract credentials
        preg_match('/define\\s*\\(\\s*[\'"]ZOHO_CLIENT_ID[\'"]\\s*,\\s*(.*?)\\s*\\)\\s*;/s', $config_content, $client_id_match);
        preg_match('/define\\s*\\(\\s*[\'"]ZOHO_CLIENT_SECRET[\'"]\\s*,\\s*(.*?)\\s*\\)\\s*;/s', $config_content, $client_secret_match);
        preg_match('/define\\s*\\(\\s*[\'"]ZOHO_REFRESH_TOKEN[\'"]\\s*,\\s*(.*?)\\s*\\)\\s*;/s', $config_content, $refresh_token_match);
        
        $client_id = isset($client_id_match[1]) ? $client_id_match[1] : "getenv('ZOHO_CLIENT_ID') ?: ''";
        $client_secret = isset($client_secret_match[1]) ? $client_secret_match[1] : "getenv('ZOHO_CLIENT_SECRET') ?: ''";
        $refresh_token = isset($refresh_token_match[1]) ? $refresh_token_match[1] : "getenv('ZOHO_REFRESH_TOKEN') ?: ''";
        
        // Create new config with env loading
        $new_config = <<<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);
}

// OAuth Client Credentials
// IMPORTANT: You need to fill these values with your Zoho OAuth credentials
define('ZOHO_CLIENT_ID', $client_id);
define('ZOHO_CLIENT_SECRET', $client_secret);
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', $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";
    $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;
        
        // Save the updated file
        file_put_contents($zoho_config_path, $new_config);
        echo "Updated Zoho config file with environment loading and enhanced debugging.\n";
    } else {
        echo "Zoho config file already patched.\n";
    }
} else {
    echo "Warning: Zoho config file not found at $zoho_config_path\n";
}

// Create diagnostics script
$diagnostics_path = $plugin_path . '/includes/zoho/diagnostics.php';
if (!file_exists($diagnostics_path)) {
    $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 !== '/' && !$found) {
        if (file_exists($dir . '/wp-config.php')) {
            return $dir;
        }
        $dir = dirname($dir);
    }
    return 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 "Server Protocol: " . $_SERVER['SERVER_PROTOCOL'] . "\n";
echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "\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
$plugin_data = get_file_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 "File Permissions\n";
echo "==========================================\n";

// Check permissions for important directories
$dirs_to_check = [
    $plugin_dir,
    $plugin_dir . '/includes',
    $plugin_dir . '/includes/zoho',
    $plugin_dir . '/includes/admin',
    $plugin_dir . '/includes/logs',
    $plugin_dir . '/assets',
    $plugin_dir . '/assets/js',
    $plugin_dir . '/assets/css',
];

foreach ($dirs_to_check as $dir) {
    echo "Directory: $dir\n";
    echo "  Exists: " . (file_exists($dir) ? 'Yes' : 'No') . "\n";
    if (file_exists($dir)) {
        echo "  Readable: " . (is_readable($dir) ? 'Yes' : 'No') . "\n";
        echo "  Writable: " . (is_writable($dir) ? 'Yes' : 'No') . "\n";
        echo "  Permissions: " . substr(sprintf('%o', fileperms($dir)), -4) . "\n";
        echo "  Owner: " . posix_getpwuid(fileowner($dir))['name'] . "\n";
        echo "  Group: " . posix_getgrgid(filegroup($dir))['name'] . "\n";
    }
    echo "\n";
}

// List files in zoho directory
$zoho_dir = $plugin_dir . '/includes/zoho';
if (file_exists($zoho_dir) && is_readable($zoho_dir)) {
    echo "Files in Zoho directory:\n";
    $files = scandir($zoho_dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $file_path = $zoho_dir . '/' . $file;
            echo "  $file: " . substr(sprintf('%o', fileperms($file_path)), -4) . " " . 
                 posix_getpwuid(fileowner($file_path))['name'] . ":" . 
                 posix_getgrgid(filegroup($file_path))['name'] . " " . 
                 filesize($file_path) . " bytes\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 ? "Success (Token: " . substr($token, 0, 10) . "...)" : "Failed") . "\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;
    
    file_put_contents($diagnostics_path, $diagnostics_content);
    echo "Created Zoho CRM diagnostics script at $diagnostics_path\n";
} else {
    echo "Zoho CRM diagnostics script already exists at $diagnostics_path\n";
}

// Create local diagnostics file
$check_permissions_path = $plugin_path . '/includes/zoho/check-permissions.php';
if (!file_exists($check_permissions_path)) {
    $check_permissions_content = <<<EOT
<?php
/**
 * Zoho CRM Integration - File Permissions Check
 * 
 * This script checks file and directory permissions related to Zoho CRM integration.
 * Access via URL with security parameter: ?check=true
 */

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

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

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

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

// Check permissions for important directories
$dirs_to_check = [
    $plugin_dir,
    $plugin_dir . '/includes',
    $plugin_dir . '/includes/zoho',
    $plugin_dir . '/includes/admin',
    $plugin_dir . '/includes/logs',
    $plugin_dir . '/assets',
    $plugin_dir . '/assets/js',
    $plugin_dir . '/assets/css',
];

foreach ($dirs_to_check as $dir) {
    echo "Directory: $dir\n";
    if (!file_exists($dir)) {
        echo "  DOES NOT EXIST! Attempting to create...\n";
        if (mkdir($dir, 0755, true)) {
            echo "  Created successfully.\n";
        } else {
            echo "  FAILED to create!\n";
        }
    } else {
        echo "  Exists: Yes\n";
        echo "  Readable: " . (is_readable($dir) ? 'Yes' : 'No') . "\n";
        echo "  Writable: " . (is_writable($dir) ? 'Yes' : 'No') . "\n";
        
        if (!is_writable($dir)) {
            echo "  WARNING: Directory is not writable. Attempting to fix permissions...\n";
            if (chmod($dir, 0755)) {
                echo "  Permissions fixed successfully.\n";
                echo "  Writable now: " . (is_writable($dir) ? 'Yes' : 'No') . "\n";
            } else {
                echo "  FAILED to fix permissions!\n";
            }
        }
    }
    echo "\n";
}

// List of important files to check
$files_to_check = [
    $plugin_dir . '/includes/zoho/zoho-config.php',
    $plugin_dir . '/includes/zoho/class-zoho-crm-auth.php',
    $plugin_dir . '/includes/admin/class-zoho-admin.php',
    $plugin_dir . '/assets/js/zoho-admin.js',
    $plugin_dir . '/assets/css/zoho-admin.css',
];

foreach ($files_to_check as $file) {
    echo "File: $file\n";
    if (!file_exists($file)) {
        echo "  DOES NOT EXIST!\n";
    } else {
        echo "  Exists: Yes\n";
        echo "  Readable: " . (is_readable($file) ? 'Yes' : 'No') . "\n";
        echo "  Writable: " . (is_writable($file) ? 'Yes' : 'No') . "\n";
        echo "  Size: " . filesize($file) . " bytes\n";
        
        if (!is_readable($file) || !is_writable($file)) {
            echo "  WARNING: File has incorrect permissions. Attempting to fix...\n";
            if (chmod($file, 0644)) {
                echo "  Permissions fixed successfully.\n";
                echo "  Readable now: " . (is_readable($file) ? 'Yes' : 'No') . "\n";
                echo "  Writable now: " . (is_writable($file) ? 'Yes' : 'No') . "\n";
            } else {
                echo "  FAILED to fix permissions!\n";
            }
        }
    }
    echo "\n";
}

// Create log directory if it doesn't exist
$log_dir = $plugin_dir . '/includes/logs';
if (!file_exists($log_dir)) {
    echo "Log directory does not exist. Attempting to create...\n";
    if (mkdir($log_dir, 0755, true)) {
        echo "Log directory created successfully at: $log_dir\n";
    } else {
        echo "FAILED to create log directory!\n";
    }
} else {
    echo "Log directory exists at: $log_dir\n";
    echo "Log directory writable: " . (is_writable($log_dir) ? 'Yes' : 'No') . "\n";
    
    // Try to create a test log file
    $test_log_file = $log_dir . '/test-' . time() . '.log';
    echo "Testing log file creation at: $test_log_file\n";
    
    if (file_put_contents($test_log_file, "Test log entry at " . date('Y-m-d H:i:s') . "\n")) {
        echo "Test log file created successfully.\n";
        unlink($test_log_file);
        echo "Test log file removed.\n";
    } else {
        echo "FAILED to create test log file!\n";
    }
}

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

// Exit to prevent any further output
exit();
EOT;
    
    file_put_contents($check_permissions_path, $check_permissions_content);
    echo "Created file permissions check script at $check_permissions_path\n";
} else {
    echo "File permissions check script already exists at $check_permissions_path\n";
}

echo "\nZoho CRM integration patching completed successfully!\n";
echo "You can now test the connection in the WordPress admin panel.\n";
echo "If issues persist, access the diagnostic tools at:\n";
echo "- Diagnostics: https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true\n";
echo "- Permissions Check: https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/check-permissions.php?check=true\n";
EOF < /dev/null