#!/bin/bash

# A direct deployment script for Zoho CRM integration fixes
# This script runs the patch-zoho.php locally and then uploads the patched files

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

echo -e "${YELLOW}=== Patching Zoho CRM Integration Locally ===${NC}"

# Run the PHP patcher script
php "$(dirname "$0")/patch-zoho.php"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Failed to patch Zoho CRM integration locally. Aborting.${NC}"
    exit 1
fi

echo -e "${GREEN}Local patching completed successfully.${NC}"

# 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"
SRC_DIR="$(dirname "$0")/../wordpress/wp-content/plugins/hvac-community-events"

echo -e "${YELLOW}=== Deploying Patched Files to Staging ===${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" <<EOSSH
mkdir -p $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/includes/zoho
mkdir -p $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/includes/admin
mkdir -p $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/assets/js
mkdir -p $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/assets/css
mkdir -p $PLUGIN_PATH/includes/logs

cp $PLUGIN_PATH/includes/zoho/*.php $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/includes/zoho/ 2>/dev/null || true
cp $PLUGIN_PATH/includes/admin/class-zoho-admin.php $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/includes/admin/ 2>/dev/null || true
cp $PLUGIN_PATH/assets/js/zoho-admin.js $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/assets/js/ 2>/dev/null || true
cp $PLUGIN_PATH/assets/css/zoho-admin.css $PLUGIN_PATH/backups/zoho-$(date +%Y%m%d%H%M%S)/assets/css/ 2>/dev/null || true
EOSSH

# Upload patched files
echo -e "${YELLOW}Uploading patched files...${NC}"

# Create the list of files to upload
FILES_TO_UPLOAD=(
    "$SRC_DIR/includes/zoho/class-zoho-crm-auth.php"
    "$SRC_DIR/includes/zoho/zoho-config.php"
    "$SRC_DIR/includes/zoho/diagnostics.php"
    "$SRC_DIR/includes/zoho/check-permissions.php"
    "$SRC_DIR/includes/admin/class-zoho-admin.php"
    "$SRC_DIR/assets/js/zoho-admin.js"
    "$SRC_DIR/assets/css/zoho-admin.css"
)

# Upload each file individually to ensure correct paths
for file in "${FILES_TO_UPLOAD[@]}"; do
    rel_path=${file#$SRC_DIR/}
    target_path="$PLUGIN_PATH/$rel_path"
    target_dir=$(dirname "$target_path")
    
    echo "Uploading $file to $target_path"
    
    # Ensure target directory exists
    sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "mkdir -p $target_dir"
    
    # Upload file if it exists
    if [ -f "$file" ]; then
        sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$file" "$REMOTE_USER@$REMOTE_HOST:$target_path"
        
        if [ $? -ne 0 ]; then
            echo -e "${RED}Error: Failed to upload $file. Continuing...${NC}"
        else
            echo -e "${GREEN}Successfully uploaded $file${NC}"
        fi
    else
        echo -e "${RED}File not found: $file${NC}"
    fi
done

echo -e "${GREEN}Files uploaded process completed.${NC}"

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

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}"
echo -e "${YELLOW}Or check permissions at: https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/check-permissions.php?check=true${NC}"

exit 0