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

# Create a 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-redirect.php << 'EOF'
<?php
// Load WordPress
require_once('wp-load.php');

echo "Fixing login redirect issues...\n";

// 1. Fix login-handler.php file
echo "1. Fixing login handler class...\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);
    
    // Make sure login failure handler is enabled
    if (strpos($content, '// add_action(\'wp_login_failed\'') !== false) {
        $content = str_replace(
            '// add_action(\'wp_login_failed\', array($this, \'handle_login_failure\'));',
            'add_action(\'wp_login_failed\', array($this, \'handle_login_failure\'));',
            $content
        );
        echo "Enabled login failure handler\n";
    }
    
    // Make sure redirect_to is set in wp_login_form args
    if (strpos($content, '$args[\'redirect\']') === false) {
        $content = str_replace(
            'wp_login_form( $args );',
            '$args[\'redirect\'] = home_url(\'/hvac-dashboard/\');' . "\n\t\t" . 'wp_login_form( $args );',
            $content
        );
        echo "Added redirect_to to login form args\n";
    }
    
    // Save changes
    if (file_put_contents($login_handler_path, $content)) {
        echo "Saved changes to login handler file\n";
    } else {
        echo "Failed to save changes to login handler file\n";
    }
} else {
    echo "Login handler file not found at: $login_handler_path\n";
}

// 2. Make sure community-login page exists and has shortcode
echo "2. Checking community login page...\n";
$page = get_page_by_path('community-login');
if (!$page) {
    $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 content has 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";
    } else {
        echo "Page already has login shortcode\n";
    }
}

// 3. Reset test_trainer user password
echo "3. Resetting test_trainer user...\n";
$user = get_user_by('login', 'test_trainer');
if ($user) {
    // Reset password
    wp_set_password('test_password', $user->ID);
    echo "Reset password for test_trainer (ID: {$user->ID})\n";
    
    // Clear user sessions
    $sessions = WP_Session_Tokens::get_instance($user->ID);
    $sessions->destroy_all();
    echo "Cleared all sessions for test_trainer\n";
    
    // Make sure user has hvac_trainer role
    if (!in_array('hvac_trainer', $user->roles)) {
        $user->add_role('hvac_trainer');
        echo "Added hvac_trainer role to test_trainer\n";
    } else {
        echo "User already has hvac_trainer role\n";
    }
} else {
    echo "test_trainer user not found\n";
}

// 4. Check if template files exist and fix if needed
echo "4. Checking template files...\n";
$page_template = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/page-community-login.php';
$form_template = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/community/login-form.php';

if (!file_exists($page_template)) {
    echo "Page template missing at: $page_template\n";
} else {
    echo "Page template exists\n";
}

if (!file_exists($form_template)) {
    echo "Form template missing at: $form_template\n";
} else {
    echo "Form template exists\n";
}

// 5. Fix template loader in main class
echo "5. Checking template loader...\n";
$main_class_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/class-hvac-community-events.php';
if (file_exists($main_class_path)) {
    $content = file_get_contents($main_class_path);
    
    // Make sure template loader handles community-login page
    if (strpos($content, "is_page('community-login')") === false) {
        echo "Template loader doesn't include community-login page - fixing...\n";
        
        // Find the load_custom_templates method
        if (preg_match('/public function load_custom_templates\s*\(\s*\$template\s*\)\s*{/s', $content, $matches, PREG_OFFSET_CAPTURE)) {
            $method_start = $matches[0][1];
            
            // Find where the custom_template checks start
            if (preg_match('/\$custom_template\s*=\s*null;/s', $content, $matches, PREG_OFFSET_CAPTURE, $method_start)) {
                $checks_start = $matches[0][1] + strlen($matches[0][0]);
                
                // Add community-login check if it doesn't exist
                $community_login_check = "\n\t\t// Check for community-login page\n\t\tif (is_page('community-login')) {\n\t\t\t\$custom_template = HVAC_CE_PLUGIN_DIR . 'templates/page-community-login.php';\n\t\t}\n";
                
                // Insert the check
                $updated_content = substr($content, 0, $checks_start) . $community_login_check . substr($content, $checks_start);
                
                // Save the updated content
                if (file_put_contents($main_class_path, $updated_content)) {
                    echo "Added community-login page to template loader\n";
                } else {
                    echo "Failed to update template loader\n";
                }
            }
        }
    } else {
        echo "Template loader already includes community-login page\n";
    }
} else {
    echo "Main class file not found at: $main_class_path\n";
}

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

// 7. Flush rewrite rules
echo "7. Flushing rewrite rules...\n";
flush_rewrite_rules();
echo "Rewrite rules flushed\n";

echo "\nLogin fix complete.\n";
echo "Please try logging in with username 'test_trainer' and password 'test_password'.\n";
echo "Login URL: " . site_url('/community-login/') . "\n";
EOF"

# Execute the fix 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-redirect.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-redirect.php"

echo -e "\n===== Login Redirect Fix Complete ====="
echo "The login redirect issues should now be fixed."
echo "Please try logging in with username 'test_trainer' and password 'test_password'."
echo "Login URL: http://upskill-staging.measurequick.com/community-login/"