#!/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 "===== Fixing Login Issues (Simple Version) ====="

# Fix the login form to use correct redirect
echo "1. Fixing login form..."
LOGIN_HANDLER_FIX="<?php
// Load WordPress
require_once('wp-load.php');

// Fix 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);
    
    // Enable login failure handler
    if (strpos(\$content, '// add_action(\\'wp_login_failed\\'') !== false) {
        \$content = str_replace(
            '// add_action(\\'wp_login_failed\\', array(\$this, \\'handle_login_failure\\'));',
            'add_action(\\'wp_login_failed\\', array(\$this, \\'handle_login_failure\\'));',
            \$content
        );
        echo \"Fixed login failure handler\\n\";
    }
    
    // Add redirect to login form
    if (strpos(\$content, '\$args[\\'redirect\\']') === false) {
        \$content = str_replace(
            'wp_login_form( \$args );',
            '\$args[\\'redirect\\'] = home_url(\\'/hvac-dashboard/\\');' . \"\\n\\t\\t\" . 'wp_login_form( \$args );',
            \$content
        );
        echo \"Added redirect to login form\\n\";
    }
    
    // Save changes
    if (file_put_contents(\$login_handler_path, \$content)) {
        echo \"Saved changes to login handler\\n\";
    } else {
        echo \"Failed to save changes\\n\";
    }
}

// Reset test_trainer user
\$user = get_user_by('login', 'test_trainer');
if (\$user) {
    wp_set_password('test_password', \$user->ID);
    echo \"Reset password for test_trainer\\n\";
    
    // Clear sessions
    \$sessions = WP_Session_Tokens::get_instance(\$user->ID);
    \$sessions->destroy_all();
    echo \"Cleared user sessions\\n\";
}

// Clear cache
\$cache_dirs = array(
    WP_CONTENT_DIR . '/cache/breeze',
    WP_CONTENT_DIR . '/uploads/breeze/css',
    WP_CONTENT_DIR . '/uploads/breeze/js'
);

foreach (\$cache_dirs as \$dir) {
    if (is_dir(\$dir)) {
        \$files = glob(\$dir . '/*');
        if (\$files) {
            foreach (\$files as \$file) {
                if (is_file(\$file)) {
                    @unlink(\$file);
                }
            }
        }
        echo \"Cleared cache directory: \$dir\\n\";
    }
}

echo \"Login fix complete\\n\";
"

# Send the fix script
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > fix-login.php << 'EOF'
$LOGIN_HANDLER_FIX
EOF"

# Execute the PHP script
echo "Executing fix script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php fix-login.php"

# Create a direct login test
echo -e "\n2. Testing direct login..."
DIRECT_LOGIN_TEST="<?php
// Load WordPress
require_once('wp-load.php');

// Test direct login
\$result = wp_authenticate('test_trainer', 'test_password');
if (is_wp_error(\$result)) {
    echo \"Authentication failed: \" . \$result->get_error_message() . \"\\n\";
} else {
    echo \"Authentication successful for user ID: {\$result->ID}\\n\";
    echo \"User login: {\$result->user_login}\\n\";
    echo \"User roles: \" . implode(', ', \$result->roles) . \"\\n\";
    
    // Try setting auth cookie
    wp_set_auth_cookie(\$result->ID, true);
    echo \"Set auth cookie\\n\";
}

echo \"Login test complete\\n\";
"

# Send the test script
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > test-login.php << 'EOF'
$DIRECT_LOGIN_TEST
EOF"

# Execute the test script
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php test-login.php"

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

echo -e "\n===== Login Fix Complete ====="
echo "The login issues should now be fixed."
echo "Please try logging in with username 'test_trainer' and password 'test_password'."
echo "Login URL: http://upskill-staging.measurequick.com/community-login/"