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

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

echo "===== Testing Login Form =====\n";

// Check if the login template exists
$template_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/community/login-form.php';
if (file_exists($template_path)) {
    echo "Login template exists at: $template_path\n";
    
    // Display template content
    $content = file_get_contents($template_path);
    echo "\nTemplate content:\n" . substr($content, 0, 500) . "...\n";
    
    // Check for critical components
    $check_items = array(
        'wp_login_form' => 'wp_login_form(',
        'form_id' => 'form_id',
        'redirect' => 'redirect',
        'login-error' => 'login-error',
        'login=failed' => 'login=failed'
    );
    
    echo "\nChecking for critical components:\n";
    foreach ($check_items as $name => $pattern) {
        echo "$name: " . (strpos($content, $pattern) !== false ? "FOUND" : "NOT FOUND") . "\n";
    }
} else {
    echo "Login template NOT found at: $template_path\n";
}

// Check the page template
$page_template_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/page-community-login.php';
if (file_exists($page_template_path)) {
    echo "\nPage template exists at: $page_template_path\n";
    
    // Display template content
    $content = file_get_contents($page_template_path);
    echo "\nPage template content:\n" . substr($content, 0, 500) . "...\n";
    
    // Check for critical components
    $check_items = array(
        'Login_Handler' => 'Login_Handler',
        'render_login_form' => 'render_login_form',
        'shortcode' => 'shortcode'
    );
    
    echo "\nChecking for critical components:\n";
    foreach ($check_items as $name => $pattern) {
        echo "$name: " . (strpos($content, $pattern) !== false ? "FOUND" : "NOT FOUND") . "\n";
    }
} else {
    echo "Page template NOT found at: $page_template_path\n";
}

// Test if shortcode is registered
echo "\nTesting if the login shortcode is registered:\n";
$shortcodes = array_keys($GLOBALS['shortcode_tags']);
echo "Registered shortcodes: " . implode(', ', $shortcodes) . "\n";
echo "hvac_community_login shortcode is " . (in_array('hvac_community_login', $shortcodes) ? "registered" : "NOT registered") . "\n";

// Test the render_login_form method directly
echo "\nTesting login form rendering directly:\n";
if (class_exists('\\HVAC_Community_Events\\Community\\Login_Handler')) {
    $login_handler = new \\HVAC_Community_Events\\Community\\Login_Handler();
    
    if (method_exists($login_handler, 'render_login_form')) {
        echo "Login handler has render_login_form method\n";
        
        // Capture output
        ob_start();
        $form = $login_handler->render_login_form(array());
        ob_end_clean();
        
        echo "Form output length: " . strlen($form) . " characters\n";
        echo "Form contains form tag: " . (strpos($form, '<form') !== false ? "YES" : "NO") . "\n";
        echo "Form contains login field: " . (strpos($form, 'user_login') !== false ? "YES" : "NO") . "\n";
        echo "Form contains password field: " . (strpos($form, 'user_pass') !== false ? "YES" : "NO") . "\n";
    } else {
        echo "Login handler does NOT have render_login_form method\n";
    }
} else {
    echo "Login_Handler class not found\n";
}

// Check for pages with the community-login slug
echo "\nChecking for community-login page:\n";
$page = get_page_by_path('community-login');
if ($page) {
    echo "Community login page found with ID: {$page->ID}\n";
    echo "Title: {$page->post_title}\n";
    echo "Status: {$page->post_status}\n";
    echo "Content contains shortcode: " . (strpos($page->post_content, '[hvac_community_login]') !== false ? "YES" : "NO") . "\n";
} else {
    echo "Community login page NOT found\n";
    
    // Try to check all pages
    echo "\nLooking for any pages that might contain the login shortcode:\n";
    $pages = get_posts(array(
        'post_type' => 'page',
        'posts_per_page' => -1,
    ));
    
    $found = false;
    foreach ($pages as $p) {
        if (strpos($p->post_content, '[hvac_community_login]') !== false) {
            echo "Found login shortcode in page: {$p->ID} - {$p->post_title}\n";
            echo "Page slug: {$p->post_name}\n";
            $found = true;
        }
    }
    
    if (!$found) {
        echo "No pages found with the login shortcode\n";
    }
}

// Test WordPress login directly
echo "\nTesting WordPress login directly:\n";
$creds = array(
    'user_login' => 'test_trainer',
    'user_password' => 'test_password',
    'remember' => true
);

$user = wp_signon($creds, false);

if (is_wp_error($user)) {
    echo "Login failed: " . $user->get_error_message() . "\n";
} else {
    echo "Login successful for user ID: {$user->ID}\n";
    echo "User roles: " . implode(', ', $user->roles) . "\n";
    echo "User has hvac_trainer role: " . (in_array('hvac_trainer', $user->roles) ? "YES" : "NO") . "\n";
    echo "User has view_hvac_dashboard capability: " . (user_can($user->ID, 'view_hvac_dashboard') ? "YES" : "NO") . "\n";
}

echo "\nFinished testing login form\n";
EOF"

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

echo -e "\n===== Login Form Test Complete ====="