#!/bin/bash

# Manual Test Data Cleanup Script
# Uses the same method as deploy-to-staging.sh

set -e

# Load environment variables
if [ -f .env ]; then
    export $(cat .env | sed 's/#.*//g' | xargs)
fi

# Check required variables
if [ -z "$UPSKILL_STAGING_IP" ] || [ -z "$UPSKILL_STAGING_SSH_USER" ]; then
    echo "❌ Missing required environment variables"
    echo "Required: UPSKILL_STAGING_IP, UPSKILL_STAGING_SSH_USER"
    exit 1
fi

STAGING_HOST="$UPSKILL_STAGING_IP"
STAGING_USER="$UPSKILL_STAGING_SSH_USER"
STAGING_PATH="$UPSKILL_STAGING_PATH"

echo "========================================="
echo "🧹 MANUAL TEST DATA CLEANUP"
echo "========================================="
echo "Target: $STAGING_HOST"
echo "User: $STAGING_USER"
echo "Path: $STAGING_PATH"
echo ""

# Create cleanup PHP script locally
cat > cleanup-manual.php << 'EOF'
<?php
require_once('wp-load.php');

echo "=== Manual Cleanup Starting ===\n";

$deleted_items = 0;

// 1. Remove test users by login
echo "Removing test users...\n";
$test_users = ['test_trainer', 'joemedosch'];
foreach ($test_users as $username) {
    $user = get_user_by('login', $username);
    if ($user) {
        echo "  - Removing user: {$username} ({$user->user_email})\n";
        wp_delete_user($user->ID, 1); // Reassign content to admin
        $deleted_items++;
    }
}

// Remove JoeMedosch by email
$joe_user = get_user_by('email', 'JoeMedosch@gmail.com');
if ($joe_user) {
    echo "  - Removing JoeMedosch@gmail.com\n";
    wp_delete_user($joe_user->ID, 1);
    $deleted_items++;
}

// Remove HVAC roles from joe@measurequick.com
$joe_mq = get_user_by('email', 'joe@measurequick.com');
if ($joe_mq) {
    $user = new WP_User($joe_mq->ID);
    $had_roles = false;
    if (in_array('hvac_trainer', $user->roles)) {
        $user->remove_role('hvac_trainer');
        $had_roles = true;
    }
    if (in_array('hvac_master_trainer', $user->roles)) {
        $user->remove_role('hvac_master_trainer');  
        $had_roles = true;
    }
    if ($had_roles) {
        echo "  - Removed HVAC roles from joe@measurequick.com\n";
        $deleted_items++;
    }
}

// 2. Remove events with specific test patterns
echo "Removing test events...\n";
$test_patterns = [
    'HVAC System Diagnostics',
    'Commercial Refrigeration', 
    'Energy Efficient HVAC',
    'Advanced HVAC Troubleshooting',
    'HVAC Energy Efficiency Workshop',
    'Commercial Refrigeration Systems',
    'Residential HVAC Installation Best Practices',
    'HVAC Controls and Automation',
    'AUER STEEL'
];

foreach ($test_patterns as $pattern) {
    $events = get_posts([
        'post_type' => 'tribe_events',
        's' => $pattern,
        'posts_per_page' => -1,
        'post_status' => 'any'
    ]);
    
    foreach ($events as $event) {
        echo "  - Removing event: {$event->post_title} (ID: {$event->ID})\n";
        
        // Remove associated data first
        $attendees = get_posts([
            'post_type' => 'tribe_tpp_attendees',
            'meta_query' => [['key' => '_tribe_tpp_event', 'value' => $event->ID]],
            'posts_per_page' => -1
        ]);
        foreach ($attendees as $attendee) {
            wp_delete_post($attendee->ID, true);
        }
        
        $tickets = get_posts([
            'post_type' => 'tribe_tpp_tickets', 
            'meta_query' => [['key' => '_tribe_tpp_for_event', 'value' => $event->ID]],
            'posts_per_page' => -1
        ]);
        foreach ($tickets as $ticket) {
            wp_delete_post($ticket->ID, true);
        }
        
        wp_delete_post($event->ID, true);
        $deleted_items++;
    }
}

// 3. Remove attendees with @example.com emails
echo "Removing test attendees...\n";
$attendees = get_posts([
    'post_type' => 'tribe_tpp_attendees',
    'meta_query' => [['key' => '_tribe_tickets_email', 'value' => '@example.com', 'compare' => 'LIKE']], 
    'posts_per_page' => -1
]);
foreach ($attendees as $attendee) {
    $email = get_post_meta($attendee->ID, '_tribe_tickets_email', true);
    echo "  - Removing test attendee: {$attendee->post_title} ({$email})\n";
    wp_delete_post($attendee->ID, true);
    $deleted_items++;
}

// 4. Remove clear test organizers and venues
echo "Removing test organizers and venues...\n";
$test_organizers = get_posts([
    'post_type' => 'tribe_organizer',
    'posts_per_page' => -1,
    'post_status' => 'any'
]);
foreach ($test_organizers as $organizer) {
    $title_lower = strtolower($organizer->post_title);
    if (strpos($title_lower, 'test') !== false || strpos($title_lower, 'bentest') !== false) {
        echo "  - Removing test organizer: {$organizer->post_title}\n";
        wp_delete_post($organizer->ID, true);
        $deleted_items++;
    }
}

$test_venues = get_posts([
    'post_type' => 'tribe_venue',
    'posts_per_page' => -1,
    'post_status' => 'any'
]);
foreach ($test_venues as $venue) {
    $title_lower = strtolower($venue->post_title);
    if (strpos($title_lower, 'training center') !== false || strpos($title_lower, 'test') !== false) {
        echo "  - Removing test venue: {$venue->post_title}\n";
        wp_delete_post($venue->ID, true);
        $deleted_items++;
    }
}

// Clear caches
wp_cache_flush();

echo "=== Manual Cleanup Complete ===\n";
echo "Total items removed: {$deleted_items}\n";
?>
EOF

# Try to upload and execute without sshpass first (key-based auth)
echo "📤 Attempting to upload cleanup script..."
if scp -o StrictHostKeyChecking=no cleanup-manual.php $STAGING_USER@$STAGING_HOST:tmp/ 2>/dev/null; then
    echo "✅ Upload successful (key-based auth)"
    echo "🧹 Executing cleanup..."
    ssh -o StrictHostKeyChecking=no $STAGING_USER@$STAGING_HOST "cd $STAGING_PATH && php ../tmp/cleanup-manual.php && rm ../tmp/cleanup-manual.php"
else
    echo "❌ Key-based auth failed. Please run cleanup manually:"
    echo ""
    echo "1. Copy this content to a file on the server:"
    echo "   File: cleanup-manual.php"
    echo ""
    cat cleanup-manual.php
    echo ""
    echo "2. Run: cd $STAGING_PATH && php cleanup-manual.php"
    echo ""
fi

# Clean up local file
rm cleanup-manual.php

echo ""
echo "✅ Manual cleanup process completed!"