<?php

/**
 * MassPost Diagnostics - Safe Production Debugging Tool
 *
 * USAGE:
 * 1. Include this file in masspost.php: require_once __DIR__ . '/masspost-diagnostics.php';
 * 2. Enable logging: define('MASSPOST_DEBUG', true); in wp-config.php
 * 3. View logs in: wp-content/debug.log or use the diagnostics page
 *
 * SAFETY: This file only LOGS - it doesn't modify any functionality
 */

if (!defined("ABSPATH")) {
    exit();
}

/**
 * Check if debug mode is enabled
 */
function masspost_is_debug_enabled()
{
    return defined('MASSPOST_DEBUG') && MASSPOST_DEBUG === true;
}

/**
 * Get debug status details (for troubleshooting)
 */
function masspost_get_debug_status_details()
{
    $details = [];

    if (defined('MASSPOST_DEBUG')) {
        $details['defined'] = true;
        $details['value'] = MASSPOST_DEBUG;
        $details['type'] = gettype(MASSPOST_DEBUG);
        $details['is_true'] = (MASSPOST_DEBUG === true);
    } else {
        $details['defined'] = false;
        $details['value'] = null;
        $details['type'] = null;
        $details['is_true'] = false;
    }

    return $details;
}

/**
 * Safe logging function - only logs when debug enabled
 */
function masspost_debug_log($message, $context = '')
{
    if (!masspost_is_debug_enabled()) {
        return;
    }

    $timestamp = current_time('Y-m-d H:i:s');
    $context_str = $context ? " [{$context}]" : '';
    $log_message = "[{$timestamp}] MassPost{$context_str}: {$message}";

    // Log to debug.log if WP_DEBUG_LOG is enabled
    if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
        error_log($log_message); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional for debug mode
    }

    // Also store in option for easy viewing (last 50 entries)
    $logs = get_option('masspost_debug_logs', []);
    array_unshift($logs, ['time' => $timestamp, 'message' => $message, 'context' => $context]);
    $logs = array_slice($logs, 0, 50); // Keep last 50 entries
    update_option('masspost_debug_logs', $logs, false);
}

/**
 * Hook into permission callback to log authentication attempts
 */
add_filter('rest_request_before_callbacks', function ($response, $handler, $request) {
    $route = $request->get_route();

    // Only log MassPost endpoints
    if (strpos($route, '/masspost/v1/') === false) {
        return $response;
    }

    masspost_debug_log("REST request to: {$route}", 'REST');

    // Log authorization header (masked)
    $auth_header = $request->get_header('authorization');
    if ($auth_header) {
        $token = preg_replace("/^Bearer\s+/i", "", $auth_header);
        $masked_token = substr($token, 0, 5) . '***' . substr($token, -5);
        masspost_debug_log("Auth header present: Bearer {$masked_token}", 'AUTH');
    } else {
        masspost_debug_log("Auth header MISSING", 'AUTH');
    }

    // Log configured token (masked)
    $stored_token = get_option('masspost_api_token', '');
    if ($stored_token) {
        $masked_stored = substr($stored_token, 0, 5) . '***' . substr($stored_token, -5);
        masspost_debug_log("Configured Pass Key: {$masked_stored}", 'CONFIG');
    } else {
        masspost_debug_log("Pass Key NOT CONFIGURED on this site!", 'CONFIG-ERROR');
    }

    // Log configured user
    $api_user = get_option('masspost_api_user', '');
    if ($api_user) {
        masspost_debug_log("Configured User: {$api_user}", 'CONFIG');
    } else {
        masspost_debug_log("User NOT CONFIGURED on this site!", 'CONFIG-ERROR');
    }

    return $response;
}, 10, 3);

/**
 * Log permission callback results
 */
add_action('rest_api_init', function () {
    // Wrap the permission callback to log results
    $original_callback = 'masspost_permission_callback';

    add_filter('rest_pre_dispatch', function ($result, $server, $request) {
        $route = $request->get_route();

        if (strpos($route, '/masspost/v1/') === false) {
            return $result;
        }

        // Test permission callback
        $permission_result = masspost_permission_callback($request);

        if (is_wp_error($permission_result)) {
            masspost_debug_log(
                "Permission DENIED: " . $permission_result->get_error_message() .
                    " (Code: " . $permission_result->get_error_code() . ")",
                'PERMISSION-ERROR'
            );
        } else {
            masspost_debug_log("Permission GRANTED", 'PERMISSION');
            $current_user = wp_get_current_user();
            masspost_debug_log("User set to: {$current_user->user_login} (ID: {$current_user->ID})", 'USER');
        }

        return $result;
    }, 10, 3);
}, 9); // Run before endpoint registration

/**
 * Log outgoing requests
 */
add_filter('http_request_args', function ($args, $url) {
    // Only log MassPost requests
    if (strpos($url, '/masspost/v1/') === false) {
        return $args;
    }

    masspost_debug_log("Sending request to: {$url}", 'SEND');

    // Log if this is a GET or POST
    $method = isset($args['method']) ? $args['method'] : 'GET';
    masspost_debug_log("Request method: {$method}", 'SEND');

    return $args;
}, 10, 2);

/**
 * Log HTTP responses
 */
add_action('http_api_debug', function ($response, $context, $class, $args, $url) {
    // Only log MassPost requests
    if (strpos($url, '/masspost/v1/') === false) {
        return;
    }

    if (is_wp_error($response)) {
        masspost_debug_log(
            "HTTP Error: " . $response->get_error_message(),
            'SEND-ERROR'
        );
    } else {
        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);

        masspost_debug_log("Response code: {$code}", 'RESPONSE');

        if ($code !== 200 && $code !== 204) {
            masspost_debug_log("Response body: {$body}", 'RESPONSE-ERROR');
        } else {
            masspost_debug_log("Response: Success", 'RESPONSE');
        }
    }
}, 10, 5);

/**
 * Add diagnostics page to admin menu
 */
add_action('admin_menu', function () {
    add_submenu_page(
        'masspost',
        'Diagnostics',
        'Diagnostics',
        'manage_options',
        'masspost-diagnostics',
        'masspost_diagnostics_page'
    );
}, 20);

/**
 * Diagnostics admin page
 */
/**
 * Diagnostics admin page
 */
function masspost_diagnostics_page()
{
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }

    // Handle log clear
    if (isset($_POST['clear_logs']) && check_admin_referer('masspost_clear_logs')) {
        delete_option('masspost_debug_logs');
        echo '<div class="notice notice-success"><p>Logs cleared.</p></div>';
    }

    $is_debug_enabled = masspost_is_debug_enabled();
    $debug_details = masspost_get_debug_status_details();
?>
    <div class="masspost-admin-wrap">
        <header class="masspost-header">
            <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'assets/images/masspost-logo-light.svg'); ?>" alt="MassPost Logo">
            <h1><?php esc_html_e('Diagnostics', 'masspost'); ?></h1>
            <p class="masspost-subtitle"><?php esc_html_e('Technical system check and debugging logs for your multi-site network.', 'masspost'); ?></p>
        </header>

        <div class="masspost-premium-card">
            <div class="masspost-premium-card-header">
                <h3 class="masspost-premium-card-title"><?php esc_html_e('Debug Status', 'masspost'); ?></h3>
                <?php if ($is_debug_enabled): ?>
                    <span class="mp-pill mp-pill-active"><?php esc_html_e('Enabled', 'masspost'); ?></span>
                <?php else: ?>
                    <span class="mp-pill mp-pill-inactive"><?php esc_html_e('Disabled', 'masspost'); ?></span>
                <?php endif; ?>
            </div>
            <div class="masspost-premium-card-content">
                <?php if ($is_debug_enabled): ?>
                    <p><code>define('MASSPOST_DEBUG', true);</code> is active in wp-config.php</p>
                <?php else: ?>
                    <?php if ($debug_details['defined']): ?>
                        <div style="background: #fef2f2; border-radius: 8px; padding: 16px; border: 1px solid #fee2e2;">
                            <strong style="color: #dc2626;">⚠ MASSPOST_DEBUG is defined but has wrong value!</strong><br>
                            Current value: <code><?php echo esc_html(var_export($debug_details['value'], true)); ?></code><br>
                            Current type: <code><?php echo esc_html($debug_details['type']); ?></code><br><br>
                            <strong>Problem:</strong> You used quotes around <code>true</code><br>
                            <strong>Fix:</strong> Change to <code>define('MASSPOST_DEBUG', true);</code> (without quotes around true)
                        </div>
                    <?php else: ?>
                        <p><strong>MASSPOST_DEBUG is not defined.</strong> To enable, add this to wp-config.php before the final line:</p>
                        <div class="masspost-code-block">define('MASSPOST_DEBUG', true);</div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="masspost-premium-card">
            <div class="masspost-premium-card-header">
                <h3 class="masspost-premium-card-title"><?php esc_html_e('Configuration Check', 'masspost'); ?></h3>
            </div>
            <div class="masspost-premium-card-content">
                <?php
                $api_token = get_option('masspost_api_token', '');
                $api_user = get_option('masspost_api_user', '');
                $websites = get_option('masspost_websites', []);
                ?>
                <div class="masspost-repeater">
                    <div class="masspost-repeater-item" style="cursor: default;">
                        <div class="masspost-repeater-fields">
                            <div class="masspost-field-group">
                                <label class="masspost-label"><?php esc_html_e('Pass Key (Receive)', 'masspost'); ?></label>
                                <?php if ($api_token): ?>
                                    <div class="masspost-code-block"><?php echo esc_html(substr($api_token, 0, 5) . '***' . substr($api_token, -5)); ?> <span class="mp-pill mp-pill-active" style="float: right;"><?php esc_html_e('Ready', 'masspost'); ?></span></div>
                                <?php else: ?>
                                    <div class="masspost-code-block" style="color: #dc2626;"><?php esc_html_e('NOT CONFIGURED', 'masspost'); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="masspost-field-group">
                                <label class="masspost-label"><?php esc_html_e('API User (Receive)', 'masspost'); ?></label>
                                <?php if ($api_user): ?>
                                    <div class="masspost-code-block">
                                        <?php
                                        $user = is_numeric($api_user) ? get_user_by('id', (int)$api_user) : get_user_by('login', $api_user);
                                        if ($user) {
                                            echo esc_html($user->user_login . " (ID: {$user->ID})");
                                            if (!user_can($user, 'edit_posts')) {
                                                echo ' <span class="mp-pill mp-pill-inactive" style="float: right;">Lacks Capability</span>';
                                            } else {
                                                echo ' <span class="mp-pill mp-pill-active" style="float: right;">Valid</span>';
                                            }
                                        } else {
                                            echo '<span style="color: #dc2626;">User not found!</span>';
                                        }
                                        ?>
                                    </div>
                                <?php else: ?>
                                    <div class="masspost-code-block" style="color: #dc2626;"><?php esc_html_e('NOT CONFIGURED', 'masspost'); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="masspost-repeater-item" style="cursor: default;">
                        <label class="masspost-label" style="display: block; margin-bottom: 8px;"><?php esc_html_e('Target Nodes (Outgoing)', 'masspost'); ?></label>
                        <?php if (!empty($websites)): ?>
                            <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                                <?php foreach ($websites as $site): ?>
                                    <span class="mp-pill mp-pill-pending" style="background: #f3f4f6; border-color: #e5e7eb; color: #374151;"><?php echo esc_html($site['name']); ?></span>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p style="color: #d97706; margin: 0;"><?php esc_html_e('No target nodes configured.', 'masspost'); ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="masspost-premium-card">
            <div class="masspost-premium-card-header">
                <h3 class="masspost-premium-card-title"><?php esc_html_e('REST API Infrastructure', 'masspost'); ?></h3>
            </div>
            <div class="masspost-premium-card-content">
                <p><?php esc_html_e('Your endpoint for receiving posts:', 'masspost'); ?></p>
                <div class="masspost-code-block" style="margin-bottom: 16px;"><?php echo esc_url(home_url('/wp-json/masspost/v1/post/')); ?></div>
                <a href="<?php echo esc_url(home_url('/wp-json/masspost/v1/')); ?>" target="_blank" class="masspost-btn mp-btn-outline" style="width: auto;">
                    <span class="dashicons dashicons-external"></span> <?php esc_html_e('Test API Endpoint', 'masspost'); ?>
                </a>
                <p class="description" style="margin-top: 12px;"><?php esc_html_e('Should return a status error (expected since no token is sent), but confirms the endpoint is reachable.', 'masspost'); ?></p>
            </div>
        </div>

        <?php if ($is_debug_enabled): ?>
            <div class="masspost-premium-card">
                <div class="masspost-premium-card-header">
                    <h3 class="masspost-premium-card-title"><?php esc_html_e('Real-time Debug Logs', 'masspost'); ?></h3>
                    <form method="post" style="margin: 0;">
                        <?php wp_nonce_field('masspost_clear_logs'); ?>
                        <button type="submit" name="clear_logs" class="masspost-btn mp-btn-remove">
                            <span class="dashicons dashicons-trash"></span>
                        </button>
                    </form>
                </div>
                <div class="masspost-premium-card-content">
                    <?php
                    $logs = get_option('masspost_debug_logs', []);
                    if (empty($logs)):
                    ?>
                        <p><em><?php esc_html_e('No log entries yet. Sync operations will appear here.', 'masspost'); ?></em></p>
                    <?php else: ?>
                        <div style="overflow-x: auto; border: 1px solid #e5e7eb; border-radius: 8px;">
                            <table class="widefat" style="border: none; box-shadow: none;">
                                <thead>
                                    <tr>
                                        <th style="background: #f9fafb;"><?php esc_html_e('Timestamp', 'masspost'); ?></th>
                                        <th style="background: #f9fafb;"><?php esc_html_e('Context', 'masspost'); ?></th>
                                        <th style="background: #f9fafb;"><?php esc_html_e('Message', 'masspost'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($logs as $log): ?>
                                        <tr>
                                            <td style="font-family: monospace; font-size: 11px; color: #6b7280;"><?php echo esc_html($log['time']); ?></td>
                                            <td><span class="mp-pill" style="background: #f3f4f6; color: #111827;"><?php echo esc_html($log['context']); ?></span></td>
                                            <td style="font-family: monospace; font-size: 12px;"><?php echo esc_html($log['message']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="masspost-premium-card">
            <div class="masspost-premium-card-header">
                <h3 class="masspost-premium-card-title"><?php esc_html_e('Quick Troubleshooting', 'masspost'); ?></h3>
            </div>
            <div class="masspost-premium-card-content">
                <ul style="list-style-type: none; padding: 0; margin: 0;">
                    <li style="padding-bottom: 12px; border-bottom: 1px solid #f3f4f6; margin-bottom: 12px;"><strong>1. Check Target Configuration:</strong> Ensure Pass Key and User ID are identical on both source and target.</li>
                    <li style="padding-bottom: 12px; border-bottom: 1px solid #f3f4f6; margin-bottom: 12px;"><strong>2. Security Plugins:</strong> If you use Wordfence or similar, whitelist the <code>/wp-json/masspost/</code> directory.</li>
                    <li style="padding-bottom: 12px; border-bottom: 1px solid #f3f4f6; margin-bottom: 12px;"><strong>3. Permalinks:</strong> WordPress REST API requires "Pretty Permalinks". Enable them in Settings → Permalinks.</li>
                    <li><strong>4. Check PHP Limits:</strong> For large networks, ensure <code>max_execution_time</code> is at least 60 seconds.</li>
                </ul>
            </div>
        </div>
    </div>
<?php
}
