#!/bin/bash

# Script to run certificate functionality tests manually for the HVAC Community Events plugin

# Load environment variables
if [ -f "./.env" ]; then
    echo "Loading environment variables from .env"
    source ./.env
fi

# Constants
STAGING_URL=${UPSKILL_STAGING_URL:-"https://wordpress-974670-5399585.cloudwaysapps.com"}
TEST_USER="test_trainer"
TEST_PASSWORD="Test123!"

# Plugin activation and rewrite flush
echo "Reactivating plugin to ensure hooks fire..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp plugin deactivate hvac-community-events --allow-root" || echo "Note: Plugin already inactive or not found (continuing)."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp plugin activate hvac-community-events --allow-root"
if [ $? -ne 0 ]; then
    echo "Failed to activate hvac-community-events plugin. Exiting."
    exit 1
fi
echo "Plugin reactivated."

echo "Flushing rewrite rules..."
if ! sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp rewrite flush --hard --allow-root"; then
    echo "Failed to flush rewrite rules. Exiting."
    exit 1
fi
echo "Rewrite rules flushed."

# Launch the browser
case "$1" in
    "generation")
        TEST_TYPE="Generation"
        URL="${STAGING_URL}/generate-certificates/"
        ;;
    "reports")
        TEST_TYPE="Reports"
        URL="${STAGING_URL}/certificate-reports/"
        ;;
    *)
        TEST_TYPE="Login"
        URL="${STAGING_URL}/community-login/"
        ;;
esac

echo "Running Certificate $TEST_TYPE Test..."

echo "Test Steps for Certificate $TEST_TYPE:"
echo "1. Login as $TEST_USER with password $TEST_PASSWORD"

case "$TEST_TYPE" in
    "Generation")
        echo "2. Select an event from the dropdown"
        echo "3. Select attendees (all, or filtered by check-in status)"
        echo "4. Click Generate Certificates button"
        echo "5. Verify success message and certificate generation"
        ;;
    "Reports")
        echo "2. Verify certificate listing appears"
        echo "3. Test View, Email, and Revoke functionality"
        echo "4. Test filtering and pagination if available"
        ;;
    *)
        echo "2. Navigate to Generate Certificates or Certificate Reports page"
        echo "3. Follow specific test steps for that page"
        ;;
esac

# Open the browser
echo "Opening Chrome to $URL"
open -a "Google Chrome" "$URL"

echo "Manual test started. Follow the steps above to verify certificate functionality."
echo "Press any key when finished to complete the test..."
read -n 1 -s

echo ""
echo "Certificate testing complete."