#!/bin/bash

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

# Base URL of the staging server
BASE_URL="https://wordpress-974670-5399585.cloudwaysapps.com"

# Login credentials (used for manual testing only)
echo "${YELLOW}Login Credentials for Manual Testing${NC}"
echo "Username: test_trainer"
echo "Password: Test123!"
echo ""

# Array of URLs to test
declare -a URLS=(
    "/"
    "/community-login/"
    "/hvac-dashboard/"
    "/trainer-profile/"
    "/event-summary/"
    "/manage-event/"
    "/email-attendees/"
    "/certificate-reports/"
    "/generate-certificates/"
)

# Array of expected redirects (if not logged in)
declare -a REDIRECTS=(
    ""
    ""
    "/community-login/"
    "/community-login/"
    "/community-login/"
    "/community-login/"
    "/community-login/"
    "/community-login/"
    "/community-login/"
)

echo "${YELLOW}Checking URLs on $BASE_URL...${NC}"
echo ""

# Loop through the URLs and check HTTP status
for i in "${!URLS[@]}"; do
    URL="${BASE_URL}${URLS[$i]}"
    EXPECTED_REDIRECT="${REDIRECTS[$i]}"
    
    echo "Testing: ${URL}"
    
    # Get the HTTP status code
    HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
    
    # Get the final URL after redirects
    FINAL_URL=$(curl -s -o /dev/null -L -w "%{url_effective}" "$URL")
    
    # Display results
    echo "  Status Code: $HTTP_STATUS"
    echo "  Final URL: $FINAL_URL"
    
    # Check if the status is 500 (to identify our error)
    if [ "$HTTP_STATUS" -eq 500 ]; then
        echo "  ${RED}Error: Server error (500)${NC}"
    # Check for 404 errors
    elif [ "$HTTP_STATUS" -eq 404 ]; then
        echo "  ${RED}Error: Page not found (404)${NC}"
    # Check if the status is 200 or a redirect (3xx)
    elif [ "$HTTP_STATUS" -eq 200 ] || [ "$HTTP_STATUS" -ge 300 ] && [ "$HTTP_STATUS" -lt 400 ]; then
        # If we have an expected redirect, check it
        if [ -n "$EXPECTED_REDIRECT" ]; then
            if [[ "$FINAL_URL" == *"$EXPECTED_REDIRECT"* ]]; then
                echo "  ${GREEN}Success: Redirected as expected${NC}"
            else
                echo "  ${YELLOW}Warning: Redirected, but not to expected location${NC}"
                echo "  Expected: *${EXPECTED_REDIRECT}*"
            fi
        else
            echo "  ${GREEN}Success: Page loaded successfully${NC}"
        fi
    else
        echo "  ${RED}Error: Unexpected HTTP status${NC}"
    fi
    
    echo ""
done

echo "${YELLOW}Test completed. Please also test with actual login to verify page functionality.${NC}"
echo ""
echo "To test logged-in functionality:"
echo "1. Go to $BASE_URL/community-login/"
echo "2. Enter the test credentials"
echo "3. After login, check each page manually:"

for URL in "${URLS[@]}"; do
    if [ "$URL" != "/" ] && [ "$URL" != "/community-login/" ]; then
        echo "   - $BASE_URL$URL"
    fi
done

# Make script executable
chmod +x "$0"