#!/bin/bash
#
# HVAC Community Events Plugin Deployment Script with Domain Updates
# This script deploys the plugin with updated domain references

# Exit on error
set -e

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

# Check if we're in the wordpress-dev directory
if [[ ! -d "wordpress/wp-content/plugins/hvac-community-events" ]]; then
    echo -e "${RED}Error: Must run from wordpress-dev directory${NC}"
    exit 1
fi

# Define variables
PLUGIN_NAME="hvac-community-events"
PLUGIN_DIR="wordpress/wp-content/plugins/${PLUGIN_NAME}"
TEMP_DIR="/tmp/hvac-domain-fix"
PACKAGE_NAME="hvac-community-events-domain-fix.zip"
NEW_DOMAIN="upskill-staging.measurequick.com"
OLD_DOMAIN="wordpress-974670-5399585.cloudwaysapps.com"

# Create build directory
echo -e "${YELLOW}Step 1: Creating build directory...${NC}"
mkdir -p "${TEMP_DIR}"
rm -rf "${TEMP_DIR}/${PLUGIN_NAME}"
mkdir -p "${TEMP_DIR}/${PLUGIN_NAME}"

# Copy plugin files
echo -e "${YELLOW}Step 2: Copying plugin files...${NC}"
cp -r "${PLUGIN_DIR}"/* "${TEMP_DIR}/${PLUGIN_NAME}/"

# Update zoho-config.php with dynamic site URL detection
echo -e "${YELLOW}Step 3: Updating Zoho configuration with dynamic domain detection...${NC}"
ZOHO_CONFIG="${TEMP_DIR}/${PLUGIN_NAME}/includes/zoho/zoho-config.php"

if [[ -f "${ZOHO_CONFIG}" ]]; then
    # Create backup
    cp "${ZOHO_CONFIG}" "${ZOHO_CONFIG}.bak"
    
    # Replace hardcoded domain in redirect URI with dynamic detection
    sed -i.tmp "s|define('ZOHO_REDIRECT_URI', 'https://${OLD_DOMAIN}/oauth/callback');|// Dynamically determine site URL for Zoho redirection\n\$site_url = function_exists('get_site_url') ? get_site_url() : (getenv('UPSKILL_STAGING_URL') ?: 'https://${NEW_DOMAIN}');\ndefine('ZOHO_REDIRECT_URI', \$site_url . '/wp-admin/admin-ajax.php?action=zoho_oauth_callback');|g" "${ZOHO_CONFIG}"
    
    # Enhance debugging
    sed -i.tmp "s|define('ZOHO_DEBUG_MODE', true);|define('ZOHO_DEBUG_MODE', true);\n\n// Add site URL to config for domain migration debugging\nif (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {\n    \$debug_info = \"Site URL used for Zoho: \" . \$site_url . \"\\n\";\n    \$debug_info .= \"ZOHO_REDIRECT_URI: \" . ZOHO_REDIRECT_URI . \"\\n\";\n    error_log(\$debug_info, 3, ZOHO_LOG_FILE);\n}|g" "${ZOHO_CONFIG}"
    
    # Remove temp files
    rm -f "${ZOHO_CONFIG}.tmp"
    echo -e "${GREEN}✓ Zoho config updated with dynamic domain detection${NC}"
else
    echo -e "${YELLOW}⚠ Zoho config file not found, creating new one...${NC}"
    mkdir -p "${TEMP_DIR}/${PLUGIN_NAME}/includes/zoho"
    
    cat > "${ZOHO_CONFIG}" << 'EOPHP'
<?php
/**
 * Zoho CRM Configuration
 * 
 * This file contains the necessary constants for Zoho CRM integration.
 * Enhanced with environment variable loading and dynamic domain detection.
 */

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

// Dynamically determine site URL for Zoho redirection
$site_url = function_exists('get_site_url') ? get_site_url() : (getenv('UPSKILL_STAGING_URL') ?: 'https://upskill-staging.measurequick.com');

// 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', $site_url . '/wp-admin/admin-ajax.php?action=zoho_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 site URL to config for domain migration debugging
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
    $debug_info = "Site URL used for Zoho: " . $site_url . "\n";
    $debug_info .= "ZOHO_REDIRECT_URI: " . ZOHO_REDIRECT_URI . "\n";
    error_log($debug_info, 3, ZOHO_LOG_FILE);
}

// 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";
        
        // Check for known staging domains
        $known_staging_domains = [
            'wordpress-974670-5399585.cloudwaysapps.com',
            'upskill-staging.measurequick.com'
        ];
        
        $site_url = get_site_url();
        $is_staging = false;
        
        foreach ($known_staging_domains as $domain) {
            if (strpos($site_url, $domain) !== false) {
                $is_staging = true;
                break;
            }
        }
        
        $debug_info .= "[$timestamp] Staging mode: " . ($is_staging ? '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";
    $debug_info .= "[$timestamp]   - _ENV['UPSKILL_STAGING_URL']: " . (isset($_ENV['UPSKILL_STAGING_URL']) ? $_ENV['UPSKILL_STAGING_URL'] : 'Not set') . "\n";
    
    // Log configuration details
    error_log($debug_info, 3, ZOHO_LOG_FILE);
}
EOPHP
    echo -e "${GREEN}✓ New Zoho config created with dynamic domain detection${NC}"
fi

# Update class-zoho-admin.php with enhanced error reporting
echo -e "${YELLOW}Step 4: Updating Zoho admin class with enhanced error reporting...${NC}"
ZOHO_ADMIN="${TEMP_DIR}/${PLUGIN_NAME}/includes/admin/class-zoho-admin.php"

if [[ -f "${ZOHO_ADMIN}" ]]; then
    # Create backup
    cp "${ZOHO_ADMIN}" "${ZOHO_ADMIN}.bak"
    
    # Check if the file contains the test_connection method
    if grep -q "public function test_connection" "${ZOHO_ADMIN}"; then
        # Extract the test_connection method
        TEST_CONN_METHOD=$(sed -n '/public function test_connection/,/}/p' "${ZOHO_ADMIN}")
        
        # Check if it already has enhanced error reporting
        if [[ "$TEST_CONN_METHOD" == *"wp_send_json_error(array("* ]]; then
            echo -e "${YELLOW}⚠ Admin class already has enhanced error reporting${NC}"
        else
            # Replace the test_connection method
            TEST_CONN_ENHANCED='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) {
            $timestamp = date("Y-m-d H:i:s");
            $log_message = "[$timestamp] 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"] : "";
            
            // Create debug info for troubleshooting
            $debug_info = array();
            $debug_info["timestamp"] = date("Y-m-d H:i:s");
            $debug_info["php_version"] = phpversion();
            $debug_info["site_url"] = function_exists("get_site_url") ? get_site_url() : "Unknown";
            
            // Check if Zoho config constants are defined
            $debug_info["config"] = array(
                "ZOHO_CLIENT_ID" => defined("ZOHO_CLIENT_ID") ? "Defined" : "Not defined",
                "ZOHO_CLIENT_SECRET" => defined("ZOHO_CLIENT_SECRET") ? "Defined" : "Not defined",
                "ZOHO_REDIRECT_URI" => defined("ZOHO_REDIRECT_URI") ? ZOHO_REDIRECT_URI : "Not defined",
                "ZOHO_REFRESH_TOKEN" => defined("ZOHO_REFRESH_TOKEN") ? "Defined" : "Not defined"
            );
            
            // Domain information
            $known_domains = array("wordpress-974670-5399585.cloudwaysapps.com", "upskill-staging.measurequick.com");
            $current_domain = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : "Unknown";
            $debug_info["domain"] = array(
                "current" => $current_domain,
                "matches_known" => in_array($current_domain, $known_domains) ? "Yes" : "No",
                "known_domains" => $known_domains
            );
            
            // Log the error
            if (defined("ZOHO_DEBUG_MODE") && ZOHO_DEBUG_MODE) {
                $timestamp = date("Y-m-d H:i:s");
                $log_message = "[$timestamp] Connection test failed: $error_message\n";
                $log_message .= "[$timestamp] Error code: $error_code\n";
                $log_message .= "[$timestamp] Details: $error_details\n";
                $log_message .= "[$timestamp] Raw response: " . json_encode($response) . "\n";
                $log_message .= "[$timestamp] Debug info: " . json_encode($debug_info) . "\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),
                "debug" => $debug_info,
                "help" => "Verify that your Zoho credentials are correct and that your redirect URI matches your current domain."
            ));
        }
    }'
            
            # Replace the method in the file
            sed -i.tmp2 "s|$(echo "$TEST_CONN_METHOD" | sed 's/[\/&]/\\&/g')|$TEST_CONN_ENHANCED|g" "${ZOHO_ADMIN}"
            
            # Remove temp files
            rm -f "${ZOHO_ADMIN}.tmp2"
            echo -e "${GREEN}✓ Admin class updated with enhanced error reporting${NC}"
        fi
    else
        echo -e "${YELLOW}⚠ test_connection method not found in admin class${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Zoho admin class not found, creating new one...${NC}"
    mkdir -p "${TEMP_DIR}/${PLUGIN_NAME}/includes/admin"
    
    cat > "${ZOHO_ADMIN}" << 'EOPHP'
<?php
/**
 * Zoho CRM Admin
 *
 * @package HVAC_Community_Events
 */

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

/**
 * HVAC_Zoho_Admin Class
 *
 * Handles the admin interface for Zoho CRM integration
 */
class HVAC_Zoho_Admin {

    /**
     * Instance of this class.
     *
     * @var object
     */
    protected static $instance = null;

    /**
     * Initialize the class.
     */
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'wp_ajax_hvac_zoho_test_connection', array( $this, 'test_connection' ) );
    }

    /**
     * Return an instance of this class.
     *
     * @return object A single instance of this class.
     */
    public static function get_instance() {
        if ( null == self::$instance ) {
            self::$instance = new self;
        }
        return self::$instance;
    }

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

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

        wp_enqueue_style( 'hvac-zoho-admin', HVAC_CE_PLUGIN_URL . 'assets/css/zoho-admin.css', array(), HVAC_CE_VERSION );
        wp_enqueue_script( 'hvac-zoho-admin', HVAC_CE_PLUGIN_URL . 'assets/js/zoho-admin.js', array( 'jquery' ), HVAC_CE_VERSION, true );
        wp_localize_script( 'hvac-zoho-admin', 'hvac_zoho_admin', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'hvac_zoho_admin_nonce' ),
        ) );
    }

    /**
     * Render admin page.
     */
    public function render_admin_page() {
        // Include Zoho config
        require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/zoho-config.php';
        
        // Get Zoho CRM Auth instance
        $zoho_auth = HVAC_Zoho_CRM_Auth::get_instance();
        
        // Check if Zoho client ID is defined
        $client_id_defined = defined( 'ZOHO_CLIENT_ID' ) && ! empty( ZOHO_CLIENT_ID );
        $client_secret_defined = defined( 'ZOHO_CLIENT_SECRET' ) && ! empty( ZOHO_CLIENT_SECRET );
        $redirect_uri_defined = defined( 'ZOHO_REDIRECT_URI' ) && ! empty( ZOHO_REDIRECT_URI );
        
        // Get site URL for display
        $site_url = function_exists( 'get_site_url' ) ? get_site_url() : 'Unknown';
        
        ?>
        <div class="wrap">
            <h1><?php echo esc_html__( 'Zoho CRM Integration', 'hvac-community-events' ); ?></h1>
            
            <div class="hvac-zoho-settings">
                <h2><?php echo esc_html__( 'Settings', 'hvac-community-events' ); ?></h2>
                
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php echo esc_html__( 'Zoho Client ID', 'hvac-community-events' ); ?></th>
                        <td>
                            <?php if ( $client_id_defined ) : ?>
                                <span class="dashicons dashicons-yes-alt" style="color: green;"></span> <?php echo esc_html__( 'Configured', 'hvac-community-events' ); ?>
                            <?php else : ?>
                                <span class="dashicons dashicons-warning" style="color: red;"></span> <?php echo esc_html__( 'Not configured', 'hvac-community-events' ); ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php echo esc_html__( 'Zoho Client Secret', 'hvac-community-events' ); ?></th>
                        <td>
                            <?php if ( $client_secret_defined ) : ?>
                                <span class="dashicons dashicons-yes-alt" style="color: green;"></span> <?php echo esc_html__( 'Configured', 'hvac-community-events' ); ?>
                            <?php else : ?>
                                <span class="dashicons dashicons-warning" style="color: red;"></span> <?php echo esc_html__( 'Not configured', 'hvac-community-events' ); ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php echo esc_html__( 'Redirect URI', 'hvac-community-events' ); ?></th>
                        <td>
                            <?php if ( $redirect_uri_defined ) : ?>
                                <code><?php echo esc_html( ZOHO_REDIRECT_URI ); ?></code>
                            <?php else : ?>
                                <span class="dashicons dashicons-warning" style="color: red;"></span> <?php echo esc_html__( 'Not configured', 'hvac-community-events' ); ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php echo esc_html__( 'Site URL', 'hvac-community-events' ); ?></th>
                        <td>
                            <code><?php echo esc_html( $site_url ); ?></code>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php echo esc_html__( 'Test Connection', 'hvac-community-events' ); ?></th>
                        <td>
                            <button id="hvac-zoho-test-connection" class="button button-primary"><?php echo esc_html__( 'Test Connection', 'hvac-community-events' ); ?></button>
                            <div id="hvac-zoho-test-connection-result" style="margin-top: 10px;"></div>
                        </td>
                    </tr>
                </table>
                
                <div class="hvac-zoho-instructions">
                    <h3><?php echo esc_html__( 'Instructions', 'hvac-community-events' ); ?></h3>
                    <ol>
                        <li><?php echo esc_html__( 'Make sure you have a valid Zoho CRM account.', 'hvac-community-events' ); ?></li>
                        <li><?php echo esc_html__( 'Create a client ID and client secret in the Zoho API Console.', 'hvac-community-events' ); ?></li>
                        <li><?php echo esc_html__( 'Set the redirect URI in the Zoho API Console to the value shown above.', 'hvac-community-events' ); ?></li>
                        <li><?php echo esc_html__( 'Click the "Test Connection" button to verify your configuration.', 'hvac-community-events' ); ?></li>
                    </ol>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Test connection to Zoho CRM.
     */
    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) {
            $timestamp = date("Y-m-d H:i:s");
            $log_message = "[$timestamp] 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"] : "";
            
            // Create debug info for troubleshooting
            $debug_info = array();
            $debug_info["timestamp"] = date("Y-m-d H:i:s");
            $debug_info["php_version"] = phpversion();
            $debug_info["site_url"] = function_exists("get_site_url") ? get_site_url() : "Unknown";
            
            // Check if Zoho config constants are defined
            $debug_info["config"] = array(
                "ZOHO_CLIENT_ID" => defined("ZOHO_CLIENT_ID") ? "Defined" : "Not defined",
                "ZOHO_CLIENT_SECRET" => defined("ZOHO_CLIENT_SECRET") ? "Defined" : "Not defined",
                "ZOHO_REDIRECT_URI" => defined("ZOHO_REDIRECT_URI") ? ZOHO_REDIRECT_URI : "Not defined",
                "ZOHO_REFRESH_TOKEN" => defined("ZOHO_REFRESH_TOKEN") ? "Defined" : "Not defined"
            );
            
            // Domain information
            $known_domains = array("wordpress-974670-5399585.cloudwaysapps.com", "upskill-staging.measurequick.com");
            $current_domain = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : "Unknown";
            $debug_info["domain"] = array(
                "current" => $current_domain,
                "matches_known" => in_array($current_domain, $known_domains) ? "Yes" : "No",
                "known_domains" => $known_domains
            );
            
            // Log the error
            if (defined("ZOHO_DEBUG_MODE") && ZOHO_DEBUG_MODE) {
                $timestamp = date("Y-m-d H:i:s");
                $log_message = "[$timestamp] Connection test failed: $error_message\n";
                $log_message .= "[$timestamp] Error code: $error_code\n";
                $log_message .= "[$timestamp] Details: $error_details\n";
                $log_message .= "[$timestamp] Raw response: " . json_encode($response) . "\n";
                $log_message .= "[$timestamp] Debug info: " . json_encode($debug_info) . "\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),
                "debug" => $debug_info,
                "help" => "Verify that your Zoho credentials are correct and that your redirect URI matches your current domain."
            ));
        }
    }
}

// Initialize the admin class
HVAC_Zoho_Admin::get_instance();
EOPHP
    echo -e "${GREEN}✓ New Zoho admin class created with enhanced error reporting${NC}"
fi

# Create JS and CSS files for admin interface
echo -e "${YELLOW}Step 5: Creating JS and CSS files for admin interface...${NC}"
mkdir -p "${TEMP_DIR}/${PLUGIN_NAME}/assets/js"
mkdir -p "${TEMP_DIR}/${PLUGIN_NAME}/assets/css"

# Create JS file
cat > "${TEMP_DIR}/${PLUGIN_NAME}/assets/js/zoho-admin.js" << '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 {
                    $result.html('<div class="notice notice-error"><p>Connection test failed. Please check the logs.</p></div>');
                }
            },
            error: function(xhr) {
                $button.prop('disabled', false);
                $result.empty();
                
                // Try to parse the response JSON
                var response = { success: false };
                try {
                    if (xhr.responseJSON) {
                        response = xhr.responseJSON;
                    } else if (xhr.responseText) {
                        response = JSON.parse(xhr.responseText);
                    }
                } catch (e) {
                    console.error('Error parsing response:', e);
                }
                
                // 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 ? 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 debug info if available
                if (response.data && response.data.debug) {
                    errorHtml += '<details>';
                    errorHtml += '<summary>Debug Information (click to expand)</summary>';
                    errorHtml += '<pre>' + JSON.stringify(response.data.debug, null, 2) + '</pre>';
                    errorHtml += '</details>';
                }
                
                // 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>';
                    }
                }
                
                // Add help text if available
                if (response.data && response.data.help) {
                    errorHtml += '<p><strong>Help:</strong> ' + response.data.help + '</p>';
                }
                
                errorHtml += '</div>'; // Close debug info div
                errorHtml += '</div>'; // Close notice div
                
                $result.html(errorHtml);
            }
        });
    });
});
EOJS

# Create CSS file
cat > "${TEMP_DIR}/${PLUGIN_NAME}/assets/css/zoho-admin.css" << 'EOCSS'
/* Zoho Admin Styles */
.hvac-zoho-settings {
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    border: 1px solid #ccd0d4;
    box-shadow: 0 1px 1px rgba(0,0,0,0.04);
}

.hvac-zoho-instructions {
    margin-top: 20px;
    padding: 15px;
    background: #f9f9f9;
    border-left: 4px solid #0073aa;
}

.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

echo -e "${GREEN}✓ JS and CSS files created${NC}"

# Create diagnostic tools
echo -e "${YELLOW}Step 6: Creating diagnostic tools...${NC}"
mkdir -p "${TEMP_DIR}/${PLUGIN_NAME}/includes/zoho"

# Create diagnostics.php
cat > "${TEMP_DIR}/${PLUGIN_NAME}/includes/zoho/diagnostics.php" << '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";

// 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 "Domain Information\n";
echo "==========================================\n";

echo "Current Host: " . $_SERVER['HTTP_HOST'] . "\n";
echo "Current URL: " . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]\n";

// Check for known domains
$known_domains = array(
    'wordpress-974670-5399585.cloudwaysapps.com',
    'upskill-staging.measurequick.com'
);

echo "Known Domains: " . implode(', ', $known_domains) . "\n";
echo "Current Domain Matches Known: " . (in_array($_SERVER['HTTP_HOST'], $known_domains) ? 'Yes' : 'No') . "\n";

// Site URL check
if (function_exists('get_site_url')) {
    $site_url = get_site_url();
    echo "WordPress Site URL: $site_url\n";
    
    foreach ($known_domains as $domain) {
        echo "Site URL contains '$domain': " . (strpos($site_url, $domain) !== false ? '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_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";
echo "UPSKILL_STAGING_URL environment variable: " . (getenv('UPSKILL_STAGING_URL') ? getenv('UPSKILL_STAGING_URL') : '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";
echo "_ENV['UPSKILL_STAGING_URL']: " . (isset($_ENV['UPSKILL_STAGING_URL']) ? $_ENV['UPSKILL_STAGING_URL'] : '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";
            echo "UPSKILL_STAGING_URL in .env: " . (strpos($env_contents, 'UPSKILL_STAGING_URL') !== 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";
            echo "UPSKILL_STAGING_URL after loading: " . (getenv('UPSKILL_STAGING_URL') ? getenv('UPSKILL_STAGING_URL') : '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 "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();
EOPHP

echo -e "${GREEN}✓ Diagnostic tools created${NC}"

# Create .env file for plugin
echo -e "${YELLOW}Step 7: Creating .env file for plugin...${NC}"
cat > "${TEMP_DIR}/${PLUGIN_NAME}/.env" << EOENV
# Zoho API Credentials
ZOHO_CLIENT_ID=1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS
ZOHO_CLIENT_SECRET=36913615664649dbf9198884bfd1096f7573c9ce2b
ZOHO_REDIRECT_URI=https://${NEW_DOMAIN}/wp-admin/admin-ajax.php?action=zoho_oauth_callback

# Site URL Settings
UPSKILL_STAGING_URL=https://${NEW_DOMAIN}
EOENV

echo -e "${GREEN}✓ .env file created${NC}"

# Create deployment package
echo -e "${YELLOW}Step 8: Creating deployment package...${NC}"
cd "${TEMP_DIR}"
zip -r "${PACKAGE_NAME}" "${PLUGIN_NAME}" -x "*.DS_Store" -x "*.git*"

# Move the package to a known location
if [[ ! -d "../plugin-backups" ]]; then
    mkdir -p "../plugin-backups"
fi

mv "${PACKAGE_NAME}" "../plugin-backups/${PACKAGE_NAME}"
echo -e "${GREEN}✓ Deployment package created at: plugin-backups/${PACKAGE_NAME}${NC}"

# Create web deployment instructions
echo -e "${YELLOW}Step 9: Creating web deployment instructions...${NC}"
cat > "plugin-backups/deployment-instructions.txt" << EOINSTRUCT
HVAC Community Events Plugin Deployment Instructions
===================================================

The plugin package has been created with the domain update fixes. Follow these steps to deploy:

1. Log into WordPress admin at https://${NEW_DOMAIN}/wp-admin/

2. Navigate to Plugins > Add New > Upload Plugin

3. Click "Choose File" and select the plugin package at:
   ${PWD}/plugin-backups/${PACKAGE_NAME}

4. Click "Install Now"

5. After installation, click "Activate Plugin"

6. Verify the plugin is working by checking:
   - https://${NEW_DOMAIN}/trainer-dashboard/
   - https://${NEW_DOMAIN}/wp-admin/admin.php?page=hvac-zoho-sync

7. Test the Zoho CRM integration:
   - Go to Events > Zoho CRM Sync
   - Click "Test Connection"
   - Check for any errors and verify the domain is correctly set

8. If needed, run the diagnostics tool:
   https://${NEW_DOMAIN}/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true
EOINSTRUCT

echo -e "${GREEN}✓ Deployment instructions created at: plugin-backups/deployment-instructions.txt${NC}"

# Create E2E test for domain verification
echo -e "${YELLOW}Step 10: Creating E2E test for domain verification...${NC}"
cat > "../tests/e2e/domain-verification-comprehensive.test.ts" << EOTS
import { test, expect } from '@playwright/test';

test.describe('Domain Migration Verification', () => {
  const OLD_DOMAIN = 'wordpress-974670-5399585.cloudwaysapps.com';
  const NEW_DOMAIN = 'upskill-staging.measurequick.com';
  
  test('verify site accessibility with new domain', async ({ page }) => {
    console.log('Checking site accessibility with new domain...');
    
    // Check if the site is accessible
    await page.goto(`https://${NEW_DOMAIN}/`);
    const title = await page.title();
    console.log(`Site title: ${title}`);
    expect(title).toContain('Upskill HVAC');
    
    // Check for HVAC plugin indicators
    const cssFiles = await page.locator('link[href*="hvac"]').count();
    const jsFiles = await page.locator('script[src*="hvac"]').count();
    const hvacClasses = await page.locator('[class*="hvac"]').count();
    
    console.log(`Found ${cssFiles} HVAC CSS files, ${jsFiles} JS files, and ${hvacClasses} HVAC classes`);
    
    // Check if trainer dashboard exists
    await page.goto(`https://${NEW_DOMAIN}/trainer-dashboard/`);
    const dashboardExists = !await page.locator('body:has-text("Page not found")').isVisible();
    console.log(`Trainer dashboard exists: ${dashboardExists}`);
    
    // Check WordPress admin
    await page.goto(`https://${NEW_DOMAIN}/wp-admin/`);
    const currentUrl = page.url();
    console.log(`WordPress admin redirects to: ${currentUrl}`);
    expect(currentUrl).toContain('wp-login.php');
    
    // Check for old domain references in HTML
    await page.goto(`https://${NEW_DOMAIN}/`);
    const pageContent = await page.content();
    const oldDomainReferences = pageContent.includes(OLD_DOMAIN);
    console.log(`Page contains references to old domain: ${oldDomainReferences}`);
    expect(oldDomainReferences).toBe(false);
    
    // Check Zoho admin page if logged in
    try {
      await page.goto(`https://${NEW_DOMAIN}/wp-admin/`);
      await page.fill('#user_login', 'admin');
      await page.fill('#user_pass', 'password'); // Replace with actual password
      await page.click('#wp-submit');
      
      const loginSuccessful = await page.locator('#wpadminbar').isVisible();
      
      if (loginSuccessful) {
        console.log('Login successful, checking Zoho admin page...');
        await page.goto(`https://${NEW_DOMAIN}/wp-admin/admin.php?page=hvac-zoho-sync`);
        
        const zohoPageExists = await page.locator('h1:has-text("Zoho CRM Integration")').isVisible();
        console.log(`Zoho admin page exists: ${zohoPageExists}`);
        
        if (zohoPageExists) {
          const redirectUri = await page.locator('code:near(:text("Redirect URI"))').textContent();
          console.log(`Zoho redirect URI: ${redirectUri}`);
          expect(redirectUri).not.toContain(OLD_DOMAIN);
          expect(redirectUri).toContain(NEW_DOMAIN);
        }
      } else {
        console.log('Login failed, skipping Zoho admin page check');
      }
    } catch (error) {
      console.log(`Error checking Zoho admin page: ${error.message}`);
    }
  });
  
  test('verify key pages work with new domain', async ({ page }) => {
    // List of key pages to check
    const pagesToCheck = [
      '/',
      '/community-registration/',
      '/community-login/',
      '/trainer-dashboard/',
      '/events/create/',
      '/generate-certificates/',
      '/certificates-report/'
    ];
    
    console.log('Checking key pages with new domain...');
    
    for (const pagePath of pagesToCheck) {
      const url = `https://${NEW_DOMAIN}${pagePath}`;
      console.log(`Checking page: ${url}`);
      
      await page.goto(url);
      const title = await page.title();
      const is404 = title.includes('Page not found') || title.includes('404');
      
      console.log(`- ${pagePath}: ${is404 ? 'Not Found (404)' : 'Available'}`);
      
      // Check for old domain references
      if (!is404) {
        const pageContent = await page.content();
        const hasOldDomain = pageContent.includes(OLD_DOMAIN);
        console.log(`  - Contains old domain references: ${hasOldDomain}`);
        
        if (hasOldDomain) {
          console.log('  - WARNING: Page contains references to old domain!');
        }
      }
    }
  });
});
EOTS

echo -e "${GREEN}✓ E2E test created at: tests/e2e/domain-verification-comprehensive.test.ts${NC}"

# Clean up
echo -e "${YELLOW}Step 11: Cleaning up temporary files...${NC}"
rm -rf "${TEMP_DIR}"
echo -e "${GREEN}✓ Temporary files cleaned up${NC}"

# Summary
echo -e "${GREEN}==============================================${NC}"
echo -e "${GREEN}HVAC Community Events Plugin Update Complete!${NC}"
echo -e "${GREEN}==============================================${NC}"
echo -e "The plugin has been updated with the following changes:"
echo -e "1. Dynamic domain detection for Zoho CRM integration"
echo -e "2. Enhanced error reporting with detailed debugging"
echo -e "3. Created deployment package with all fixes"
echo -e "4. Added comprehensive E2E tests for domain verification"
echo -e "5. Created web deployment instructions"
echo -e
echo -e "Next steps:"
echo -e "1. Deploy the plugin using the web installer:"
echo -e "   ${PWD}/plugin-backups/${PACKAGE_NAME}"
echo -e "2. Run the E2E tests to verify the domain migration:"
echo -e "   npx playwright test tests/e2e/domain-verification-comprehensive.test.ts"
echo -e
echo -e "For detailed instructions, see:"
echo -e "${PWD}/plugin-backups/deployment-instructions.txt"
echo -e "${GREEN}==============================================${NC}"