#!/bin/bash

# Script to verify The Events Calendar and Community Events plugin activation status
# Usage: ./verify-tec-plugins.sh [staging_url] [wp_cli_path]

# Load environment variables from .env if present
if [ -f "$SCRIPT_DIR/../.env" ]; then
  set -o allexport
  source "$SCRIPT_DIR/../.env"
  set +o allexport
fi

# Ensure wp-cli is installed and available locally (for local use only)
if [ -f "$SCRIPT_DIR/install-and-verify-wp-cli.sh" ]; then
  bash "$SCRIPT_DIR/install-and-verify-wp-cli.sh"
fi

# Default values
STAGING_URL=${1:-"https://wordpress-974670-5399585.cloudwaysapps.com"}
# Use MASTER credentials for Cloudways VPS
WP_CLI_REMOTE_PATH="${UPSKILL_STAGING_PATH:-/home/974670.cloudwaysapps.com/uberrxmprk/public_html}/wp-content/plugins/hvac-community-events"
WP_CLI_REMOTE="cd $WP_CLI_REMOTE_PATH && wp"
SSH_USER="${UPSKILL_STAGING_MASTER_SSH_USER:-master_kczkabufnc}"
SSH_IP="${UPSKILL_STAGING_IP:-146.190.76.204}"
SSHPASS="${UPSKILL_STAGING_MASTER_SSH_PASS:-tmvKuJQ8QptF}"

# Debug: Print resolved SSH variables
echo "DEBUG: Using SSH_USER=$SSH_USER, SSH_IP=$SSH_IP, WP_CLI_REMOTE_PATH=$WP_CLI_REMOTE_PATH"

# Helper to run wp-cli remotely with sshpass
run_wp_remote() {
  local cmd="$1"
  sshpass -p "$SSHPASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SSH_IP" "$WP_CLI_REMOTE $cmd --url=$STAGING_URL --allow-root"
}

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

echo "=== The Events Calendar Plugin Verification ==="
echo "Checking plugin activation status on: $STAGING_URL"
echo ""

# Required plugins to check
declare -a REQUIRED_PLUGINS=(
    "the-events-calendar"
    "events-calendar-pro"
    "the-events-calendar-community-events"
    "event-tickets"
    "event-tickets-plus"
)

# Function to check if a plugin is active
check_plugin() {
    local plugin=$1
    local plugin_name=$2
    
    echo -n "Checking $plugin_name... "
    
    # Use WP-CLI to check if plugin is active
    # This assumes WP-CLI is configured to work with the staging site
    RESULT=$(run_wp_remote "plugin is-active $plugin")
    if [[ $? -eq 0 ]]; then
        echo -e "${GREEN}ACTIVE${NC}"
        return 0
    else
        echo -e "${RED}NOT ACTIVE${NC}"
        return 1
    fi
}

# Function to get plugin details
get_plugin_details() {
    local plugin=$1
    
    echo "Getting details for $plugin..."
    run_wp_remote "plugin get $plugin --format=json" 2>/dev/null || echo "{}"
}

# Track overall status
OVERALL_STATUS=0

# Check each required plugin
echo "=== Required Plugins ==="
check_plugin "the-events-calendar" "The Events Calendar" || OVERALL_STATUS=1
check_plugin "events-calendar-pro" "Events Calendar PRO" || OVERALL_STATUS=1
check_plugin "the-events-calendar-community-events" "Community Events" || OVERALL_STATUS=1
check_plugin "event-tickets" "Event Tickets" || OVERALL_STATUS=1
check_plugin "event-tickets-plus" "Event Tickets Plus" || OVERALL_STATUS=1

echo ""
echo "=== Plugin Details ==="

# Get and display detailed information about each plugin
for plugin in "${REQUIRED_PLUGINS[@]}"; do
    DETAILS=$(get_plugin_details $plugin)
    
    # Extract version and status using grep and cut
    VERSION=$(echo $DETAILS | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
    STATUS=$(echo $DETAILS | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
    
    if [[ -z "$VERSION" ]]; then
        echo -e "${plugin}: ${RED}Not installed${NC}"
    else
        if [[ "$STATUS" == "active" ]]; then
            echo -e "${plugin}: ${GREEN}v${VERSION} (Active)${NC}"
        else
            echo -e "${plugin}: ${YELLOW}v${VERSION} (Inactive)${NC}"
            OVERALL_STATUS=1
        fi
    fi
done

echo ""
echo "=== Checking Plugin Dependencies ==="

# Check if The Events Calendar is active before Community Events
check_plugin "the-events-calendar" "The Events Calendar" > /dev/null
TEC_ACTIVE=$?

check_plugin "the-events-calendar-community-events" "Community Events" > /dev/null
CE_ACTIVE=$?

if [[ $TEC_ACTIVE -eq 0 && $CE_ACTIVE -eq 0 ]]; then
    echo -e "${GREEN}✓ Community Events and its required dependency (The Events Calendar) are both active.${NC}"
elif [[ $TEC_ACTIVE -eq 1 && $CE_ACTIVE -eq 0 ]]; then
    echo -e "${RED}✗ Community Events is active but its required dependency (The Events Calendar) is not active!${NC}"
    OVERALL_STATUS=1
fi

# Check if Event Tickets is active before Event Tickets Plus
check_plugin "event-tickets" "Event Tickets" > /dev/null
ET_ACTIVE=$?

check_plugin "event-tickets-plus" "Event Tickets Plus" > /dev/null
ETP_ACTIVE=$?

if [[ $ET_ACTIVE -eq 0 && $ETP_ACTIVE -eq 0 ]]; then
    echo -e "${GREEN}✓ Event Tickets Plus and its required dependency (Event Tickets) are both active.${NC}"
elif [[ $ET_ACTIVE -eq 1 && $ETP_ACTIVE -eq 0 ]]; then
    echo -e "${RED}✗ Event Tickets Plus is active but its required dependency (Event Tickets) is not active!${NC}"
    OVERALL_STATUS=1
fi

echo ""
echo "=== Checking Plugin Shortcodes ==="

# Check if shortcodes are registered by looking at the rendered HTML
echo "Checking Community Events shortcodes..."
MANAGE_EVENT_HTML=$(run_wp_remote "eval 'echo do_shortcode(\"[tribe_community_events]\");'")

if [[ $MANAGE_EVENT_HTML == *"tribe-community-events"* ]]; then
    echo -e "${GREEN}✓ [tribe_community_events] shortcode is working${NC}"
else
    echo -e "${RED}✗ [tribe_community_events] shortcode is not rendering properly${NC}"
    OVERALL_STATUS=1
fi

MY_EVENTS_HTML=$(run_wp_remote "eval 'echo do_shortcode(\"[tribe_community_events view=\\\"list\\\"]\");'")

if [[ $MY_EVENTS_HTML == *"tribe-community-events-list"* ]]; then
    echo -e "${GREEN}✓ [tribe_community_events view=\"list\"] shortcode is working${NC}"
else
    echo -e "${RED}✗ [tribe_community_events view=\"list\"] shortcode is not rendering properly${NC}"
    OVERALL_STATUS=1
fi

echo ""
echo "=== Summary ==="
if [[ $OVERALL_STATUS -eq 0 ]]; then
    echo -e "${GREEN}All required plugins are active and properly configured.${NC}"
    exit 0
else
    echo -e "${RED}Some plugins are missing or not properly configured. See details above.${NC}"
    exit 1
fi