#!/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 "===== Comprehensive Login Debug Script ====="

# Step 1: Check if the test_trainer user exists and get their details
echo -e "\n1. Checking test_trainer user details:"
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 --format=json"

# Step 2: Verify user roles and capabilities
echo -e "\n2. Checking user roles and capabilities:"
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp user meta get test_trainer wp_capabilities"

# Step 3: Test login authentication directly
echo -e "\n3. Testing authentication directly via wp-cli:"
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp eval 'echo \"Authentication result: \" . (wp_authenticate(\"test_trainer\", \"test_password\") instanceof WP_User ? \"Success\" : \"Failed\");'"

# Step 4: Create and execute a PHP diagnostic script for login
echo -e "\n4. Running comprehensive login diagnostic:"
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > login-debug.php << 'EOF'
<?php
// Load WordPress
require_once('wp-load.php');

echo \"===== Login Diagnostics =====\n\";

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

echo \"User ID: {\$user->ID}\n\";
echo \"Username: {\$user->user_login}\n\";
echo \"User email: {\$user->user_email}\n\";
echo \"User roles: \" . implode(', ', \$user->roles) . \"\n\";

// Check if user has the hvac_trainer role
echo \"Has hvac_trainer role: \" . (in_array('hvac_trainer', \$user->roles) ? 'Yes' : 'No') . \"\n\";

// Check capabilities
echo \"Has view_hvac_dashboard capability: \" . (user_can(\$user->ID, 'view_hvac_dashboard') ? 'Yes' : 'No') . \"\n\";
echo \"Has manage_hvac_events capability: \" . (user_can(\$user->ID, 'manage_hvac_events') ? 'Yes' : 'No') . \"\n\";

// Test password verification directly
\$password = 'test_password'; // Replace with actual test password if different
echo \"Password verification: \" . (wp_check_password(\$password, \$user->user_pass, \$user->ID) ? 'Correct' : 'Incorrect') . \"\n\";

// Test full login
\$creds = array(
    'user_login'    => 'test_trainer',
    'user_password' => \$password,
    'remember'      => false
);

\$login_result = wp_signon(\$creds, false);
if (is_wp_error(\$login_result)) {
    echo \"Login error: {\$login_result->get_error_message()}\n\";
} else {
    echo \"Login successful! User ID: {\$login_result->ID}\n\";
}

// Check for active plugins that might interfere with login
echo \"\nActive plugins that might affect login:\n\";
\$login_related_plugins = array('breeze', 'wp-super-cache', 'w3-total-cache', 'wordfence', 'better-wp-security', 'all-in-one-wp-security');
\$active_plugins = get_option('active_plugins');
\$found = false;

foreach (\$active_plugins as \$plugin) {
    foreach (\$login_related_plugins as \$related) {
        if (strpos(\$plugin, \$related) !== false) {
            echo \"- {\$plugin}\n\";
            \$found = true;
        }
    }
}

if (!\$found) {
    echo \"No known login-affecting plugins detected\n\";
}

// Check user session tokens
\$tokens = get_user_meta(\$user->ID, 'session_tokens', true);
echo \"\nUser has \" . (empty(\$tokens) ? 'no' : count(\$tokens)) . \" active session tokens\n\";

// Check cookie settings
echo \"\nCookie settings:\n\";
echo \"COOKIEPATH: \" . (defined('COOKIEPATH') ? COOKIEPATH : 'Not defined') . \"\n\";
echo \"COOKIE_DOMAIN: \" . (defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : 'Not defined') . \"\n\";
echo \"SITECOOKIEPATH: \" . (defined('SITECOOKIEPATH') ? SITECOOKIEPATH : 'Not defined') . \"\n\";
echo \"ADMIN_COOKIE_PATH: \" . (defined('ADMIN_COOKIE_PATH') ? ADMIN_COOKIE_PATH : 'Not defined') . \"\n\";
echo \"SECURE_AUTH_COOKIE: \" . (defined('SECURE_AUTH_COOKIE') ? SECURE_AUTH_COOKIE : 'Not defined') . \"\n\";
echo \"AUTH_COOKIE: \" . (defined('AUTH_COOKIE') ? AUTH_COOKIE : 'Not defined') . \"\n\";
echo \"LOGGED_IN_COOKIE: \" . (defined('LOGGED_IN_COOKIE') ? LOGGED_IN_COOKIE : 'Not defined') . \"\n\";

// Check login hooks
echo \"\nLogin hooks:\n\";
global \$wp_filter;
\$login_hooks = array('wp_login', 'login_redirect', 'login_form_login', 'login_init', 'wp_login_failed');
foreach (\$login_hooks as \$hook) {
    if (isset(\$wp_filter[\$hook])) {
        echo \"{\$hook} has \" . count(\$wp_filter[\$hook]) . \" callbacks\n\";
        foreach (\$wp_filter[\$hook]->callbacks as \$priority => \$callbacks) {
            foreach (\$callbacks as \$id => \$callback) {
                \$callback_name = '';
                if (is_array(\$callback['function'])) {
                    if (is_object(\$callback['function'][0])) {
                        \$callback_name = get_class(\$callback['function'][0]) . '::' . \$callback['function'][1];
                    } else {
                        \$callback_name = \$callback['function'][0] . '::' . \$callback['function'][1];
                    }
                } else if (is_string(\$callback['function'])) {
                    \$callback_name = \$callback['function'];
                } else {
                    \$callback_name = 'Anonymous function';
                }
                echo \"  - Priority {\$priority}: {\$callback_name}\n\";
            }
        }
    } else {
        echo \"{\$hook} has no callbacks\n\";
    }
}

// Check Breeze settings if active
if (in_array('breeze/breeze.php', \$active_plugins)) {
    echo \"\nBreeze cache settings:\n\";
    \$breeze_settings = get_option('breeze_options');
    if (\$breeze_settings) {
        echo \"Cache enabled: \" . (\$breeze_settings['cache_system'] ? 'Yes' : 'No') . \"\n\";
        echo \"Browser cache: \" . (\$breeze_settings['browser_cache'] ? 'Yes' : 'No') . \"\n\";
        echo \"Mobile cache: \" . (\$breeze_settings['mobile_cache'] ? 'Yes' : 'No') . \"\n\";
        echo \"Disable cache for logged-in users: \" . (\$breeze_settings['logged-in'] ? 'Yes' : 'No') . \"\n\";
        
        // Check if there are cache exceptions
        if (isset(\$breeze_settings['no_cache_pages']) && !empty(\$breeze_settings['no_cache_pages'])) {
            echo \"Pages excluded from cache: \" . \$breeze_settings['no_cache_pages'] . \"\n\";
        } else {
            echo \"No pages are excluded from cache\n\";
        }
    } else {
        echo \"No Breeze settings found\n\";
    }
}

echo \"\n===== End of Login Diagnostics =====\n\";
EOF"

# Execute the PHP diagnostic script
echo -e "\nExecuting login diagnostic script:"
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php login-debug.php"

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

# Step 6: Create a fix script for common login issues
echo -e "\n5. Creating a login 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-issues.php << 'EOF'
<?php
// Load WordPress
require_once('wp-load.php');

echo \"===== Applying Login Fixes =====\n\";

// 1. Re-enable login failure handler in the Login_Handler class
echo \"1. Checking for disabled login failure handler...\n\";
\$login_handler_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/community/class-login-handler.php';
\$login_handler_content = file_get_contents(\$login_handler_path);

if (strpos(\$login_handler_content, '// add_action(\'wp_login_failed\'') !== false) {
    // The login failure handler is commented out, let's uncomment it
    \$updated_content = str_replace(
        '// add_action(\'wp_login_failed\', array($this, \'handle_login_failure\'));',
        'add_action(\'wp_login_failed\', array($this, \'handle_login_failure\'));',
        \$login_handler_content
    );
    
    if (file_put_contents(\$login_handler_path, \$updated_content)) {
        echo \"✅ Login failure handler re-enabled\n\";
    } else {
        echo \"❌ Failed to update login handler file\n\";
    }
} else {
    echo \"✅ Login failure handler is already enabled\n\";
}

// 2. Create mu-plugin to disable Breeze cache for login-related pages
echo \"2. Creating mu-plugin to disable Breeze cache for login pages...\n\";
\$mu_plugins_dir = WP_CONTENT_DIR . '/mu-plugins';
if (!is_dir(\$mu_plugins_dir)) {
    mkdir(\$mu_plugins_dir);
}

\$disable_cache_path = \$mu_plugins_dir . '/hvac-disable-cache-for-login.php';
\$disable_cache_content = <<<'EOT'
<?php
/**
 * Plugin Name: HVAC - Disable Cache for Login Pages
 * Description: Disables caching for login-related pages to prevent authentication issues
 * Version: 1.0.0
 * Author: HVAC Community Events
 */

// Disable caching for login-related pages
function hvac_disable_cache_for_login() {
    // List of pages to disable cache for
    $no_cache_pages = [
        'community-login',
        'wp-login.php',
        'hvac-dashboard'
    ];
    
    // Check if we're on a login-related page
    $current_page = basename($_SERVER['REQUEST_URI']);
    $is_login_page = false;
    
    foreach ($no_cache_pages as $page) {
        if (strpos($current_page, $page) !== false) {
            $is_login_page = true;
            break;
        }
    }
    
    // Also check for login parameter
    if (isset($_GET['login']) || isset($_POST['log'])) {
        $is_login_page = true;
    }
    
    if ($is_login_page) {
        // Disable caching
        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true);
        }
        
        // Set no-cache headers
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header('Expires: Mon, 07 Jul 1997 05:00:00 GMT');
    }
}
add_action('init', 'hvac_disable_cache_for_login', 1);

// Disable Breeze specific caching for login pages
function hvac_disable_breeze_cache() {
    // Add login pages to Breeze no-cache list
    if (class_exists('Breeze_Options_Reader') && method_exists('Breeze_Options_Reader', 'get_option_value')) {
        $breeze_settings = Breeze_Options_Reader::get_option_value('basic_settings');
        
        if (is_array($breeze_settings)) {
            $no_cache_pages = isset($breeze_settings['no-cache-pages']) ? $breeze_settings['no-cache-pages'] : '';
            $login_urls = '/community-login/, /wp-login.php, /hvac-dashboard/';
            
            if (strpos($no_cache_pages, '/community-login/') === false) {
                // Add our login URLs to no-cache list
                $breeze_settings['no-cache-pages'] = $no_cache_pages . ($no_cache_pages ? ', ' : '') . $login_urls;
                
                // Update the settings
                $breeze_options = get_option('breeze_basic_settings');
                if (is_array($breeze_options)) {
                    $breeze_options = array_merge($breeze_options, $breeze_settings);
                    update_option('breeze_basic_settings', $breeze_options);
                }
            }
        }
    }
}
add_action('plugins_loaded', 'hvac_disable_breeze_cache');

// Force disable cache for logged-in users if Breeze is active
function hvac_modify_breeze_user_cache() {
    if (is_user_logged_in() && class_exists('Breeze_Options_Reader') && method_exists('Breeze_Options_Reader', 'get_option_value')) {
        $advanced_settings = Breeze_Options_Reader::get_option_value('advanced_settings');
        
        if (is_array($advanced_settings) && isset($advanced_settings['breeze-disable-admin'])) {
            $advanced_settings['breeze-disable-admin'] = '1';
            
            // Update the settings
            $breeze_options = get_option('breeze_advanced_settings');
            if (is_array($breeze_options)) {
                $breeze_options = array_merge($breeze_options, $advanced_settings);
                update_option('breeze_advanced_settings', $breeze_options);
            }
        }
    }
}
add_action('wp_login', 'hvac_modify_breeze_user_cache');
EOT;

if (file_put_contents(\$disable_cache_path, \$disable_cache_content)) {
    echo \"✅ Created mu-plugin to disable cache for login pages\n\";
} else {
    echo \"❌ Failed to create mu-plugin\n\";
}

// 3. Reset user capability for test_trainer
echo \"3. Verifying and fixing test_trainer capabilities...\n\";
\$user = get_user_by('login', 'test_trainer');
if (\$user) {
    // Make sure the user has the hvac_trainer role
    if (!in_array('hvac_trainer', \$user->roles)) {
        \$user->add_role('hvac_trainer');
        echo \"✅ Added hvac_trainer role to test_trainer user\n\";
    } else {
        echo \"✅ test_trainer already has hvac_trainer role\n\";
    }
    
    // Make sure the user has the view_hvac_dashboard capability
    if (!user_can(\$user->ID, 'view_hvac_dashboard')) {
        \$user_meta = get_user_meta(\$user->ID, 'wp_capabilities', true);
        if (is_array(\$user_meta)) {
            \$user_meta['view_hvac_dashboard'] = true;
            update_user_meta(\$user->ID, 'wp_capabilities', \$user_meta);
            echo \"✅ Added view_hvac_dashboard capability to test_trainer\n\";
        }
    } else {
        echo \"✅ test_trainer already has view_hvac_dashboard capability\n\";
    }
    
    // Clear user sessions
    \$sessions = WP_Session_Tokens::get_instance(\$user->ID);
    \$sessions->destroy_all();
    echo \"✅ Cleared all sessions for test_trainer\n\";
} else {
    echo \"❌ test_trainer user not found\n\";
}

// 4. Make sure admin role has dashboard access
echo \"4. Ensuring administrator role has dashboard access...\n\";
\$admin_role = get_role('administrator');
if (\$admin_role) {
    \$admin_role->add_cap('view_hvac_dashboard');
    \$admin_role->add_cap('manage_hvac_events');
    echo \"✅ Added dashboard capabilities to administrator role\n\";
}

// 5. Fix login template if needed
echo \"5. Verifying login template...\n\";
\$login_template_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/community/login-form.php';
\$login_template_content = file_get_contents(\$login_template_path);

// Add debug parameter to help troubleshoot login issues
if (strpos(\$login_template_content, 'login_debug') === false) {
    // Find the wp_login_form line
    \$updated_template = str_replace(
        'wp_login_form( $args );',
        'echo "<input type=\"hidden\" name=\"login_debug\" value=\"1\" />";' . PHP_EOL . 'wp_login_form( $args );',
        \$login_template_content
    );
    
    if (file_put_contents(\$login_template_path, \$updated_template)) {
        echo \"✅ Added debug parameter to login form\n\";
    } else {
        echo \"❌ Failed to update login template\n\";
    }
} else {
    echo \"✅ Login template already has debug parameter\n\";
}

// 6. Clear Breeze cache
echo \"6. Clearing Breeze cache...\n\";
if (function_exists('breeze_cache_flush')) {
    breeze_cache_flush();
    echo \"✅ Breeze cache cleared via function\n\";
} else {
    echo \"❓ breeze_cache_flush function not available, trying manual cleanup\n\";
    
    // Try manual cache clearing
    \$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)) {
            array_map('unlink', glob(\$dir . '/*.*'));
            echo \"✅ Cleared cache in {\$dir}\n\";
        }
    }
}

echo \"===== Login Fixes Applied =====\n\";
echo \"Please try logging in again with test_trainer user after these fixes.\n\";
EOF"

# Execute the login fix script
echo -e "\nExecuting login 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-issues.php"

# Step 7: 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-issues.php"

echo -e "\n===== Login Debug Complete ====="
echo "Fix applied: Re-enabled login failure handler"
echo "Fix applied: Created mu-plugin to disable caching for login pages"
echo "Fix applied: Reset test_trainer capabilities and sessions"
echo "Fix applied: Added dashboard access for administrator role"
echo "Fix applied: Added debug parameter to login form"
echo "Fix applied: Cleared Breeze cache"
echo -e "\nPlease try logging in again with test_trainer user.\n"