#!/bin/bash

# A simplified version of the Zoho deployment script that uses rsync directly

# 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 "Error: Missing required environment variables"
    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"

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

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

# Create backup of current Zoho files on the remote server
echo -e "${YELLOW}Creating backup of current Zoho files...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $PLUGIN_PATH && cp -r includes/zoho includes/zoho-backup-$(date +%Y%m%d%H%M%S) && cp includes/admin/class-zoho-admin.php includes/zoho-backup-admin-$(date +%Y%m%d%H%M%S).php && cp assets/js/zoho-admin.js includes/zoho-backup-js-$(date +%Y%m%d%H%M%S).js && cp assets/css/zoho-admin.css includes/zoho-backup-css-$(date +%Y%m%d%H%M%S).css"

# Create local directories for files
SRC_DIR="$(dirname "$0")/../wordpress/wp-content/plugins/hvac-community-events"
TEMP_DIR=$(mktemp -d)

# Copy files to deploy
echo -e "${YELLOW}Preparing files for deployment...${NC}"
mkdir -p "$TEMP_DIR/includes/zoho"
mkdir -p "$TEMP_DIR/includes/admin"
mkdir -p "$TEMP_DIR/assets/js"
mkdir -p "$TEMP_DIR/assets/css"

cp "$SRC_DIR/includes/zoho/class-zoho-crm-auth.php" "$TEMP_DIR/includes/zoho/"
cp "$SRC_DIR/includes/zoho/diagnostics.php" "$TEMP_DIR/includes/zoho/"
cp "$SRC_DIR/includes/zoho/check-permissions.php" "$TEMP_DIR/includes/zoho/"
cp "$SRC_DIR/includes/admin/class-zoho-admin.php" "$TEMP_DIR/includes/admin/"
cp "$SRC_DIR/assets/js/zoho-admin.js" "$TEMP_DIR/assets/js/"
cp "$SRC_DIR/assets/css/zoho-admin.css" "$TEMP_DIR/assets/css/"

# Deploy with rsync
echo -e "${YELLOW}Deploying files to staging server...${NC}"
sshpass -p "$REMOTE_PASS" rsync -avz --no-perms --no-owner --no-group -e "ssh -o StrictHostKeyChecking=no" "$TEMP_DIR/" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to deploy files. Aborting.${NC}"
    rm -rf "$TEMP_DIR"
    exit 1
fi

echo -e "${GREEN}Files deployed successfully.${NC}"

# Create a PHP script to update the zoho-config.php file
cat > "$TEMP_DIR/patch-config.php" << 'EOL'
<?php
// Load existing config
$config_file = __DIR__ . '/includes/zoho/zoho-config.php';
if (!file_exists($config_file)) {
    echo "Error: zoho-config.php not found!\n";
    exit(1);
}

// Read current config
$current_config = file_get_contents($config_file);

// Create backup
$backup_file = __DIR__ . '/includes/zoho/zoho-config-backup-' . date('YmdHis') . '.php';
file_put_contents($backup_file, $current_config);
echo "Created backup at: $backup_file\n";

// Extract credentials
preg_match('/define\\s*\\(\\s*[\'"]ZOHO_CLIENT_ID[\'"]\\s*,\\s*(.*?)\\s*\\)\\s*;/s', $current_config, $client_id_match);
preg_match('/define\\s*\\(\\s*[\'"]ZOHO_CLIENT_SECRET[\'"]\\s*,\\s*(.*?)\\s*\\)\\s*;/s', $current_config, $client_secret_match);
preg_match('/define\\s*\\(\\s*[\'"]ZOHO_REFRESH_TOKEN[\'"]\\s*,\\s*(.*?)\\s*\\)\\s*;/s', $current_config, $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
EOT;

// Add the credentials
$new_config .= "\ndefine('ZOHO_CLIENT_ID', $client_id);\n";
$new_config .= "define('ZOHO_CLIENT_SECRET', $client_secret);\n";
$new_config .= "define('ZOHO_REDIRECT_URI', 'https://wordpress-974670-5399585.cloudwaysapps.com/oauth/callback');\n\n";

// Add the rest of the config
$new_config .= <<<'EOT'
// 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)
EOT;

// Add refresh token
$new_config .= "\ndefine('ZOHO_REFRESH_TOKEN', $refresh_token);\n\n";

// Add the debugging section
$new_config .= <<<'EOT'
// 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 updated config
file_put_contents($config_file, $new_config);
echo "Updated zoho-config.php successfully.\n";

// Create logs directory
$logs_dir = __DIR__ . '/includes/logs';
if (!file_exists($logs_dir)) {
    mkdir($logs_dir, 0755, true);
    echo "Created logs directory: $logs_dir\n";
}

// Update wp-config.php to enable diagnostics
$wp_config_file = realpath(__DIR__ . '/../wp-config.php');
if (file_exists($wp_config_file)) {
    $wp_config = file_get_contents($wp_config_file);
    
    // Check if diagnostic flag already exists
    if (strpos($wp_config, 'ZOHO_DIAGNOSTICS_ENABLED') === false) {
        // Find the line where custom values should be added
        $pattern = "/\/\* Add any custom values between this line and the \"stop editing\" line\. \*\//";
        $replacement = "/* Add any custom values between this line and the \"stop editing\" line. */\n\n/* Enable Zoho CRM Diagnostics */\ndefine('ZOHO_DIAGNOSTICS_ENABLED', true);";
        
        $wp_config = preg_replace($pattern, $replacement, $wp_config);
        
        // Create backup
        $wp_backup = __DIR__ . '/../wp-config-' . date('YmdHis') . '.php.bak';
        file_put_contents($wp_backup, file_get_contents($wp_config_file));
        echo "Created wp-config.php backup at: $wp_backup\n";
        
        // Write updated config
        file_put_contents($wp_config_file, $wp_config);
        echo "Updated wp-config.php to enable Zoho diagnostics.\n";
    } else {
        echo "ZOHO_DIAGNOSTICS_ENABLED already present in wp-config.php.\n";
    }
} else {
    echo "Warning: wp-config.php not found at expected location.\n";
}

echo "Configuration update completed successfully.\n";
EOL

# Upload and run the patching script
echo -e "${YELLOW}Uploading and running config patcher...${NC}"
# First ensure the directory exists
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "mkdir -p $PLUGIN_PATH/includes/logs"
# Upload patch script
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$TEMP_DIR/patch-config.php" "$REMOTE_USER@$REMOTE_HOST:$PLUGIN_PATH/patch-config.php"

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

# Execute the patch script
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $PLUGIN_PATH && php patch-config.php && rm patch-config.php"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Config patching failed. Aborting.${NC}"
    rm -rf "$TEMP_DIR"
    exit 1
fi

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

# Clean up
rm -rf "$TEMP_DIR"

echo -e "${GREEN}=== Zoho CRM integration fixes deployed successfully! ===${NC}"
echo -e "${YELLOW}You can now test the connection in the WordPress admin panel.${NC}"
echo -e "${YELLOW}If issues persist, check the logs at: ${PLUGIN_PATH}/includes/logs/zoho-debug.log${NC}"
echo -e "${YELLOW}Or 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