#!/bin/bash

# HVAC Trainer CSV Import Script Wrapper
# Usage: ./scripts/import-trainers.sh

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

echo -e "${BLUE}=== HVAC Trainer CSV Import ===${NC}"
echo "Date: $(date)"
echo ""

# Check if CSV file exists
CSV_FILE="CSV_Trainers_Import_1Aug2025.csv"
if [ ! -f "$CSV_FILE" ]; then
    echo -e "${RED}❌ Error: CSV file '$CSV_FILE' not found in current directory${NC}"
    echo "Please ensure the CSV file is in the project root directory."
    exit 1
fi

echo -e "${GREEN}✅ Found CSV file: $CSV_FILE${NC}"
echo ""

# Check if we're on staging server
if [[ "$HOSTNAME" =~ "cloudways" ]] || [[ "$PWD" =~ "cloudwaysapps" ]]; then
    echo -e "${YELLOW}⚠️  Running on staging server${NC}"
    STAGING=true
else
    echo -e "${BLUE}ℹ️  Running on local development environment${NC}"
    STAGING=false
fi

echo ""

# Confirmation prompt
echo -e "${YELLOW}This will import/update users, create venues and organizers from the CSV file.${NC}"
echo -e "${YELLOW}Email notifications will be temporarily disabled during import.${NC}"
echo ""
read -p "Do you want to continue? (y/N): " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${RED}Import cancelled.${NC}"
    exit 1
fi

echo ""
echo -e "${BLUE}Starting import...${NC}"
echo ""

# Run the import script
if [ "$STAGING" = true ]; then
    # On staging server, use wp-cli directly
    wp eval-file bin/import-trainers-from-csv.php --path=/home/974670.cloudwaysapps.com/uberrxmprk/public_html
    RESULT=$?
else
    # On local development, check if WP-CLI is available
    if command -v wp &> /dev/null; then
        wp eval-file bin/import-trainers-from-csv.php
        RESULT=$?
    else
        echo -e "${RED}❌ Error: WP-CLI not found${NC}"
        echo "Please install WP-CLI or run this script on the staging server."
        exit 1
    fi
fi

echo ""

# Check result
if [ $RESULT -eq 0 ]; then
    echo -e "${GREEN}✅ Import completed successfully!${NC}"
    
    if [ "$STAGING" = true ]; then
        echo ""
        echo -e "${BLUE}🔗 You can now test the imported users at:${NC}"
        echo "  • Login: https://upskill-staging.measurequick.com/training-login/"
        echo "  • Dashboard: https://upskill-staging.measurequick.com/trainer/dashboard/"
        echo ""
        echo -e "${YELLOW}💡 Note: New users will need to reset their passwords${NC}"
    fi
else
    echo -e "${RED}❌ Import failed with exit code: $RESULT${NC}"
    exit $RESULT
fi