#!/bin/bash

# Simplified Zoho CRM Integration Fix Deployment Script
# This script deploys the core Zoho fix files directly

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Load environment variables
source "$(dirname "$0")/../.env"

# Set variables
REMOTE_HOST="${UPSKILL_STAGING_IP}"
REMOTE_USER="${UPSKILL_STAGING_SSH_USER}"
REMOTE_PASS="${UPSKILL_STAGING_PASS}"
REMOTE_PATH="/home/974670.cloudwaysapps.com/uberrxmprk/public_html"
PLUGINS_PATH="${REMOTE_PATH}/wp-content/plugins"
MAIN_PLUGIN="hvac-community-events"
PLUGIN_PATH="${PLUGINS_PATH}/${MAIN_PLUGIN}"

echo -e "${YELLOW}=== Simplified Zoho CRM Integration Fix Deployment ===${NC}"
echo -e "${YELLOW}Target: ${REMOTE_USER}@${REMOTE_HOST}:${PLUGIN_PATH}${NC}"

# Step 1: Ensure the directories exist
echo -e "${YELLOW}Step 1: Creating required directories...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" <<EOSSH
mkdir -p $PLUGIN_PATH/includes/zoho
mkdir -p $PLUGIN_PATH/includes/admin
mkdir -p $PLUGIN_PATH/includes/logs
mkdir -p $PLUGIN_PATH/assets/js
mkdir -p $PLUGIN_PATH/assets/css
chmod -R 755 $PLUGIN_PATH/includes/logs
EOSSH

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to create required directories.${NC}"
    exit 1
fi

# Step 2: Create the zoho-config.php file
echo -e "${YELLOW}Step 2: Creating zoho-config.php...${NC}"
ZOHO_CONFIG=$(mktemp)
cat > "$ZOHO_CONFIG" << 'EOPHP'
<?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);
}
EOPHP

sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$ZOHO_CONFIG" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/includes/zoho/zoho-config.php"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to upload Zoho config file.${NC}"
    rm "$ZOHO_CONFIG"
    exit 1
fi

rm "$ZOHO_CONFIG"
echo -e "${GREEN}Zoho config file uploaded successfully.${NC}"

# Step 3: Create the diagnostics.php file
echo -e "${YELLOW}Step 3: Creating diagnostics.php...${NC}"
DIAGNOSTICS_FILE=$(mktemp)
cat > "$DIAGNOSTICS_FILE" << 'EOPHP'
<?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";

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

// Plugin Path
$plugin_dir = dirname(dirname(dirname(__FILE__)));
echo "Plugin Directory: $plugin_dir\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();
EOPHP

sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$DIAGNOSTICS_FILE" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/includes/zoho/diagnostics.php"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to upload diagnostics file.${NC}"
    rm "$DIAGNOSTICS_FILE"
    exit 1
fi

rm "$DIAGNOSTICS_FILE"
echo -e "${GREEN}Diagnostics file uploaded successfully.${NC}"

# Step 4: Create the CSS file
echo -e "${YELLOW}Step 4: Creating CSS file...${NC}"
CSS_FILE=$(mktemp)
cat > "$CSS_FILE" << 'EOCSS'
/* 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;
}
EOCSS

sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$CSS_FILE" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/assets/css/zoho-admin.css"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to upload CSS file.${NC}"
    rm "$CSS_FILE"
    exit 1
fi

rm "$CSS_FILE"
echo -e "${GREEN}CSS file uploaded successfully.${NC}"

# Step 5: Create the JS file
echo -e "${YELLOW}Step 5: Creating JS file...${NC}"
JS_FILE=$(mktemp)
cat > "$JS_FILE" << 'EOJS'
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);
            }
        });
    });
});
EOJS

sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$JS_FILE" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/assets/js/zoho-admin.js"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to upload JS file.${NC}"
    rm "$JS_FILE"
    exit 1
fi

rm "$JS_FILE"
echo -e "${GREEN}JS file uploaded successfully.${NC}"

# Step 6: Create the PHP patch script
echo -e "${YELLOW}Step 6: Creating PHP patch script...${NC}"
PATCH_SCRIPT=$(mktemp)
cat > "$PATCH_SCRIPT" << 'EOPHP'
<?php
/**
 * HVAC Zoho Patch Script
 * 
 * This script patches the Zoho admin class to show detailed errors and
 * enhances the Zoho auth class to load environment variables.
 */

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

// 1. Create directories if they don't exist
$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)) {
        mkdir($dir, 0755, true);
        echo "Created directory: $dir\n";
    } else {
        echo "Directory exists: $dir\n";
    }
}

// 2. Check for the Admin class
$admin_class_path = $plugin_path . '/includes/admin/class-zoho-admin.php';
if (file_exists($admin_class_path)) {
    // Create backup
    copy($admin_class_path, $admin_class_path . '.bak.' . date('YmdHis'));
    echo "Created backup of admin class\n";
    
    // Read the file
    $admin_content = file_get_contents($admin_class_path);
    
    // If the test_connection method exists, enhance it
    if (strpos($admin_content, 'public function test_connection') !== false) {
        $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)
            ));
        }
    }';
        
        $modified_admin_content = preg_replace($pattern, $replacement, $admin_content);
        
        if ($modified_admin_content !== $admin_content) {
            file_put_contents($admin_class_path, $modified_admin_content);
            echo "Enhanced the test_connection method in the admin class\n";
        } else {
            echo "Failed to enhance the test_connection method. Pattern not found.\n";
        }
    } else {
        echo "The test_connection method was not found in the admin class\n";
    }
} else {
    echo "Admin class not found at: $admin_class_path\n";
}

// 3. Check for the Auth class
$auth_class_path = $plugin_path . '/includes/zoho/class-zoho-crm-auth.php';
if (file_exists($auth_class_path)) {
    // Create backup
    copy($auth_class_path, $auth_class_path . '.bak.' . date('YmdHis'));
    echo "Created backup of auth class\n";
    
    // Read the file
    $auth_content = file_get_contents($auth_class_path);
    
    // Enhance the constructor to load environment variables
    $constructor_pattern = '/public function __construct\(\) {/';
    $constructor_replacement = 'public function __construct() {
        // Load environment variables from .env if available
        if (function_exists(\'load_env_from_dotenv\')) {
            load_env_from_dotenv();
        }';
    
    $modified_auth_content = preg_replace($constructor_pattern, $constructor_replacement, $auth_content);
    
    // Add getter methods if they don't exist
    if (strpos($modified_auth_content, 'get_client_id') === false) {
        $class_end_pattern = '/}(\s*)$/';
        $getters = '
    /**
     * 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';
        
        $modified_auth_content = preg_replace($class_end_pattern, $getters, $modified_auth_content);
        echo "Added getter methods to the auth class\n";
    }
    
    // Save the modified auth class
    if ($modified_auth_content !== $auth_content) {
        file_put_contents($auth_class_path, $modified_auth_content);
        echo "Enhanced the auth class to load environment variables\n";
    } else {
        echo "Failed to enhance the auth class\n";
    }
} else {
    echo "Auth class not found at: $auth_class_path\n";
}

echo "Patch completed\n";
EOPHP

sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$PATCH_SCRIPT" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/hvac-zoho-patch.php"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to upload patch script.${NC}"
    rm "$PATCH_SCRIPT"
    exit 1
fi

# Step 7: Run the patch script
echo -e "${YELLOW}Step 7: Running the patch script...${NC}"
PATCH_RESULT=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && php hvac-zoho-patch.php")
echo "$PATCH_RESULT"

# Clean up the patch script
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "rm -f $REMOTE_PATH/hvac-zoho-patch.php"
rm "$PATCH_SCRIPT"

# Step 8: Clear WordPress cache
echo -e "${YELLOW}Step 8: Clearing WordPress cache...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && wp cache flush"

# Summary
echo -e "${GREEN}=== Zoho CRM Integration Fix Deployed Successfully! ===${NC}"
echo -e "${YELLOW}The following steps were completed:${NC}"
echo -e "1. Created required directories"
echo -e "2. Added zoho-config.php with environment variable loading"
echo -e "3. Created diagnostics.php for troubleshooting"
echo -e "4. Added CSS styling for debug information"
echo -e "5. Enhanced the zoho-admin.js file for better error reporting"
echo -e "6. Patched the PHP classes for better logging and error handling"
echo -e "7. Cleared WordPress cache"

echo -e "${YELLOW}You can now test the Zoho CRM integration in the WordPress admin panel.${NC}"
echo -e "${YELLOW}Go to Events > Zoho CRM Sync and click the 'Test Connection' button.${NC}"
echo -e "${YELLOW}If issues persist, run the diagnostics tool at:${NC}"
echo -e "${YELLOW}https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true${NC}"

exit 0