#!/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 "===== Checking Community Login Page ====="

# Verify if page exists
echo "Checking if community-login page exists..."
PAGE_EXISTS=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp post list --post_type=page --name=community-login --field=ID")

if [ -z "$PAGE_EXISTS" ]; then
    echo "Community login page does not exist. Creating it now..."
    PAGE_ID=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp post create --post_type=page --post_title='Community Login' --post_name='community-login' --post_status=publish --post_content='[hvac_community_login]' --porcelain")
    echo "Created community login page with ID: $PAGE_ID"
else
    echo "Community login page exists with ID: $PAGE_EXISTS"
    
    # Check page content
    PAGE_CONTENT=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp post get $PAGE_EXISTS --field=post_content")
    echo "Current page content: $PAGE_CONTENT"
    
    # Update page content if needed
    if [[ "$PAGE_CONTENT" != *"[hvac_community_login]"* ]]; then
        echo "Updating page content to include [hvac_community_login] shortcode..."
        sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp post update $PAGE_EXISTS --post_content='[hvac_community_login]'"
        echo "Page content updated"
    fi
fi

# Check if template files exist
echo -e "\nChecking template files..."
TEMPLATE_EXISTS=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && [ -f wp-content/plugins/hvac-community-events/templates/page-community-login.php ] && echo 'yes' || echo 'no'")
FORM_TEMPLATE_EXISTS=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && [ -f wp-content/plugins/hvac-community-events/templates/community/login-form.php ] && echo 'yes' || echo 'no'")

echo "Page template exists: $TEMPLATE_EXISTS"
echo "Form template exists: $FORM_TEMPLATE_EXISTS"

# Check shortcode registration
echo -e "\nChecking if shortcode is registered..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > check-shortcode.php << 'EOF'
<?php
require_once('wp-load.php');
\$shortcodes = array_keys(\$GLOBALS['shortcode_tags']);
echo implode(\", \", \$shortcodes);
EOF"

SHORTCODES=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php check-shortcode.php")
echo "Registered shortcodes: $SHORTCODES"

SHORTCODE_REGISTERED=$(echo "$SHORTCODES" | grep -q "hvac_community_login" && echo "yes" || echo "no")
echo "hvac_community_login shortcode registered: $SHORTCODE_REGISTERED"

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

# Test the login page via curl
echo -e "\nTesting login page via curl..."
LOGIN_URL="http://upskill-staging.measurequick.com/community-login/"
CURL_RESULT=$(curl -s -L -I "$LOGIN_URL" | grep -i "location" || echo "No redirect")
echo "Login page curl result: $CURL_RESULT"

# Check if login is redirecting to wp-login.php
if [[ "$CURL_RESULT" == *"wp-login.php"* ]]; then
    echo "⚠️ Login page is redirecting to wp-login.php. This indicates a problem!"
    
    # Try to fix by forcing template loading for the page
    echo "Creating a fix for template loading..."
    sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > fix-login-template.php << 'EOF'
<?php
require_once('wp-load.php');

// First, make sure the page exists and has the right slug
\$page = get_page_by_path('community-login');
if (!\$page) {
    // Create the page if it doesn't exist
    \$page_id = wp_insert_post(array(
        '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 it has the shortcode
    if (strpos(\$page->post_content, '[hvac_community_login]') === false) {
        wp_update_post(array(
            'ID' => \$page->ID,
            'post_content' => '[hvac_community_login]'
        ));
        echo \"Updated page content with shortcode\n\";
    }
}

// Make sure the Login_Handler class and shortcode are registered
\$login_handler_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/community/class-login-handler.php';
if (file_exists(\$login_handler_path)) {
    echo \"Login handler file exists\n\";
    // Force include the file
    include_once \$login_handler_path;
    
    // Force register the shortcode
    if (!shortcode_exists('hvac_community_login')) {
        add_shortcode('hvac_community_login', array(new \\HVAC_Community_Events\\Community\\Login_Handler(), 'render_login_form'));
        echo \"Manually registered the hvac_community_login shortcode\n\";
    } else {
        echo \"Shortcode is already registered\n\";
    }
} else {
    echo \"Login handler file NOT found!\n\";
}

// Update template handling for this page
\$main_file_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/class-hvac-community-events.php';
if (file_exists(\$main_file_path)) {
    \$content = file_get_contents(\$main_file_path);
    
    // Check if the load_custom_templates function includes community-login
    if (strpos(\$content, \"is_page('community-login')\") !== false) {
        echo \"Template loader already includes community-login page\n\";
    } else {
        echo \"Template loader needs updating\n\";
        
        // Try to fix by forcing the template
        add_filter('template_include', function(\$template) {
            if (is_page('community-login')) {
                \$custom_template = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/page-community-login.php';
                if (file_exists(\$custom_template)) {
                    return \$custom_template;
                }
            }
            return \$template;
        }, 99);
        
        echo \"Added temporary template filter\n\";
    }
}

// Force flush rewrite rules
flush_rewrite_rules();
echo \"Flushed rewrite rules\n\";

echo \"Login page fix applied\n\";
EOF"

    # Execute the fix
    echo -e "\nApplying login page fix..."
    sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php fix-login-template.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-template.php"
    
    # Test again
    echo -e "\nTesting login page again after fix..."
    CURL_RESULT=$(curl -s -L -I "$LOGIN_URL" | grep -i "location" || echo "No redirect")
    echo "Login page curl result after fix: $CURL_RESULT"
fi

echo -e "\n===== Community Login Page Check Complete ====="