#!/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 via PHP ====="

# Create a PHP script to fix login issues
echo "Creating PHP script to fix login issues..."
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 "===== Fixing Login Issues =====\n";

// 1. Re-enable login failure handler
echo "1. Re-enabling login failure handler...\n";
$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
        );
        if (file_put_contents($login_handler_path, $fixed_content)) {
            echo "✓ Login failure handler re-enabled\n";
        } else {
            echo "✗ Failed to update login handler file\n";
        }
    } else {
        echo "✓ Login failure handler already enabled\n";
    }
} else {
    echo "✗ Login handler file not found\n";
}

// 2. Create mu-plugin to disable caching
echo "2. Creating mu-plugin to disable caching...\n";
$mu_plugin_dir = WP_CONTENT_DIR . '/mu-plugins';
if (!is_dir($mu_plugin_dir)) {
    mkdir($mu_plugin_dir, 0755);
}

$nocache_plugin_path = $mu_plugin_dir . '/hvac-nocache.php';
$nocache_plugin_content = <<<'EOT'
<?php
/**
 * Plugin Name: HVAC No-Cache for Login
 * Description: Prevents caching on login and dashboard pages
 * Version: 1.0
 */

function hvac_disable_cache() {
    // Check if we're on a login-related page
    $uri = $_SERVER['REQUEST_URI'];
    $disable_cache = false;
    
    // Pages that should never be cached
    $no_cache_pages = array(
        'community-login',
        'wp-login.php',
        'hvac-dashboard',
        'certificate-reports',
        'generate-certificates',
        'event-summary'
    );
    
    foreach ($no_cache_pages as $page) {
        if (strpos($uri, $page) !== false) {
            $disable_cache = true;
            break;
        }
    }
    
    // Also disable cache for logged-in users or authentication attempts
    if (is_user_logged_in() || isset($_POST['log']) || isset($_GET['login'])) {
        $disable_cache = true;
    }
    
    if ($disable_cache) {
        // Define WordPress constant
        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true);
        }
        
        // Set no-cache headers
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Pragma: no-cache');
    }
}
add_action('init', 'hvac_disable_cache', 0);

// Disable Breeze caching for logged-in users
function hvac_disable_breeze_cache() {
    if (is_user_logged_in()) {
        add_filter('breeze_skip_cache', '__return_true');
    }
}
add_action('init', 'hvac_disable_breeze_cache');
EOT;

if (file_put_contents($nocache_plugin_path, $nocache_plugin_content)) {
    echo "✓ No-cache plugin created successfully\n";
} else {
    echo "✗ Failed to create no-cache plugin\n";
}

// 3. Fix test_trainer user
echo "3. Verifying test_trainer user...\n";
$user = get_user_by('login', 'test_trainer');
if ($user) {
    // Reset password just to be sure
    wp_set_password('test_password', $user->ID);
    echo "✓ Password reset for test_trainer\n";
    
    // Clear user sessions
    $sessions = WP_Session_Tokens::get_instance($user->ID);
    $sessions->destroy_all();
    echo "✓ All sessions cleared for test_trainer\n";
    
    // Verify role
    $user_meta = get_userdata($user->ID);
    if (!in_array('hvac_trainer', $user_meta->roles)) {
        $user->add_role('hvac_trainer');
        echo "✓ Added hvac_trainer role\n";
    } else {
        echo "✓ User already has hvac_trainer role\n";
    }
    
    // Make sure user has the right capabilities
    if (!user_can($user->ID, 'view_hvac_dashboard')) {
        $role = get_role('hvac_trainer');
        if ($role) {
            $role->add_cap('view_hvac_dashboard', true);
            echo "✓ Added view_hvac_dashboard capability to hvac_trainer role\n";
        }
    } else {
        echo "✓ User already has view_hvac_dashboard capability\n";
    }
} else {
    echo "✗ test_trainer user not found\n";
}

// 4. Clear Breeze cache
echo "4. Clearing Breeze cache...\n";
if (function_exists('breeze_cache_flush')) {
    breeze_cache_flush();
    echo "✓ Cache cleared via function\n";
} else {
    // Try manually clearing cache directories
    $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 . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            echo "✓ Cleared cache directory: $dir\n";
        }
    }
}

// 5. Check Breeze settings
echo "5. Checking Breeze settings...\n";
$breeze_basic = get_option('breeze_basic_settings');
if ($breeze_basic && is_array($breeze_basic)) {
    // Make sure cache is disabled for logged-in users
    $breeze_advanced = get_option('breeze_advanced_settings');
    if ($breeze_advanced && is_array($breeze_advanced)) {
        if (!isset($breeze_advanced['breeze-disable-admin']) || $breeze_advanced['breeze-disable-admin'] != '1') {
            $breeze_advanced['breeze-disable-admin'] = '1';
            update_option('breeze_advanced_settings', $breeze_advanced);
            echo "✓ Updated Breeze to disable cache for logged-in users\n";
        } else {
            echo "✓ Breeze already disables cache for logged-in users\n";
        }
    }
    
    // Add login pages to no-cache list
    $no_cache_pages = isset($breeze_basic['no-cache-pages']) ? $breeze_basic['no-cache-pages'] : '';
    $pages_to_add = array('/community-login/', '/wp-login.php', '/hvac-dashboard/');
    $updated = false;
    
    foreach ($pages_to_add as $page) {
        if (strpos($no_cache_pages, $page) === false) {
            $no_cache_pages .= (!empty($no_cache_pages) ? ', ' : '') . $page;
            $updated = true;
        }
    }
    
    if ($updated) {
        $breeze_basic['no-cache-pages'] = $no_cache_pages;
        update_option('breeze_basic_settings', $breeze_basic);
        echo "✓ Added login pages to Breeze no-cache list\n";
    } else {
        echo "✓ Login pages already in Breeze no-cache list\n";
    }
} else {
    echo "✗ Breeze settings not found\n";
}

echo "\n===== Login Issues Fixed =====\n";
echo "You should now be able to log in with test_trainer / test_password\n";

// Return login URLs for testing
$login_url = site_url('/community-login/');
$dashboard_url = site_url('/hvac-dashboard/');
echo "\nTest URLs:\n";
echo "Login: $login_url\n";
echo "Dashboard: $dashboard_url\n";
EOF"

# Execute the PHP script
echo "Executing 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"

# 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 Fixes Applied ====="
echo "The login issues for the test_trainer user should now be resolved."
echo "Please try logging in with username 'test_trainer' and password 'test_password'."