#\!/bin/bash

# Simple direct fix for Zoho CRM integration
# This script deploys the necessary changes to the staging server

# 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"

# Check if environment variables are loaded
if [ -z "$UPSKILL_STAGING_IP" ] || [ -z "$UPSKILL_STAGING_SSH_USER" ]; then
    echo -e "${RED}Error: Missing required environment variables${NC}"
    echo "Please ensure .env file exists and contains UPSKILL_STAGING_IP and UPSKILL_STAGING_SSH_USER"
    exit 1
fi

# 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"
PLUGIN_PATH="${REMOTE_PATH}/wp-content/plugins/hvac-community-events"

echo -e "${YELLOW}=== Deploying Zoho CRM Integration Fixes ===${NC}"
echo -e "${YELLOW}Target: ${REMOTE_USER}@${REMOTE_HOST}:${PLUGIN_PATH}${NC}"

# Create the remote directories
echo -e "${YELLOW}Creating directories on remote server...${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
EOSSH

# Create a temporary directory
TEMP_DIR=$(mktemp -d)
echo -e "${YELLOW}Creating temporary files in ${TEMP_DIR}...${NC}"

# Create zoho-config.php
cat > "$TEMP_DIR/zoho-config.php" << 'EOPHP'
<?php
/**
 * Zoho CRM Configuration
 * 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();

// 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') ?: '');
define('ZOHO_CLIENT_SECRET', getenv('ZOHO_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', 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";
    $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";
    
    // 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);
}
EOPHP

# Create diagnostics.php
cat > "$TEMP_DIR/diagnostics.php" << 'EOPHP'
<?php
/**
 * Zoho CRM Integration Diagnostics
 */

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

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

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

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

// Check if Zoho config file exists
$zoho_config_path = $plugin_dir . '/includes/zoho/zoho-config.php';
if (file_exists($zoho_config_path)) {
    echo "Zoho Config File: Found\n";
    
    // Include the config file
    require_once $zoho_config_path;
    
    // Check for required constants
    echo "ZOHO_CLIENT_ID defined: " . (defined('ZOHO_CLIENT_ID') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_CLIENT_ID value: " . (defined('ZOHO_CLIENT_ID') && ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'EMPTY') . "\n";
    
    echo "ZOHO_CLIENT_SECRET defined: " . (defined('ZOHO_CLIENT_SECRET') ? 'Yes' : 'No') . "\n";
    echo "ZOHO_CLIENT_SECRET value: " . (defined('ZOHO_CLIENT_SECRET') && ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'EMPTY') . "\n";
    
    echo "ZOHO_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_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 "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();
EOPHP

# Upload files
echo -e "${YELLOW}Uploading fixed files to the server...${NC}"

# Upload zoho-config.php
echo "Uploading zoho-config.php..."
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$TEMP_DIR/zoho-config.php" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/includes/zoho/zoho-config.php"
if [ $? -ne 0 ]; then
    echo -e "${RED}Failed to upload zoho-config.php${NC}"
fi

# Upload diagnostics.php
echo "Uploading diagnostics.php..."
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$TEMP_DIR/diagnostics.php" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/includes/zoho/diagnostics.php"
if [ $? -ne 0 ]; then
    echo -e "${RED}Failed to upload diagnostics.php${NC}"
fi

# Clean up temporary directory
rm -rf "$TEMP_DIR"

echo -e "${GREEN}=== Zoho CRM integration fixes deployed successfully\! ===${NC}"
echo -e "${YELLOW}You can now check the Zoho CRM integration in the WordPress admin panel.${NC}"
echo -e "${YELLOW}If issues persist, run the diagnostic tool at: https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true${NC}"

exit 0
