#!/bin/bash

# Exit on error
set -e

# Source environment variables
if [ -f ".env" ]; then
    source .env
else
    echo "Error: .env file not found. Please create it with the required variables."
    exit 1
fi

echo "===== Verifying test_trainer User ====="

# Get the user ID
echo "Getting user ID..."
USER_ID=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp user get test_trainer --field=ID")
echo "User ID: $USER_ID"

# Get the user login
echo "Getting username..."
USERNAME=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp user get $USER_ID --field=user_login")
echo "Username: $USERNAME"

# Get the user roles
echo "Getting user roles..."
ROLES=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp user meta get $USER_ID wp_capabilities")
echo "Roles: $ROLES"

# Create a PHP script to verify the user authentication
echo "Creating authentication test script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > test-authentication.php << 'EOF'
<?php
// Load WordPress
require_once('wp-load.php');

// Test direct authentication
\$username = 'test_trainer';
\$password = 'test_password';

\$user = wp_authenticate(\$username, \$password);

if (is_wp_error(\$user)) {
    echo \"Authentication Error: \" . \$user->get_error_message() . \"\n\";
} else {
    echo \"Authentication successful for user ID: {\$user->ID}\n\";
    echo \"User login: {\$user->user_login}\n\";
    echo \"User roles: \" . implode(', ', \$user->roles) . \"\n\";
}

// Check if login handler has wp_login_failed action
\$has_login_failure_handler = false;
global \$wp_filter;
if (isset(\$wp_filter['wp_login_failed'])) {
    foreach (\$wp_filter['wp_login_failed']->callbacks as \$priority => \$callbacks) {
        foreach (\$callbacks as \$callback) {
            if (is_array(\$callback['function']) && is_object(\$callback['function'][0]) && 
                get_class(\$callback['function'][0]) === 'HVAC_Community_Events\\Community\\Login_Handler') {
                \$has_login_failure_handler = true;
                echo \"Login failure handler is active\n\";
                break 2;
            }
        }
    }
}

if (!\$has_login_failure_handler) {
    echo \"Login failure handler is NOT active\n\";
    
    // Try to fix the login handler
    \$login_handler_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/community/class-login-handler.php';
    if (file_exists(\$login_handler_path)) {
        \$content = file_get_contents(\$login_handler_path);
        if (strpos(\$content, '// add_action(\'wp_login_failed\'') !== false) {
            \$fixed_content = str_replace(
                '// add_action(\'wp_login_failed\', array($this, \'handle_login_failure\'));',
                'add_action(\'wp_login_failed\', array($this, \'handle_login_failure\'));',
                \$content
            );
            file_put_contents(\$login_handler_path, \$fixed_content);
            echo \"Fixed login failure handler in file\n\";
        }
    }
}

// Test login with WP core function
\$creds = array(
    'user_login'    => \$username,
    'user_password' => \$password,
    'remember'      => true
);

\$login_result = wp_signon(\$creds, false);
if (is_wp_error(\$login_result)) {
    echo \"wp_signon Error: \" . \$login_result->get_error_message() . \"\n\";
} else {
    echo \"wp_signon successful for user ID: {\$login_result->ID}\n\";
}

// Get URLs to display to user for testing
\$login_url = site_url('/community-login/');
\$dashboard_url = site_url('/hvac-dashboard/');

echo \"\nTest URLs:\n\";
echo \"Login Page: {\$login_url}\n\";
echo \"Dashboard: {\$dashboard_url}\n\";
EOF"

# Execute the authentication test
echo -e "\nRunning authentication test..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php test-authentication.php"

# Clean up
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && rm test-authentication.php"

echo -e "\n===== Verification Complete ====="