#!/bin/bash

# Complete Zoho OAuth Setup Script
set -e

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

echo -e "${BLUE}=== Complete Zoho OAuth Setup ===${NC}"
echo

PLUGIN_DIR="/Users/ben/dev/upskill-event-manager/wordpress-dev/wordpress/wp-content/plugins/hvac-community-events"
ZOHO_DIR="$PLUGIN_DIR/includes/zoho"

# Step 1: Start callback server
echo -e "${GREEN}Starting callback server...${NC}"
cd "$ZOHO_DIR"
php -S localhost:8080 callback-server.php &
SERVER_PID=$!
echo "Callback server started (PID: $SERVER_PID)"
echo

# Step 2: Display authorization URL
echo -e "${GREEN}Please complete authorization:${NC}"
echo
echo -e "${YELLOW}1. Open this URL in your browser:${NC}"
echo
echo "https://accounts.zoho.com/oauth/v2/auth?scope=ZohoCRM.settings.all%2CZohoCRM.modules.all%2CZohoCRM.users.all%2CZohoCRM.org.all&client_id=1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS&response_type=code&access_type=offline&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&prompt=consent"
echo
echo -e "${YELLOW}2. Log in to Zoho and accept permissions${NC}"
echo -e "${YELLOW}3. Copy the authorization code from the callback page${NC}"
echo -e "${YELLOW}4. Return here and paste the code${NC}"
echo

# Step 3: Wait for callback
echo -e "${GREEN}Waiting for authorization...${NC}"
echo "Once you've authorized, you'll see the code at: http://localhost:8080/callback"
echo
read -p "Enter the authorization code: " AUTH_CODE

# Step 4: Stop callback server
kill $SERVER_PID 2>/dev/null || true
echo

# Step 5: Run integration test with the code
echo -e "${GREEN}Testing integration with authorization code...${NC}"
cd "$ZOHO_DIR"
echo "$AUTH_CODE" | php test-integration.php

echo
echo -e "${GREEN}✓ Setup complete!${NC}"
echo
echo "The Zoho configuration has been saved to:"
echo "$ZOHO_DIR/zoho-config.php"
echo
echo "You can now sync data to Zoho CRM!"