#!/bin/bash

# Get absolute path to this script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Navigate to wordpress-dev directory
cd "$(dirname "$SCRIPT_DIR")" || exit 1

# Load environment variables
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"

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

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

echo "=== Creating Test Events on Staging Server ==="
echo "Remote host: $UPSKILL_STAGING_IP"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "WordPress path: $UPSKILL_STAGING_PATH"
echo "==============================="

# Copy the PHP setup script to staging
echo -e "\n${YELLOW}Copying test event setup script to staging...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" scp -o StrictHostKeyChecking=no \
    "tests/setup-test-events.php" \
    "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}:${UPSKILL_STAGING_PATH}/wp-content/plugins/hvac-community-events/tests/"
check_status "Test script upload"

# Run the test event setup script
echo -e "\n${YELLOW}Running test event creation script...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp eval-file wp-content/plugins/hvac-community-events/tests/setup-test-events.php --allow-root"
check_status "Test event creation"

# Verify events were created
echo -e "\n${YELLOW}Verifying test events...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp post list --post_type=tribe_events --author=\$(wp user get test_trainer --field=id --allow-root) --fields=ID,post_title,post_status --format=table --allow-root"
check_status "Event verification"

# Check ticket setup (if Event Tickets is active)
echo -e "\n${YELLOW}Checking ticket setup...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp plugin is-active event-tickets --allow-root && wp post list --post_type=tribe_tpp_tickets --fields=ID,post_title,post_parent --format=table --allow-root || echo 'Event Tickets not active'"

echo -e "\n${GREEN}Test event setup completed!${NC}"
echo "Events created for test_trainer user with varying ticket prices and attendee counts"