#!/bin/bash

# Fix test_trainer login issues
echo "=== Fixing test_trainer Login Issues ==="

cat > fix-login.php << 'EOF'
<?php
// Fix test_trainer login

define('WP_USE_THEMES', false);
require_once('/home/hvaccommunity/public_html/wp-load.php');

echo "Fixing test_trainer login...\n";

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

echo "Found test_trainer user: ID " . $user->ID . "\n";
echo "Current status: " . $user->user_status . "\n";

// Reset password to ensure it's correct
$new_password = 'Test123!';
wp_set_password($new_password, $user->ID);
echo "Password reset to: $new_password\n";

// Ensure user has correct role
$user->set_role('hvac_trainer');
echo "Role set to: hvac_trainer\n";

// Clear any user meta that might be blocking login
delete_user_meta($user->ID, 'failed_login_count');
delete_user_meta($user->ID, 'last_failed_login');
delete_user_meta($user->ID, 'account_locked');
echo "Cleared login failure meta\n";

// Ensure user is active
wp_update_user(array(
    'ID' => $user->ID,
    'user_status' => 0
));
echo "User status set to active\n";

// Clear all sessions for this user
$sessions = WP_Session_Tokens::get_instance($user->ID);
$sessions->destroy_all();
echo "All sessions cleared\n";

// Test authentication
$auth_result = wp_authenticate($user->user_login, $new_password);
if (is_wp_error($auth_result)) {
    echo "Authentication failed: " . $auth_result->get_error_message() . "\n";
} else {
    echo "Authentication successful!\n";
}

// Check user capabilities
$capabilities = $user->get_role_caps();
$has_hvac_caps = isset($capabilities['hvac_manage_events']) && $capabilities['hvac_manage_events'];
echo "Has HVAC capabilities: " . ($has_hvac_caps ? 'Yes' : 'No') . "\n";

if (!$has_hvac_caps) {
    echo "Adding HVAC capabilities...\n";
    $user->add_cap('hvac_manage_events');
    $user->add_cap('hvac_view_dashboard');
    $user->add_cap('read');
    echo "HVAC capabilities added\n";
}

echo "test_trainer login fix complete!\n";
EOF

# Upload and run
scp -o StrictHostKeyChecking=no fix-login.php hvaccommunity@193.203.168.198:/home/hvaccommunity/public_html/
ssh -o StrictHostKeyChecking=no hvaccommunity@193.203.168.198 "cd /home/hvaccommunity/public_html && php fix-login.php"

# Clean up
rm fix-login.php
ssh -o StrictHostKeyChecking=no hvaccommunity@193.203.168.198 "rm -f /home/hvaccommunity/public_html/fix-login.php"

echo "Login fix complete!"