# Advanced Logging Context and Admin Protection - Summary

## Overview

Enhanced the TracknowWC logging system with admin page protection and WooCommerce hook context detection for superior debugging capabilities.

## 1. Admin Page Protection 🛡️

### Problem Solved:

- `save_click_id_to_cookie` was running on admin pages unnecessarily
- Wasted processing power on non-public pages
- Potential security/privacy concerns with admin-side cookie handling

### Solution Implemented:

```php
function save_click_id_to_cookie()
{
    try {
        // Only process on public pages, not admin pages
        if (is_admin() && !wp_doing_ajax()) {
            $this->write_debug_log("[save_click_id_to_cookie] Skipping - running on admin page.");
            return;
        }

        $this->write_debug_log("[save_click_id_to_cookie] Checking for click_id in GET request.");
        // ... rest of method
    }
}
```

### Benefits:

- **Performance**: Eliminates unnecessary processing on admin pages
- **Security**: Prevents cookie manipulation in admin context
- **Clean Logs**: Reduces noise in debug logs
- **AJAX Support**: Still works for frontend AJAX requests (`!wp_doing_ajax()`)

## 2. Enhanced WooCommerce Hook Context 🎯

### Problem Solved:

- Difficult to trace which WooCommerce hook triggered a log entry
- Generic context made debugging complex multi-hook scenarios challenging
- No way to differentiate between similar actions from different hooks

### Solution Implemented:

#### A. Expanded Context Map with Hook Information:

```php
private static $context_map = [
    // ... existing mappings
    // WooCommerce hook wrapper methods
    'wrapper_for_order_status_processing' => 'wc_hook:order_status_processing',
    'wrapper_for_payment_complete' => 'wc_hook:payment_complete',
    'wrapper_for_pre_payment_complete' => 'wc_hook:pre_payment_complete',
    'wrapper_for_order_status_completed' => 'wc_hook:order_status_completed',
    'wrapper_for_order_status_cancelled' => 'wc_hook:order_status_cancelled',
    'wrapper_for_order_status_refunded' => 'wc_hook:order_status_refunded',
    'order_status_changed' => 'wc_hook:order_status_changed',
    'deny_order' => 'wc_hook:deny_order'
];
```

#### B. Dynamic Hook Detection:

```php
private static function get_current_wc_hook()
{
    try {
        // Get current WordPress hook
        $current_filter = current_filter();

        // Only return WooCommerce-related hooks
        if ($current_filter && (strpos($current_filter, 'woocommerce_') === 0 || strpos($current_filter, 'wc_') === 0)) {
            return $current_filter;
        }

        // Also check for common WordPress hooks that WooCommerce uses
        $wc_relevant_hooks = [
            'wp_footer', 'wp_head', 'init', 'wp_loaded',
            'template_redirect', 'wp', 'wp_enqueue_scripts', 'admin_enqueue_scripts'
        ];

        if ($current_filter && in_array($current_filter, $wc_relevant_hooks)) {
            return $current_filter;
        }

        return null;
    } catch (Throwable $e) {
        return null;
    }
}
```

#### C. Enhanced Context Detection:

```php
// Auto-detect context from the calling method if not provided
if ($context === null) {
    try {
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        if (isset($backtrace[1]['function'])) {
            $base_context = self::extract_context_from_method($backtrace[1]['function']);

            // Enhance context with current WooCommerce hook if available
            $current_hook = self::get_current_wc_hook();
            if ($current_hook) {
                $context = $base_context . '|hook:' . $current_hook;
            } else {
                $context = $base_context;
            }
        }
    } catch (Throwable $e) {
        $context = 'general'; // Fallback context
    }
}
```

## 3. Enhanced Logging Examples

### Before (Basic Context):

```
[TracknowWC] Processing order 12345
Context: pixel_send
```

### After (Rich Context with Hook Info):

```
[TracknowWC] Processing order 12345
Context: pixel_send|hook:woocommerce_order_status_processing
Order ID: 12345
```

### Hook Detection Examples:

- `pixel_send|hook:woocommerce_payment_complete`
- `wc_hook:order_status_completed|hook:woocommerce_order_status_completed`
- `cookie_save|hook:wp_footer`
- `click_tracking|hook:init`

## 4. Performance and Security Benefits

### Performance Improvements:

- **Admin Skip**: Eliminates cookie processing on admin pages
- **Static Hook Detection**: Efficient hook identification
- **Conditional Enhancement**: Only adds hook context when available

### Security Enhancements:

- **Admin Isolation**: Cookie handling restricted to public pages
- **AJAX Compatibility**: Maintains functionality for legitimate AJAX requests
- **Safe Hook Detection**: Protected with try-catch to prevent crashes

### Debugging Advantages:

- **Precise Tracing**: Know exactly which WC hook triggered each log
- **Multi-Hook Scenarios**: Differentiate between similar actions from different hooks
- **Context Richness**: Method + Hook + Order ID = comprehensive debugging info

## 5. Real-World Use Cases

### E-commerce Order Flow Debugging:

```
pixel_send|hook:woocommerce_checkout_order_processed - Order 123
pixel_send|hook:woocommerce_payment_complete - Order 123
wc_hook:order_status_completed|hook:woocommerce_order_status_completed - Order 123
```

### Click Tracking Flow:

```
cookie_save|hook:init - Public page click tracking
auto_click|hook:wp_footer - Deferred click generation
click_gen|hook:woocommerce_thankyou - Thank you page pixel
```

### Performance Monitoring:

```
[save_click_id_to_cookie] Skipping - running on admin page - Admin optimization working
pixel_send|hook:woocommerce_payment_complete - Order 456 - Production hook firing correctly
```

## 6. Backward Compatibility

- All existing logging continues to work unchanged
- Enhanced context is additive (doesn't break existing log parsing)
- Admin page check is safe (uses WordPress core functions)
- Hook detection gracefully degrades if WordPress functions unavailable

## Summary

These enhancements provide **surgical precision** for debugging WooCommerce integrations while optimizing performance by preventing unnecessary admin-side processing. The rich context information makes it easy to trace the exact execution path that led to each log entry, dramatically improving troubleshooting efficiency for complex e-commerce scenarios.
