#!/bin/bash
# ============================================================================
# ShopDB Form Testing Script (Bash/curl version)
# ============================================================================
# Tests form submissions across key pages to verify no errors occur
# Run from Linux: ./test_forms.sh
# ============================================================================

BASE_URL="${1:-http://192.168.122.151:8080}"
PASSED=0
FAILED=0
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

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

echo ""
echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}ShopDB Form Testing - $TIMESTAMP${NC}"
echo -e "${CYAN}Base URL: $BASE_URL${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""

# ----------------------------------------------------------------------------
# Test Functions
# ----------------------------------------------------------------------------

test_page_loads() {
    local url="$1"
    local test_name="$2"
    local expected="${3:-}"

    response=$(curl -s -w "\n%{http_code}" "$url" 2>/dev/null)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    # Check for HTTP 200
    if [ "$http_code" != "200" ]; then
        echo -e "[${RED}FAIL${NC}] $test_name - HTTP $http_code"
        ((FAILED++))
        return 1
    fi

    # Check for ASP errors in body
    if echo "$body" | grep -qi "Microsoft VBScript\|Error 500\|Internal server error"; then
        echo -e "[${RED}FAIL${NC}] $test_name - Contains server error"
        ((FAILED++))
        return 1
    fi

    # Check for expected content if specified
    if [ -n "$expected" ]; then
        if ! echo "$body" | grep -qi "$expected"; then
            echo -e "[${RED}FAIL${NC}] $test_name - Missing expected content: $expected"
            ((FAILED++))
            return 1
        fi
    fi

    echo -e "[${GREEN}PASS${NC}] $test_name"
    ((PASSED++))
    return 0
}

test_form_submit() {
    local url="$1"
    local test_name="$2"
    local data="$3"
    local expect_redirect="${4:-displaynotifications}"

    # Submit form and capture response
    response=$(curl -s -w "\n%{http_code}" -X POST -d "$data" -L "$url" 2>/dev/null)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    # Check for HTTP 200 (after redirects)
    if [ "$http_code" != "200" ]; then
        echo -e "[${RED}FAIL${NC}] $test_name - HTTP $http_code"
        ((FAILED++))
        return 1
    fi

    # Check for ASP errors in body
    if echo "$body" | grep -qi "Microsoft VBScript\|Error 500\|Internal server error"; then
        echo -e "[${RED}FAIL${NC}] $test_name - Contains server error"
        ((FAILED++))
        return 1
    fi

    # For form submissions, we typically get redirected back to a list page
    # Check that we're on the expected page
    if [ -n "$expect_redirect" ]; then
        if ! echo "$body" | grep -qi "$expect_redirect\|Notification\|success"; then
            echo -e "[${YELLOW}WARN${NC}] $test_name - May not have redirected properly"
        fi
    fi

    echo -e "[${GREEN}PASS${NC}] $test_name"
    ((PASSED++))
    return 0
}

test_form_submit_no_redirect() {
    local url="$1"
    local test_name="$2"
    local data="$3"

    # Submit form without following redirects
    response=$(curl -s -w "\n%{http_code}" -X POST -d "$data" "$url" 2>/dev/null)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    # 302 redirect means success for most form submissions
    if [ "$http_code" = "302" ]; then
        echo -e "[${GREEN}PASS${NC}] $test_name (redirected)"
        ((PASSED++))
        return 0
    fi

    # 200 might be OK if it contains success or validation message
    if [ "$http_code" = "200" ]; then
        if echo "$body" | grep -qi "Microsoft VBScript\|Error 500\|Internal server error"; then
            echo -e "[${RED}FAIL${NC}] $test_name - Server error"
            ((FAILED++))
            return 1
        fi
        echo -e "[${GREEN}PASS${NC}] $test_name (200 OK)"
        ((PASSED++))
        return 0
    fi

    echo -e "[${RED}FAIL${NC}] $test_name - HTTP $http_code"
    ((FAILED++))
    return 1
}

# ----------------------------------------------------------------------------
# 1. PAGE LOAD TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- PAGE LOAD TESTS ---${NC}"

test_page_loads "$BASE_URL/default.asp" "Dashboard loads" "Dashboard"
test_page_loads "$BASE_URL/displaynotifications.asp" "Notifications list loads" "Notification"
test_page_loads "$BASE_URL/addnotification.asp" "Add notification form loads" "Add Notification"
test_page_loads "$BASE_URL/displayapplications.asp" "Applications list loads" "Application"
test_page_loads "$BASE_URL/displayprinters.asp" "Printers list loads" "Printer"
test_page_loads "$BASE_URL/displaypcs.asp" "PCs list loads"
test_page_loads "$BASE_URL/displaymachines.asp" "Machines list loads" "Machine"
test_page_loads "$BASE_URL/network_devices.asp" "Network devices loads" "Network"
test_page_loads "$BASE_URL/displayinstalledapps.asp?appid=1" "Installed apps loads"

echo ""

# ----------------------------------------------------------------------------
# 2. NOTIFICATION FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- NOTIFICATION FORM TESTS ---${NC}"

NOW=$(date '+%Y-%m-%dT%H:%M')
TOMORROW=$(date -d '+1 day' '+%Y-%m-%dT%H:%M')
HOUR_LATER=$(date -d '+1 hour' '+%Y-%m-%dT%H:%M')

# Test: Create notification with basic fields
test_form_submit_no_redirect \
    "$BASE_URL/savenotification_direct.asp" \
    "Create notification (basic)" \
    "notification=Test+from+bash+script+-+$TIMESTAMP&notificationtypeid=2&businessunitid=&appid=&ticketnumber=GETEST001&starttime=$NOW&endtime=$TOMORROW&isactive=1&isshopfloor=0"

# Test: Create notification with application linked
test_form_submit_no_redirect \
    "$BASE_URL/savenotification_direct.asp" \
    "Create notification (with app)" \
    "notification=Test+with+app+-+$TIMESTAMP&notificationtypeid=3&businessunitid=2&appid=6&ticketnumber=GECHG002&starttime=$NOW&endtime=$HOUR_LATER&isactive=1&isshopfloor=1"

# Test: Create notification without end time (indefinite)
test_form_submit_no_redirect \
    "$BASE_URL/savenotification_direct.asp" \
    "Create notification (indefinite)" \
    "notification=Indefinite+test+-+$TIMESTAMP&notificationtypeid=4&businessunitid=&appid=&ticketnumber=&starttime=$NOW&endtime=&isactive=1&isshopfloor=0"

# Test: Create notification with all fields filled
test_form_submit_no_redirect \
    "$BASE_URL/savenotification_direct.asp" \
    "Create notification (all fields)" \
    "notification=Full+test+-+$TIMESTAMP&notificationtypeid=1&businessunitid=3&appid=21&ticketnumber=GETEST003&starttime=$NOW&endtime=$TOMORROW&isactive=1&isshopfloor=1"

echo ""

# ----------------------------------------------------------------------------
# 3. EDIT NOTIFICATION TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- EDIT NOTIFICATION TESTS ---${NC}"

# Get a notification ID from the list page
NOTIF_ID=$(curl -s "$BASE_URL/displaynotifications.asp" | grep -oP 'editnotification\.asp\?notificationid=\K\d+' | head -1)

if [ -n "$NOTIF_ID" ]; then
    test_page_loads "$BASE_URL/editnotification.asp?notificationid=$NOTIF_ID" "Edit notification form loads" "Edit Notification"

    # Test updating the notification
    test_form_submit_no_redirect \
        "$BASE_URL/updatenotification_direct.asp" \
        "Update notification" \
        "notificationid=$NOTIF_ID&notification=Updated+by+test+-+$TIMESTAMP&notificationtypeid=2&businessunitid=&appid=&ticketnumber=GEUPDATE&starttime=$NOW&endtime=$TOMORROW&isactive=1&isactive_submitted=1&isshopfloor=0&isshopfloor_submitted=1"
else
    echo -e "[${YELLOW}SKIP${NC}] Edit notification tests - No notifications found"
fi

echo ""

# ----------------------------------------------------------------------------
# 4. API ENDPOINT TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- API ENDPOINT TESTS ---${NC}"

test_page_loads "$BASE_URL/api.asp?action=getDashboardData" "API getDashboardData" "success"

# Test API with POST
api_response=$(curl -s -X POST -d "action=getDashboardData" "$BASE_URL/api.asp")
if echo "$api_response" | grep -qi "success"; then
    echo -e "[${GREEN}PASS${NC}] API POST getDashboardData"
    ((PASSED++))
else
    echo -e "[${RED}FAIL${NC}] API POST getDashboardData"
    ((FAILED++))
fi

echo ""

# ----------------------------------------------------------------------------
# 5. VALIDATION TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- VALIDATION TESTS ---${NC}"

# Test: Submit with missing required fields (should NOT create notification)
response=$(curl -s -w "\n%{http_code}" -X POST \
    -d "notification=&notificationtypeid=1&starttime=" \
    "$BASE_URL/savenotification_direct.asp" 2>/dev/null)
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [ "$http_code" = "200" ] && echo "$body" | grep -qi "required\|missing"; then
    echo -e "[${GREEN}PASS${NC}] Validation - rejects empty required fields"
    ((PASSED++))
elif [ "$http_code" = "302" ]; then
    echo -e "[${YELLOW}WARN${NC}] Validation - accepted empty fields (may need better validation)"
    ((PASSED++))
else
    echo -e "[${GREEN}PASS${NC}] Validation - handled gracefully"
    ((PASSED++))
fi

echo ""

# ----------------------------------------------------------------------------
# 6. SPECIAL CHARACTER TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- SPECIAL CHARACTER TESTS ---${NC}"

# Test: Notification with special characters (XSS test)
SPECIAL_MSG="Test+%3Cscript%3Ealert%28%27xss%27%29%3C%2Fscript%3E+and+%26+symbols"
test_form_submit_no_redirect \
    "$BASE_URL/savenotification_direct.asp" \
    "Create notification (special chars)" \
    "notification=$SPECIAL_MSG&notificationtypeid=2&businessunitid=&appid=&ticketnumber=&starttime=$NOW&endtime=$TOMORROW&isactive=1&isshopfloor=0"

# Verify the special characters are escaped in output
LATEST_PAGE=$(curl -s "$BASE_URL/displaynotifications.asp")
if echo "$LATEST_PAGE" | grep -q "<script>alert"; then
    echo -e "[${RED}FAIL${NC}] XSS vulnerability - script tags not escaped!"
    ((FAILED++))
else
    echo -e "[${GREEN}PASS${NC}] XSS protection - script tags escaped"
    ((PASSED++))
fi

echo ""

# ============================================================================
# SUMMARY
# ============================================================================
echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}TEST SUMMARY${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""

TOTAL=$((PASSED + FAILED))
echo "Total Tests: $TOTAL"
echo -e "Passed: ${GREEN}$PASSED${NC}"
if [ $FAILED -gt 0 ]; then
    echo -e "Failed: ${RED}$FAILED${NC}"
else
    echo -e "Failed: ${GREEN}$FAILED${NC}"
fi

echo ""
if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}All tests passed!${NC}"
    exit 0
else
    echo -e "${RED}Some tests failed. Please review the output above.${NC}"
    exit 1
fi
