<?php
defined('ABSPATH') || exit;

function businessbot_chat_assist_get_debug_log_candidates() {
    $paths = [];

    $ini_error_log = ini_get('error_log');
    if (is_string($ini_error_log) && '' !== trim($ini_error_log)) {
        $paths[] = trim($ini_error_log);
    }

    if (defined('WP_CONTENT_DIR')) {
        $paths[] = WP_CONTENT_DIR . '/debug.log';
    }

    return array_values(array_unique(array_filter($paths)));
}

function businessbot_chat_assist_read_debug_lines($max_lines = 200) {
    $candidates = businessbot_chat_assist_get_debug_log_candidates();

    foreach ($candidates as $path) {
        if (!is_string($path) || '' === $path || !file_exists($path) || !is_readable($path)) {
            continue;
        }

        $content = file_get_contents($path);
        if (!is_string($content) || '' === $content) {
            continue;
        }

        $lines = preg_split('/\r\n|\r|\n/', $content);
        if (!is_array($lines) || empty($lines)) {
            continue;
        }

        $matches = [];
        foreach ($lines as $line) {
            if (false !== strpos((string) $line, '[BusinessBot Debug]')) {
                $matches[] = (string) $line;
            }
        }

        if (!empty($matches)) {
            return [
                'path' => $path,
                'lines' => array_slice($matches, -absint($max_lines)),
                'total' => count($matches),
            ];
        }
    }

    return [
        'path' => '',
        'lines' => [],
        'total' => 0,
    ];
}

function businessbot_chat_assist_logs_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $debug_mode = get_option('businessbot_debug_mode', 'no');
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only filter parameter for logs page.
    $max_lines = isset($_GET['max_lines']) ? absint(wp_unslash($_GET['max_lines'])) : 200;
    if ($max_lines < 50) {
        $max_lines = 50;
    } elseif ($max_lines > 1000) {
        $max_lines = 1000;
    }

    $result = businessbot_chat_assist_read_debug_lines($max_lines);
    ?>
    <div class="wrap businessbot-admin-shell">
        <div class="businessbot-profile-wrap businessbot-settings-wrap">
            <div class="businessbot-page-header">
                <div>
                    <h1><?php esc_html_e('Logs', 'ai-chat-assistant-for-business'); ?></h1>
                    <p><?php esc_html_e('View recent BusinessBot debug logs generated by the AI request pipeline.', 'ai-chat-assistant-for-business'); ?></p>
                </div>
            </div>

            <div class="businessbot-card">
                <h2><span class="dashicons dashicons-media-text"></span><?php esc_html_e('Debug Status', 'ai-chat-assistant-for-business'); ?></h2>
                <p class="businessbot-help businessbot-help-strong">
                    <?php echo ('yes' === $debug_mode) ? esc_html__('Debug mode is enabled.', 'ai-chat-assistant-for-business') : esc_html__('Debug mode is disabled. Enable it from Settings to capture logs.', 'ai-chat-assistant-for-business'); ?>
                </p>
                <?php if (!empty($result['path'])) : ?>
                    <p class="businessbot-help"><strong><?php esc_html_e('Log file:', 'ai-chat-assistant-for-business'); ?></strong> <code><?php echo esc_html($result['path']); ?></code></p>
                <?php else : ?>
                    <p class="businessbot-help"><?php esc_html_e('No readable log file with BusinessBot debug entries found yet.', 'ai-chat-assistant-for-business'); ?></p>
                <?php endif; ?>
                <p class="businessbot-help"><strong><?php esc_html_e('Matching entries found:', 'ai-chat-assistant-for-business'); ?></strong> <?php echo esc_html((string) (int) $result['total']); ?></p>
            </div>

            <div class="businessbot-card">
                <h2><span class="dashicons dashicons-list-view"></span><?php esc_html_e('Recent Debug Entries', 'ai-chat-assistant-for-business'); ?></h2>
                <p>
                    <a class="button" href="<?php echo esc_url(add_query_arg(['page' => 'businessbot-logs', 'max_lines' => $max_lines], admin_url('admin.php'))); ?>"><?php esc_html_e('Refresh', 'ai-chat-assistant-for-business'); ?></a>
                    <a class="button button-secondary" href="<?php echo esc_url(admin_url('admin.php?page=businessbot-settings')); ?>"><?php esc_html_e('Open Settings', 'ai-chat-assistant-for-business'); ?></a>
                </p>
                <?php if (!empty($result['lines'])) : ?>
                    <textarea readonly rows="20" style="width:100%;font-family:monospace;"><?php echo esc_textarea(implode("\n", $result['lines'])); ?></textarea>
                <?php else : ?>
                    <p class="businessbot-help"><?php esc_html_e('No debug entries yet. Send a few chat messages after enabling debug mode, then refresh.', 'ai-chat-assistant-for-business'); ?></p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
}

