#!/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 "===== Creating No-Cache Plugin for Authentication Pages ====="

# Create mu-plugin to disable caching for login pages
echo "Creating mu-plugin to disable cache for login and dashboard pages..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && mkdir -p wp-content/mu-plugins && cat > wp-content/mu-plugins/hvac-disable-auth-cache.php << 'EOF'
<?php
/**
 * Plugin Name: HVAC - Disable Cache for Authentication Pages
 * Description: Disables caching for login, dashboard, and authentication-related pages
 * Version: 1.0.0
 * Author: HVAC Community Events
 */

// Disable caching for authentication-related pages
function hvac_disable_cache_for_auth_pages() {
    // List of pages and URL patterns to disable cache for
    $no_cache_patterns = [
        'community-login',
        'wp-login.php',
        'hvac-dashboard',
        'login=',
        'certificate-reports',
        'generate-certificates',
        'event-summary',
        'email-attendees',
        'trainer-profile',
        'edit-profile',
    ];
    
    // Get current URL
    $current_url = $_SERVER['REQUEST_URI'];
    
    // Check if current URL matches any of our patterns
    $disable_cache = false;
    foreach ($no_cache_patterns as $pattern) {
        if (strpos($current_url, $pattern) !== false) {
            $disable_cache = true;
            break;
        }
    }
    
    // Also disable cache for logged-in users or when handling logins
    if (is_user_logged_in() || isset($_POST['log']) || isset($_POST['pwd']) || isset($_GET['login'])) {
        $disable_cache = true;
    }
    
    if ($disable_cache) {
        // Define WordPress constant to prevent page caching
        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true);
        }
        
        // Send cache control headers
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header('Expires: Mon, 07 Jul 1997 05:00:00 GMT');
        
        // Add a specific cookie to help prevent caching
        if (!isset($_COOKIE['hvac_nocache'])) {
            setcookie('hvac_nocache', '1', 0, '/', '', is_ssl(), true);
        }
    }
}
add_action('init', 'hvac_disable_cache_for_auth_pages', 1);

// Disable Breeze caching for logged-in users
function hvac_disable_breeze_for_logged_in() {
    // If Breeze classes exist
    if (class_exists('Breeze_Options_Reader')) {
        if (is_user_logged_in()) {
            add_filter('breeze_disable_cache', '__return_true');
            add_filter('breeze_override_donotcachepage', '__return_false');
        }
    }
}
add_action('init', 'hvac_disable_breeze_for_logged_in', 5);

// Add our auth pages to Breeze's no-cache list
function hvac_add_auth_pages_to_breeze_exclude() {
    // Only run this once 
    if (get_option('hvac_breeze_pages_added')) {
        return;
    }
    
    // Get Breeze settings
    $breeze_options = get_option('breeze_basic_settings');
    if (!$breeze_options || !is_array($breeze_options)) {
        return;
    }
    
    // Pages to exclude
    $auth_pages = [
        '/community-login/',
        '/wp-login.php',
        '/hvac-dashboard/',
        '/certificate-reports/',
        '/generate-certificates/',
        '/event-summary/',
        '/email-attendees/',
        '/trainer-profile/',
        '/edit-profile/'
    ];
    
    // Current excluded pages
    $excluded_pages = isset($breeze_options['no-cache-pages']) ? $breeze_options['no-cache-pages'] : '';
    
    // Add our pages
    $pages_to_add = [];
    foreach ($auth_pages as $page) {
        if (strpos($excluded_pages, $page) === false) {
            $pages_to_add[] = $page;
        }
    }
    
    if (empty($pages_to_add)) {
        update_option('hvac_breeze_pages_added', 1);
        return;
    }
    
    // Update excluded pages
    $updated_pages = $excluded_pages;
    if (!empty($excluded_pages)) {
        $updated_pages .= ', ';
    }
    $updated_pages .= implode(', ', $pages_to_add);
    
    $breeze_options['no-cache-pages'] = $updated_pages;
    update_option('breeze_basic_settings', $breeze_options);
    update_option('hvac_breeze_pages_added', 1);
}
add_action('admin_init', 'hvac_add_auth_pages_to_breeze_exclude');

// Clear Breeze cache after user login and logout
function hvac_clear_breeze_on_login() {
    if (function_exists('breeze_cache_flush')) {
        breeze_cache_flush();
    }
}
add_action('wp_login', 'hvac_clear_breeze_on_login');
add_action('wp_logout', 'hvac_clear_breeze_on_login');
EOF"

# Clear cache after mu-plugin creation
echo "Clearing Breeze cache..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp cache flush --allow-root"

# Check if mu-plugin was created successfully
PLUGIN_EXISTS=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && [ -f wp-content/mu-plugins/hvac-disable-auth-cache.php ] && echo 'yes' || echo 'no'")

if [ "$PLUGIN_EXISTS" = "yes" ]; then
    echo "✅ No-cache plugin created successfully"
else
    echo "❌ Failed to create no-cache plugin"
fi

echo -e "\n===== Plugin Creation Complete ====="
echo "A must-use plugin has been created to prevent caching on login pages and dashboard."
echo "This should resolve browser-based login issues for the test_trainer user."