# HVAC Plugin Troubleshooting Guide

## Table of Contents
- [Common Issues](#common-issues)
- [Debugging Techniques](#debugging-techniques)
- [Error Messages](#error-messages)
- [Performance Issues](#performance-issues)
- [Deployment Problems](#deployment-problems)
- [Theme Conflicts](#theme-conflicts)
- [Database Issues](#database-issues)
- [Recovery Procedures](#recovery-procedures)

## Common Issues

### 1. Event Edit Page HTTP 500 Error

**Symptoms:**
- HTTP 500 error when accessing `/trainer/event/edit/?event_id=XXX`
- WordPress critical error message
- Page completely fails to load

**Root Cause:**
- Template file attempting to instantiate non-existent class

**Solution:**
```php
// In /templates/page-edit-event-custom.php line 26
// WRONG - Class doesn't exist
$form_handler = HVAC_Custom_Event_Edit::instance();

// CORRECT - Use existing Event Manager class
$form_handler = HVAC_Event_Manager::instance();
```

**Verification:**
- Event edit form should load with all fields
- No PHP errors in error log
- Form submission should work

### 2. Registration Form Not Displaying

**Symptoms:**
- Registration page shows only header/footer for non-authenticated users
- No form content visible at `/trainer/registration/`
- Form may work when logged in but not for new users

**Root Cause:**
- WordPress `is_page()` function doesn't accept hierarchical paths
- Authentication checks blocking public access
- Template not loading correctly

**Partial Fix Applied:**
```php
// In multiple files - use URL path detection instead of is_page()
$current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
if ($current_path === 'trainer/registration' || is_page('registration')) {
    // Your logic here
}
```

**Files Modified:**
- `/includes/class-hvac-plugin.php` - Authentication bypass
- `/includes/class-hvac-scripts-styles.php` - Asset loading
- `/includes/class-hvac-community-events.php` - Template loading

**Still Requires:**
- Check if shortcode `[hvac_registration_form]` is registered
- Verify template file exists and has correct content
- Check page template assignment in database

### 3. Dashboard Access and Functionality Issues

#### Incorrect Capability Checks
**Symptoms:**
- "Access Denied" errors for valid trainers
- Users with correct roles can't access dashboard

**Root Cause:**
- Using capability checks instead of role checks for custom roles

**Solution:**
```php
// CORRECT - Check user roles directly
$user = wp_get_current_user();
$has_trainer_role = in_array('hvac_trainer', $user->roles) || 
                    in_array('hvac_master_trainer', $user->roles);

// WRONG - Custom roles are not capabilities!
if (current_user_can('hvac_trainer')) // This won't work!
```

#### Master Dashboard Not Displaying Content
**Symptoms:**
- Master dashboard page loads but shows no content
- Blank page after header/navigation
- PHP errors about undefined methods

**Root Causes:**
1. **Breadcrumb method name error**: `HVAC_Breadcrumbs::render()` doesn't exist
2. **Hierarchical URL detection**: `is_page()` doesn't work with URLs like `/master-trainer/master-dashboard/`
3. **Dual authentication blocking**: Both template and centralized auth systems blocking content

**Solutions:**
```php
// Fix 1: Correct breadcrumb method name
// In templates/page-master-dashboard.php
$breadcrumbs_instance = HVAC_Breadcrumbs::instance();
echo $breadcrumbs_instance->render_breadcrumbs(); // NOT render()

// Fix 2: Add proper page detection for hierarchical URLs
// In class-hvac-scripts-styles.php
private function is_master_dashboard_page() {
    $current_path = $_SERVER['REQUEST_URI'];
    return (strpos($current_path, 'master-trainer/master-dashboard') !== false);
}

// Fix 3: Remove redundant authentication in template
// Comment out template-level auth checks - handled by HVAC_Access_Control
```

#### Master Dashboard Two-Column Layout Issue
**Symptoms:**
- Dashboard displays in two columns instead of single column
- Navigation appears as sidebar on left
- Content pushed to right column
- Unwanted two-column layout

**Root Cause:**
- Navigation menu rendered outside content wrapper
- Theme/CSS treating navigation as sidebar element
- Missing CSS to force single-column layout

**Solutions:**

**1. Move navigation inside content wrapper:**
```php
// In templates/page-master-dashboard.php
get_header();

echo '<div class="hvac-page-wrapper hvac-master-dashboard-page">';
echo '<div class="container">';

// Navigation MUST be inside wrapper
if (class_exists('HVAC_Master_Menu_System')) {
    $master_menu = HVAC_Master_Menu_System::instance();
    $master_menu->render_master_menu();
}
```

**2. Add CSS to force single-column layout:**
Create `assets/css/hvac-master-dashboard.css`:
```css
/* Force single column layout for master dashboard */
.hvac-master-dashboard-page {
    width: 100% !important;
    max-width: 100% !important;
}

/* Ensure navigation doesn't create sidebar */
.hvac-master-dashboard-page .hvac-trainer-menu-wrapper {
    width: 100% !important;
    display: block !important;
    float: none !important;
    position: relative !important;
    margin-bottom: 20px !important;
}

/* Force horizontal menu layout */
.hvac-master-dashboard-page .hvac-trainer-menu {
    display: flex !important;
    flex-direction: row !important;
    flex-wrap: wrap !important;
}

/* Hide any theme sidebars */
.hvac-master-dashboard-page #secondary,
.hvac-master-dashboard-page .widget-area,
.hvac-master-dashboard-page .sidebar {
    display: none !important;
}
```

**3. Enqueue the CSS conditionally:**
```php
// In class-hvac-scripts-styles.php
if ($this->is_master_dashboard_page()) {
    wp_enqueue_style(
        'hvac-master-dashboard',
        HVAC_PLUGIN_URL . 'assets/css/hvac-master-dashboard.css',
        array('hvac-consolidated-dashboard'),
        $this->version
    );
}
```

#### Dashboard Dropdown Menus Not Working
**Symptoms:**
- Dropdown menus don't open on click
- Navigation appears but isn't interactive

**Root Causes & Solutions:**
1. **Welcome Popup Interference**: Z-index conflicts blocking clicks
   - Solution: Disable welcome popup or fix z-index layering
2. **JavaScript Loading Issues**: Check browser console for errors
3. **Cache Issues**: Clear all caches after deployment

#### Dashboard Performance Issues
**Symptoms:**
- Slow loading statistics
- Database query timeouts

**Solution (Implemented August 2025):**
- Added WordPress object caching to all dashboard queries
- Cache duration: 1 hour for stats, 15-30 minutes for time-sensitive data
- Clear cache manually: `wp_cache_delete('hvac_dashboard_*', 'hvac_dashboard')`

### 2. Pages Not Found (404 Errors)

**Symptoms:**
- Trainer pages return 404
- Certificate reports page not accessible
- Profile page missing

**Solutions:**
```bash
# Flush rewrite rules
wp rewrite flush

# Recreate pages
wp eval 'do_action("hvac_create_pages");'

# Verify page exists
wp post list --post_type=page --name=trainer
```

**Code Fix:**
```php
// Force page creation in plugin
HVAC_Page_Manager::create_required_pages();
flush_rewrite_rules();
```

### 2. Duplicate Navigation Menus

**Symptoms:**
- Two navigation bars showing
- Both trainer and master menus visible

**Root Cause:**
- User has both trainer and master trainer roles
- Navigation system rendering both menus

**Solution:**
Already fixed in `HVAC_Menu_System`:
```php
// Check get_menu_structure() method
// Master trainers always see master menu only
```

### 3. Missing CSS/Styling

**Symptoms:**
- Pages appear unstyled
- Broken layouts
- Missing theme integration

**Diagnosis:**
```php
// Check if CSS is loading
add_action('wp_head', function() {
    global $wp_styles;
    echo "<!-- Loaded styles:\n";
    foreach($wp_styles->queue as $style) {
        echo $style . "\n";
    }
    echo "-->";
});
```

**Solutions:**
1. Verify `HVAC_Scripts_Styles` is loading
2. Check `is_plugin_page()` detection
3. Ensure template has `HVAC_IN_PAGE_TEMPLATE` constant

### 4. Mobile CSS Issues

#### Modal Overlay Appearing on Page Load
**Symptoms:**
- Non-functional "Apply" button overlay appears on find-trainer page
- Modal visible by default on mobile devices
- Overlay blocks interaction with page content

**Root Cause:**
- CSS specificity conflict: `display: flex !important` in CSS overrides inline `style="display: none"`
- Modal visibility controlled by both CSS and JavaScript

**Solution:**
Add `!important` to inline styles in the HTML template:
```html
<!-- In templates/page-find-trainer.php line 535 -->
<div id="hvac-filter-modal" class="hvac-filter-modal" 
     style="display: none !important; visibility: hidden !important; opacity: 0 !important;">
```

Also ensure CSS has proper default state:
```css
/* In assets/css/find-trainer.css */
.hvac-filter-modal,
#hvac-filter-modal {
    display: none !important;
    visibility: hidden;
    opacity: 0;
    pointer-events: none;
}
```

**Files Modified:**
- `templates/page-find-trainer.php` (line 535)
- `assets/css/find-trainer.css` 
- `assets/js/find-trainer.js` (initialization checks)
- `astra-child-hvac/css/hvac-find-trainer-mobile.css`

#### Excessive Mobile Padding
**Symptoms:**
- Too much left/right padding on mobile views
- Wasted screen space on small devices
- Content not utilizing full viewport width

**Solution:**
Set all container padding to 0 on mobile breakpoints:
```css
/* In astra-child-hvac/css/hvac-find-trainer-mobile.css */
@media screen and (max-width: 768px) {
    body.hvac-find-trainer-page .ast-container,
    body.page-id-1653 .ast-container {
        padding: 0 !important;
        margin: 0 !important;
        width: 100% !important;
    }
    
    /* Filters section with minimal margins */
    .hvac-filters-section {
        margin: 0 5px !important;
        padding: 8px !important;
    }
}
```

**Deployment:**
Use child theme CSS deployment script:
```bash
scripts/deploy-child-theme-css.sh
```

### 5. Sidebar Still Showing

**Symptoms:**
- 2-column layout persists
- Sidebar visible on trainer pages

**Solutions:**
1. Check Astra integration is active:
```php
// In theme's functions.php temporarily
add_action('init', function() {
    if (class_exists('HVAC_Astra_Integration')) {
        error_log('Astra integration loaded');
    }
});
```

2. Force no-sidebar via database:
```bash
wp eval '
$pages = get_posts(array(
    "post_type" => "page",
    "meta_key" => "_wp_page_template",
    "meta_value" => "trainer",
    "meta_compare" => "LIKE"
));
foreach($pages as $page) {
    update_post_meta($page->ID, "site-sidebar-layout", "no-sidebar");
    update_post_meta($page->ID, "ast-site-sidebar-layout", "no-sidebar");
}'
```

### 5. Profile Page Using Wrong Template

**Symptoms:**
- Old navigation showing
- Missing fields
- Wrong layout

**Quick Fix:**
```bash
# Find profile page
wp post list --post_type=page --name=profile --fields=ID,post_title

# Update template
wp post meta update [PAGE_ID] _wp_page_template templates/page-trainer-profile.php
```

### 6. Certificate Pages Template Issues

**Symptoms:**
- Certificate pages show only content without theme headers
- Missing navigation menu on certificate pages
- Duplicate breadcrumbs appearing
- Pages look "broken" or unstyled

**Root Causes:**
1. Template system loading content-only templates instead of full page templates
2. Astra theme adding its own breadcrumbs while plugin adds more
3. Navigation rendering being blocked by constants

**Solutions:**

**Fix Template Loading:**
```php
// In class-hvac-community-events.php load_custom_templates() method
// Change from:
$custom_template = HVAC_PLUGIN_DIR . 'templates/certificates/template-certificate-reports.php';
// To:
$custom_template = HVAC_PLUGIN_DIR . 'templates/page-certificate-reports.php';
```

**Disable Duplicate Breadcrumbs:**
```php
// In class-hvac-astra-integration.php
add_filter('astra_breadcrumb_enabled', [$this, 'disable_astra_breadcrumbs'], 999);
add_filter('astra_get_option_ast-breadcrumbs-content', [$this, 'disable_breadcrumb_option'], 999);
```

**Enable Navigation Menu:**
```php
// In page templates, remove problematic constant checks:
// Remove this:
if (class_exists('HVAC_Menu_System') && !defined('HVAC_NAV_RENDERED')) {
    define('HVAC_NAV_RENDERED', true);
    HVAC_Menu_System::instance()->render_trainer_menu();
}

// Replace with this:
if (class_exists('HVAC_Menu_System')) {
    HVAC_Menu_System::instance()->render_trainer_menu();
}
```

**Quick Diagnostic:**
```bash
# Check which template is being used
wp eval 'echo get_page_template_slug(get_page_by_path("trainer/certificate-reports")->ID);'

# Verify CSS is loading
wp eval 'wp_head(); wp_footer();' | grep -i certificate
```

## Debugging Techniques

### 1. Enable WordPress Debug Mode

**wp-config.php:**
```php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', true);
```

### 2. Plugin-Specific Debug

**Add to plugin file:**
```php
// Debug page detection
add_action('wp', function() {
    if (defined('HVAC_DEBUG') && HVAC_DEBUG) {
        error_log('Current page: ' . $_SERVER['REQUEST_URI']);
        error_log('Is plugin page: ' . (HVAC_Scripts_Styles::is_plugin_page() ? 'yes' : 'no'));
        error_log('Template: ' . get_page_template());
    }
});
```

### 3. JavaScript Debugging

```javascript
// Add debug logging
if (window.hvac_debug) {
    console.log('HVAC Debug:', {
        page: window.location.pathname,
        user: hvac_ajax.user_id,
        role: hvac_ajax.user_role
    });
}
```

### 4. Database Query Monitoring

```php
// Log all queries for a page load
define('SAVEQUERIES', true);

add_action('shutdown', function() {
    global $wpdb;
    error_log('Total queries: ' . count($wpdb->queries));
    foreach($wpdb->queries as $query) {
        if ($query[1] > 0.05) { // Queries taking > 50ms
            error_log('Slow query: ' . $query[0] . ' (' . $query[1] . 's)');
        }
    }
});
```

## Error Messages

### "There has been a critical error on this website"

**Common Causes:**
1. PHP syntax error
2. Missing required file
3. Fatal error in hook

**Debugging Steps:**
```bash
# Check PHP error log
tail -f wp-content/debug.log

# Check syntax
php -l includes/class-name.php

# Enable recovery mode
wp config set WP_DISABLE_FATAL_ERROR_HANDLER true
```

### "Headers already sent"

**Cause:** Output before WordPress headers

**Fix:**
```php
// Remove any whitespace before <?php
// Check for BOM in files
// Use ob_start() if necessary
```

### AJAX Errors

**Debug AJAX:**
```javascript
jQuery.ajax({
    // ... options
    error: function(xhr, status, error) {
        console.error('AJAX Error:', {
            status: status,
            error: error,
            response: xhr.responseText
        });
    }
});
```

## Performance Issues

### 1. Slow Page Loads

**Diagnosis:**
```php
// Add to theme's functions.php
add_action('wp_footer', function() {
    echo "<!-- Page generated in " . timer_stop(0) . " seconds -->";
    echo "<!-- Queries: " . get_num_queries() . " -->";
});
```

**Common Fixes:**
1. Enable object caching
2. Optimize database queries
3. Use transients for expensive operations

### 2. High Database Query Count

**Identify Problem Queries:**
```php
// Find duplicate queries
add_filter('posts_request', function($query) {
    error_log('Query: ' . $query);
    return $query;
});
```

**Optimization:**
```php
// Cache user queries
$cache_key = 'hvac_trainer_' . $user_id;
$trainer_data = wp_cache_get($cache_key);
if (false === $trainer_data) {
    $trainer_data = get_user_meta($user_id);
    wp_cache_set($cache_key, $trainer_data, '', 3600);
}
```

### 3. Memory Issues

**Symptoms:**
- "Allowed memory size exhausted"
- White screen of death

**Solutions:**
```php
// Increase memory limit
define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');

// Find memory usage
error_log('Memory: ' . memory_get_usage() / 1024 / 1024 . 'MB');
error_log('Peak: ' . memory_get_peak_usage() / 1024 / 1024 . 'MB');
```

## Deployment Problems

### 1. Plugin Not Activating

**Check Requirements:**
```bash
# PHP version
php -v

# Required extensions
php -m | grep -E "(mysqli|curl|gd|mbstring)"

# WordPress version
wp core version
```

### 2. Files Not Updating

**Clear All Caches:**
```bash
# WordPress cache
wp cache flush

# Opcache
wp eval 'if (function_exists("opcache_reset")) opcache_reset();'

# Breeze cache
wp breeze purge --all

# CloudFlare (if applicable)
# Use CloudFlare dashboard or API
```

### 3. Database Changes Not Applying

**Force Update:**
```bash
# Deactivate and reactivate
wp plugin deactivate hvac-community-events
wp plugin activate hvac-community-events

# Run activation hook manually
wp eval 'do_action("activate_hvac-community-events/hvac-community-events.php");'
```

## Theme Conflicts

### 1. Astra Theme Issues

**Check Theme Version:**
```bash
wp theme list --fields=name,version,status
```

**Force Compatibility:**
```php
// Add to theme's functions.php
add_action('after_setup_theme', function() {
    // Force load Astra integration
    if (!class_exists('HVAC_Astra_Integration')) {
        require_once WP_PLUGIN_DIR . '/hvac-community-events/includes/class-hvac-astra-integration.php';
        HVAC_Astra_Integration::instance();
    }
}, 5);
```

### 2. Other Theme Conflicts

**Identify Conflicts:**
```php
// Switch to default theme temporarily
wp theme activate twentytwentyone

// Test plugin functionality
// If it works, theme conflict confirmed
```

**Common Fixes:**
1. Add theme-specific integration class
2. Use more specific CSS selectors
3. Adjust hook priorities

## Database Issues

### 1. Missing Meta Keys

**Audit Meta Keys:**
```bash
# Check post meta
wp db query "SELECT DISTINCT meta_key FROM wp_postmeta WHERE meta_key LIKE '%hvac%'"

# Check user meta
wp db query "SELECT DISTINCT meta_key FROM wp_usermeta WHERE meta_key LIKE '%hvac%'"
```

### 2. Orphaned Data

**Clean Orphaned Event Data:**
```sql
-- Find events without trainers
SELECT ID, post_title 
FROM wp_posts p
WHERE post_type = 'tribe_events'
AND NOT EXISTS (
    SELECT 1 FROM wp_postmeta pm 
    WHERE pm.post_id = p.ID 
    AND pm.meta_key = '_EventTrainerID'
);
```

### 3. Data Migration

**Migrate Legacy Roles:**
```php
// Run via WP-CLI
wp eval '
$users = get_users(array("role" => "event_trainer"));
foreach($users as $user) {
    $user->remove_role("event_trainer");
    $user->add_role("hvac_trainer");
    echo "Migrated user: " . $user->user_login . "\n";
}'
```

## Recovery Procedures

### 1. Emergency Rollback

```bash
# SSH to server
ssh user@server

# Navigate to plugins
cd /path/to/wp-content/plugins

# Backup current version
mv hvac-community-events hvac-community-events-broken

# Restore previous version
cp -r hvac-backups/hvac-community-events-backup-[date] hvac-community-events

# Reactivate
wp plugin activate hvac-community-events

# Clear caches
wp cache flush
```

### 2. Database Recovery

```bash
# Export current state
wp db export backup-$(date +%Y%m%d-%H%M%S).sql

# If needed, restore from backup
wp db import backup-file.sql

# Verify data
wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_type = 'tribe_events'"
```

### 3. Complete Reset

**Nuclear Option - Full Reset:**
```bash
# Backup everything first!
wp db export full-backup.sql

# Deactivate plugin
wp plugin deactivate hvac-community-events

# Remove all plugin data
wp eval '
// Delete all pages
$pages = get_posts(array(
    "post_type" => "page",
    "meta_key" => "_wp_page_template",
    "meta_value" => "hvac",
    "meta_compare" => "LIKE",
    "posts_per_page" => -1
));
foreach($pages as $page) {
    wp_delete_post($page->ID, true);
}

// Delete options
delete_option("hvac_plugin_version");
delete_option("hvac_settings");
'

# Reinstall
wp plugin activate hvac-community-events
```

## Monitoring & Logging

### 1. Set Up Error Monitoring

```php
// Add to plugin
class HVAC_Error_Handler {
    public static function log_error($message, $context = array()) {
        $log_entry = sprintf(
            '[%s] %s | Context: %s',
            current_time('mysql'),
            $message,
            json_encode($context)
        );
        
        error_log($log_entry, 3, WP_CONTENT_DIR . '/hvac-errors.log');
        
        // Also send to external service if configured
        if (defined('HVAC_ERROR_WEBHOOK')) {
            wp_remote_post(HVAC_ERROR_WEBHOOK, array(
                'body' => json_encode(array(
                    'message' => $message,
                    'context' => $context,
                    'site' => home_url()
                ))
            ));
        }
    }
}
```

### 2. Performance Monitoring

```php
// Track slow operations
function hvac_track_performance($operation, $callback) {
    $start = microtime(true);
    $result = $callback();
    $duration = microtime(true) - $start;
    
    if ($duration > 1.0) { // Log operations taking > 1 second
        HVAC_Error_Handler::log_error(
            'Slow operation detected',
            array(
                'operation' => $operation,
                'duration' => $duration,
                'memory' => memory_get_peak_usage() / 1024 / 1024
            )
        );
    }
    
    return $result;
}
```

## Quick Reference Commands

```bash
# Check plugin status
wp plugin list --name=hvac-community-events

# View recent errors
tail -f wp-content/debug.log | grep -i hvac

# Clear all caches
wp cache flush && wp rewrite flush && wp breeze purge --all

# Test page routing
wp eval 'print_r(get_page_by_path("trainer/dashboard"));'

# Force recreate pages
wp eval 'HVAC_Page_Manager::create_required_pages();'

# Check user roles
wp user list --role=hvac_trainer,hvac_master_trainer

# Database optimization
wp db optimize
```