#!/bin/bash

# Zoho CRM Integration Test Script
# This script tests the Zoho integration setup

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

# Get the script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
ZOHO_DIR="$PROJECT_ROOT/wordpress/wp-content/plugins/hvac-community-events/includes/zoho"

echo -e "${GREEN}=== Zoho CRM Integration Test ===${NC}\n"

# Check if .env file exists
if [ ! -f "$PROJECT_ROOT/.env" ]; then
    echo -e "${RED}Error: .env file not found at $PROJECT_ROOT/.env${NC}"
    exit 1
fi

# Source the .env file
source "$PROJECT_ROOT/.env"

# Check if credentials exist
if [ -z "$ZOHO_CLIENT_ID" ] || [ -z "$ZOHO_CLIENT_SECRET" ]; then
    echo -e "${RED}Error: ZOHO_CLIENT_ID or ZOHO_CLIENT_SECRET not found in .env file${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Credentials found in .env file${NC}"
echo -e "Client ID: ${ZOHO_CLIENT_ID:0:20}...\n"

# Change to Zoho directory
cd "$ZOHO_DIR"

# Check if PHP is available
if ! command -v php &> /dev/null; then
    echo -e "${RED}Error: PHP is not installed${NC}"
    exit 1
fi

echo -e "${YELLOW}Starting Zoho integration test...${NC}\n"

# Option to start auth server
echo -e "${YELLOW}Would you like to start the OAuth callback server? (y/n)${NC}"
read -p "This will help capture the authorization code automatically: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "\n${GREEN}Starting OAuth callback server...${NC}"
    echo -e "${YELLOW}Keep this terminal open and start a new terminal for the next step.${NC}\n"
    php "$ZOHO_DIR/auth-server.php"
else
    echo -e "\n${GREEN}Running test integration script...${NC}"
    php "$ZOHO_DIR/test-integration.php"
fi

echo -e "\n${GREEN}=== Test Complete ===${NC}"