<?php
/**
 * Safari Request Debug Log Viewer
 * 
 * Simple script to view Safari debugging logs
 * Access: /debug-safari-logs.php
 */

// Security check - only allow if WP_DEBUG is enabled or specific key is provided
$debug_key = $_GET['key'] ?? '';
$expected_key = 'safari_debug_' . date('Ymd');

if (!defined('WP_DEBUG') || !WP_DEBUG) {
    if ($debug_key !== $expected_key) {
        http_response_code(404);
        exit('Not found');
    }
}

// Set content type
header('Content-Type: text/html; charset=utf-8');

// Get WordPress content directory
$wp_content = dirname(__FILE__) . '/../../../wp-content';
$log_file = $wp_content . '/safari-debug.log';
$wp_debug_log = $wp_content . '/debug.log';

?>
<!DOCTYPE html>
<html>
<head>
    <title>Safari Debug Logs</title>
    <meta charset="utf-8">
    <meta name="robots" content="noindex, nofollow">
    <style>
        body {
            font-family: monospace;
            margin: 20px;
            background: #1e1e1e;
            color: #d4d4d4;
        }
        .log-container {
            background: #2d2d2d;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid #404040;
        }
        .log-entry {
            margin-bottom: 10px;
            padding: 8px;
            border-left: 3px solid #007acc;
            background: #252526;
        }
        .timestamp {
            color: #608b4e;
            font-weight: bold;
        }
        .message {
            color: #dcdcaa;
            font-weight: bold;
            margin: 5px 0;
        }
        .data {
            color: #ce9178;
            margin-left: 20px;
            white-space: pre-wrap;
        }
        .error {
            border-left-color: #f14c4c;
            background: #332222;
        }
        .error .message {
            color: #f14c4c;
        }
        .clear-logs {
            background: #0e639c;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 3px;
            margin: 10px 5px;
        }
        .clear-logs:hover {
            background: #1177bb;
        }
        h1, h2 {
            color: #4ec9b0;
        }
        .stats {
            background: #0f3460;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            color: #9cdcfe;
        }
    </style>
</head>
<body>
    <h1>Safari Request Debug Logs</h1>
    <p>Generated: <?php echo date('Y-m-d H:i:s'); ?></p>
    
    <?php if ($debug_key !== $expected_key): ?>
    <div class="stats">
        <strong>Debug Key:</strong> Use <code>?key=<?php echo htmlspecialchars($expected_key); ?></code> for access without WP_DEBUG
    </div>
    <?php endif; ?>

    <div>
        <button class="clear-logs" onclick="if(confirm('Clear Safari debug logs?')) { window.location.href='?clear=safari&key=<?php echo urlencode($debug_key); ?>'; }">
            Clear Safari Logs
        </button>
        <button class="clear-logs" onclick="if(confirm('Clear WordPress debug logs?')) { window.location.href='?clear=wp&key=<?php echo urlencode($debug_key); ?>'; }">
            Clear WP Debug Log
        </button>
        <button class="clear-logs" onclick="window.location.reload();">Refresh</button>
    </div>

    <?php
    // Handle log clearing
    if (isset($_GET['clear'])) {
        if ($_GET['clear'] === 'safari' && file_exists($log_file)) {
            file_put_contents($log_file, '');
            echo '<div class="stats">Safari debug log cleared.</div>';
        } elseif ($_GET['clear'] === 'wp' && file_exists($wp_debug_log)) {
            file_put_contents($wp_debug_log, '');
            echo '<div class="stats">WordPress debug log cleared.</div>';
        }
    }

    // Display Safari debug log
    if (file_exists($log_file)) {
        $log_content = file_get_contents($log_file);
        $log_entries = array_filter(explode("\n", $log_content));
        $total_entries = count($log_entries);
        
        echo '<h2>Safari Debug Log (' . $total_entries . ' entries)</h2>';
        
        if ($total_entries > 0) {
            // Show recent entries first
            $log_entries = array_reverse($log_entries);
            $shown_entries = array_slice($log_entries, 0, 50); // Show last 50 entries
            
            echo '<div class="log-container">';
            foreach ($shown_entries as $entry) {
                if (empty(trim($entry))) continue;
                
                // Parse log entry
                if (preg_match('/\[(.*?)\] (.*?) \| (.*)/', $entry, $matches)) {
                    $timestamp = $matches[1];
                    $message = $matches[2];
                    $data = $matches[3];
                    
                    $is_error = (strpos($message, 'ERROR') !== false || strpos($message, 'FATAL') !== false);
                    
                    echo '<div class="log-entry' . ($is_error ? ' error' : '') . '">';
                    echo '<div class="timestamp">' . htmlspecialchars($timestamp) . '</div>';
                    echo '<div class="message">' . htmlspecialchars($message) . '</div>';
                    
                    // Pretty print JSON data
                    $decoded = json_decode($data, true);
                    if ($decoded) {
                        echo '<div class="data">' . htmlspecialchars(json_encode($decoded, JSON_PRETTY_PRINT)) . '</div>';
                    } else {
                        echo '<div class="data">' . htmlspecialchars($data) . '</div>';
                    }
                    echo '</div>';
                }
            }
            echo '</div>';
            
            if ($total_entries > 50) {
                echo '<div class="stats">Showing 50 most recent entries of ' . $total_entries . ' total.</div>';
            }
        } else {
            echo '<div class="stats">No Safari debug entries found. Make a request with Safari to generate logs.</div>';
        }
    } else {
        echo '<div class="stats">Safari debug log file not found: ' . htmlspecialchars($log_file) . '</div>';
    }

    // Display recent WordPress debug log entries that contain Safari info
    if (file_exists($wp_debug_log)) {
        $wp_log_content = file_get_contents($wp_debug_log);
        $wp_log_lines = array_filter(explode("\n", $wp_log_content));
        
        // Filter for Safari-related entries
        $safari_entries = array_filter($wp_log_lines, function($line) {
            return (strpos($line, 'SAFARI') !== false || strpos($line, 'Safari') !== false);
        });
        
        if (!empty($safari_entries)) {
            echo '<h2>WordPress Debug Log - Safari Entries (' . count($safari_entries) . ' found)</h2>';
            echo '<div class="log-container">';
            
            // Show recent Safari entries
            $recent_safari = array_reverse(array_slice($safari_entries, -20));
            foreach ($recent_safari as $entry) {
                echo '<div class="log-entry">';
                echo '<div class="data">' . htmlspecialchars($entry) . '</div>';
                echo '</div>';
            }
            
            echo '</div>';
        }
    }
    ?>

    <div class="stats">
        <h3>Instructions:</h3>
        <ol>
            <li>Visit <a href="https://upskill-staging.measurequick.com/find-a-trainer/" target="_blank" style="color: #4fc1ff;">https://upskill-staging.measurequick.com/find-a-trainer/</a> with Safari</li>
            <li>Refresh this page to see debug logs</li>
            <li>Look for FATAL ERROR or REQUEST COMPLETED entries</li>
            <li>Check memory usage patterns and plugin interactions</li>
        </ol>
        
        <p><strong>Log Locations:</strong></p>
        <ul>
            <li>Safari Debug: <?php echo htmlspecialchars($log_file); ?></li>
            <li>WordPress Debug: <?php echo htmlspecialchars($wp_debug_log); ?></li>
        </ul>
    </div>
</body>
</html>