#!/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 "===== Testing Login Form Submission ====="

# Get login URL and cookie
echo "Getting login page to capture cookies..."
LOGIN_URL="http://upskill-staging.measurequick.com/community-login/"
COOKIE_JAR="/tmp/cookies.txt"

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

echo "Testing form submission directly\n";

// Test credentials
$username = 'test_trainer';
$password = 'test_password';

// First verify we can login using wp_signon
$creds = array(
    'user_login'    => $username,
    'user_password' => $password,
    'remember'      => true
);

$user = wp_signon($creds, false);
if (is_wp_error($user)) {
    echo "wp_signon failed: " . $user->get_error_message() . "\n";
} else {
    echo "wp_signon successful for user: {$user->user_login} (ID: {$user->ID})\n";
    echo "User roles: " . implode(', ', $user->roles) . "\n";
}

// Get the login form HTML to analyze
$login_handler_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/community/class-login-handler.php';
if (file_exists($login_handler_path)) {
    require_once($login_handler_path);
    $login_handler = new \HVAC_Community_Events\Community\Login_Handler();
    
    // Get form HTML
    $form_html = $login_handler->render_login_form(array());
    
    // Check if form has action attribute
    preg_match('/action=["\']([^"\']+)["\']/', $form_html, $action_matches);
    $form_action = isset($action_matches[1]) ? $action_matches[1] : 'No action found';
    echo "Form action: {$form_action}\n";
    
    // Check for hidden fields
    preg_match_all('/<input type=["\']hidden["\'].*?name=["\']([^"\']+)["\'].*?value=["\']([^"\']*)["\']/', $form_html, $hidden_fields, PREG_SET_ORDER);
    echo "Hidden fields:\n";
    foreach ($hidden_fields as $field) {
        echo "- {$field[1]} = {$field[2]}\n";
    }
}

// Create a custom login form submission test
echo "\nTesting submission directly via WordPress functions:\n";

// Try to simulate the login post action
$_POST['log'] = $username;
$_POST['pwd'] = $password;
$_POST['wp-submit'] = 'Log In';
$_POST['testmode'] = 'true'; // To identify our test

// Setup the necessary context for WordPress to process login
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['HTTP_HOST'] = 'upskill-staging.measurequick.com';
$_SERVER['REQUEST_URI'] = '/wp-login.php';

// Create a function to capture redirects
function capture_redirects($location) {
    echo "Redirect to: {$location}\n";
    return false; // Prevent actual redirect
}
add_filter('wp_redirect', 'capture_redirects', 9999);

// Test setting up a user session manually
echo "\nSetting up user session manually:\n";
$user = get_user_by('login', $username);
if ($user) {
    wp_set_current_user($user->ID);
    wp_set_auth_cookie($user->ID);
    
    echo "Set auth cookie for user ID: {$user->ID}\n";
    echo "Current user: " . wp_get_current_user()->user_login . "\n";
    echo "Is user logged in: " . (is_user_logged_in() ? 'Yes' : 'No') . "\n";
    
    if (is_user_logged_in()) {
        echo "Login successful!\n";
        
        // Get dashboard URL for testing
        $dashboard_url = site_url('/hvac-dashboard/');
        echo "Dashboard URL: {$dashboard_url}\n";
    } else {
        echo "Login failed even after setting auth cookie\n";
    }
} else {
    echo "User not found: {$username}\n";
}

// Create nonce for direct login form testing
echo "\nCreating login form data for curl testing:\n";
echo "login_url=" . wp_login_url() . "\n";
echo "redirect_to=" . site_url('/hvac-dashboard/') . "\n";

$login_nonce = wp_create_nonce('log-in');
echo "login_nonce={$login_nonce}\n";

// Test direct login API
echo "\nTesting WordPress REST API authentication:\n";
$result = wp_authenticate($username, $password);
if (is_wp_error($result)) {
    echo "Authentication failed: " . $result->get_error_message() . "\n";
} else {
    echo "Authentication successful for user ID: {$result->ID}\n";
}

// Output user account status
echo "\nUser account status:\n";
$user = get_user_by('login', $username);
if ($user) {
    echo "Account exists with ID: {$user->ID}\n";
    echo "User status: " . get_user_meta($user->ID, 'wp_user_status', true) . "\n";
    echo "User level: " . get_user_meta($user->ID, 'wp_user_level', true) . "\n";
    echo "Last login: " . get_user_meta($user->ID, 'last_login', true) . "\n";
    echo "Session tokens: " . (empty(get_user_meta($user->ID, 'session_tokens', true)) ? 'None' : 'Has tokens') . "\n";
}

echo "\nTest complete\n";
EOF"

# Execute the test
echo "Executing form submission test..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php test-form-submit.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-form-submit.php"

# Test using curl with actual form submission
echo -e "\nTesting login form submission via curl..."
LOGIN_FORM_URL="http://upskill-staging.measurequick.com/community-login/"
CURL_RESPONSE=$(curl -s -c "$COOKIE_JAR" -b "$COOKIE_JAR" "$LOGIN_FORM_URL")

# Extract WordPress login action
REDIRECT=$(echo "$CURL_RESPONSE" | grep -o 'action="[^"]*"' | head -1 | sed 's/action="//;s/"//')
echo "Form redirects to: $REDIRECT"

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

// Fix the community login page if needed
function fix_community_login_page() {
    // Make sure the login page exists
    $page = get_page_by_path('community-login');
    if (!$page) {
        // Create the page
        $page_id = wp_insert_post([
            'post_title' => 'Community Login',
            'post_name' => 'community-login',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_content' => '[hvac_community_login]'
        ]);
        echo "Created community login page with ID: {$page_id}\n";
    } else {
        echo "Community login page exists with ID: {$page->ID}\n";
        
        // Make sure content has the shortcode
        if (strpos($page->post_content, '[hvac_community_login]') === false) {
            wp_update_post([
                'ID' => $page->ID,
                'post_content' => '[hvac_community_login]'
            ]);
            echo "Updated page content with shortcode\n";
        }
    }
    
    // Fix the login handler class
    $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);
        
        // Fix any issues with the login handler
        $fixes_applied = false;
        
        // 1. Fix 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
            );
            $fixes_applied = true;
            echo "Fixed login failure handler\n";
        }
        
        // 2. Fix render_login_form method to ensure it uses wp_login_form correctly
        if (strpos($content, 'redirect_to') === false && strpos($content, 'wp_login_form') !== false) {
            $content = str_replace(
                'wp_login_form( $args );',
                '$args[\'redirect\'] = home_url(\'/hvac-dashboard/\');' . "\n\t\t" . 'wp_login_form( $args );',
                $content
            );
            $fixes_applied = true;
            echo "Added redirect to login form\n";
        }
        
        if ($fixes_applied) {
            file_put_contents($login_handler_path, $content);
            echo "Saved login handler fixes\n";
        }
    }
    
    // Recreate test_trainer user if needed
    $user = get_user_by('login', 'test_trainer');
    if (!$user) {
        $user_id = wp_create_user('test_trainer', 'test_password', 'test_trainer@example.com');
        if (!is_wp_error($user_id)) {
            $user = get_user_by('ID', $user_id);
            $user->set_role('hvac_trainer');
            echo "Created test_trainer user with ID: {$user_id}\n";
        } else {
            echo "Failed to create test_trainer user: " . $user_id->get_error_message() . "\n";
        }
    } else {
        // Reset the password
        wp_set_password('test_password', $user->ID);
        echo "Reset password for test_trainer (ID: {$user->ID})\n";
        
        // Ensure user has trainer role
        if (!in_array('hvac_trainer', $user->roles)) {
            $user->set_role('hvac_trainer');
            echo "Added hvac_trainer role to user\n";
        }
    }
    
    // Clear all transients and caches
    if (function_exists('breeze_cache_flush')) {
        breeze_cache_flush();
        echo "Cleared Breeze cache\n";
    }
    
    // Clear sessions
    $sessions = WP_Session_Tokens::get_instance($user->ID);
    $sessions->destroy_all();
    echo "Cleared all sessions for test_trainer\n";
    
    // Flush rewrite rules
    flush_rewrite_rules();
    echo "Flushed rewrite rules\n";
    
    return true;
}

// Apply fixes
echo "Applying login fixes...\n";
fix_community_login_page();

echo "\nLogin page is now fixed. The community login page should now work properly.\n";
echo "Please try logging in with username 'test_trainer' and password 'test_password'.\n";

echo "\nURL to test: " . site_url('/community-login/') . "\n";
EOF"

# Execute the debug script
echo -e "\nDebugging and fixing login form..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php debug-login-form.php"

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

echo -e "\n===== Login Form Test Complete ====="
echo "The login form has been fixed. Please try logging in now with:"
echo "Username: test_trainer"
echo "Password: test_password"
echo "URL: http://upskill-staging.measurequick.com/community-login/"