#!/bin/bash

# Get absolute path to this script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Navigate to wordpress-dev directory
cd "$(dirname "$SCRIPT_DIR")" || exit 1

# Load environment variables
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"

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

echo "=== Fixing Event Organizer IDs on Staging Server ==="
echo "Remote host: $UPSKILL_STAGING_IP"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "==============================="

# Create PHP script to fix the organizer IDs
cat << 'EOF' > fix-organizers.php
<?php
// Load WordPress
require_once dirname(dirname(__FILE__)) . '/public_html/wp-load.php';

// Get test_trainer user ID
$trainer_user = get_user_by('login', 'test_trainer');
if (!$trainer_user) {
    die("Error: test_trainer user not found\n");
}

$trainer_id = $trainer_user->ID;
echo "test_trainer user ID: $trainer_id\n\n";

// Get all events authored by test_trainer
$args = array(
    'post_type' => 'tribe_events',
    'author' => $trainer_id,
    'post_status' => 'any',
    'posts_per_page' => -1,
    'fields' => 'ids'
);

$event_ids = get_posts($args);

if (empty($event_ids)) {
    // Try to find events by ID range
    echo "No events found by author. Checking recent events...\n";
    $args['author'] = 0;
    $args['meta_query'] = array(
        array(
            'key' => 'post_ID',
            'value' => array(5482, 5486),
            'compare' => 'BETWEEN',
            'type' => 'NUMERIC'
        )
    );
    
    // Actually, let's just get events in the ID range we created
    $event_ids = array(5482, 5483, 5484, 5485, 5486);
    
    foreach ($event_ids as $event_id) {
        if (get_post($event_id)) {
            echo "Processing event ID: $event_id\n";
            
            // Set the organizer ID to the trainer's user ID
            update_post_meta($event_id, '_EventOrganizerID', $trainer_id);
            
            // Also create an organizer post if it doesn't exist
            $organizer_exists = get_posts(array(
                'post_type' => 'tribe_organizer',
                'posts_per_page' => 1,
                'meta_key' => '_OrganizerUserID',
                'meta_value' => $trainer_id
            ));
            
            if (empty($organizer_exists)) {
                // Create organizer post
                $user_info = get_userdata($trainer_id);
                $organizer_id = wp_insert_post(array(
                    'post_type' => 'tribe_organizer',
                    'post_status' => 'publish',
                    'post_title' => $user_info->display_name . ' (Trainer)',
                    'meta_input' => array(
                        '_OrganizerPhone' => '',
                        '_OrganizerWebsite' => '',
                        '_OrganizerEmail' => $user_info->user_email,
                        '_OrganizerUserID' => $trainer_id
                    )
                ));
                
                if (!is_wp_error($organizer_id)) {
                    echo "Created organizer ID: $organizer_id\n";
                    // Update the event with the organizer ID
                    update_post_meta($event_id, '_EventOrganizerID', $organizer_id);
                }
            } else {
                // Use existing organizer
                $existing_organizer = $organizer_exists[0];
                update_post_meta($event_id, '_EventOrganizerID', $existing_organizer->ID);
                echo "Using existing organizer ID: {$existing_organizer->ID}\n";
            }
            
            echo "Updated event $event_id with organizer\n";
        }
    }
} else {
    echo "Found " . count($event_ids) . " events by test_trainer\n";
    
    foreach ($event_ids as $event_id) {
        echo "Processing event ID: $event_id\n";
        update_post_meta($event_id, '_EventOrganizerID', $trainer_id);
        echo "Updated event $event_id with organizer ID: $trainer_id\n";
    }
}

echo "\nOrganizer fixing completed!\n";
EOF

# Copy script to server
echo -e "\n${YELLOW}Copying script to server...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" scp fix-organizers.php "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}:${UPSKILL_STAGING_PATH}/"

# Execute the script
echo -e "\n${YELLOW}Running organizer fix script...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && /usr/bin/php fix-organizers.php"

# Clean up
echo -e "\n${YELLOW}Cleaning up...${NC}"
rm fix-organizers.php
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"rm ${UPSKILL_STAGING_PATH}/fix-organizers.php"

echo -e "\n${GREEN}Organizer fix completed!${NC}"