<?php
if (!defined("ABSPATH")) {
    exit();
}
// Este script é a interface administrativa principal do plugin WP Tools para visualização e análise de logs de erro. 
//Aba "Error Table": Tabela detalhada com logs de erro

//Aba "Chat": Interface de chat com IA para análise de erros
// register_tick_function('meu_tick_function');
// declare(ticks=1);
// wptools_show_logo();






// =======================

if (current_user_can('manage_options')) {
    wptools_render_tabs_page();
}

return;





// Função que será chamada na primeira aba





// Função que será chamada na segunda aba




// Função que renderiza a página com as abas
function wptools_render_tabs_page_old()
{
?>
    <div class="wrap">


        <?php wptools_show_logo();

        // <h1 style="color: gray; text-align: center;"><?php esc_attr_e("Show Site Errors", 'wptools'); 
        // </h1>
        ?>



        <?php
        //$active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'table';
        $active_tab = isset($_GET['tab']) && in_array($_GET['tab'], ['table', 'chat']) ? sanitize_key($_GET['tab']) : 'table';
        $page_slug = 'wptools_options21'; // O slug do menu que você definiu em add_options_page
        ?>

        <h2 class="nav-tab-wrapper">
            <a href="?page=<?php echo esc_attr($page_slug); ?>&tab=table" class="nav-tab <?php echo $active_tab == 'table' ? 'nav-tab-active' : ''; ?>">
                <?php esc_html_e('Error Table', 'wptools'); // 'wptools' é o text domain para tradução 
                ?>
            </a>
            <a href="?page=<?php echo esc_attr($page_slug); ?>&tab=chat" class="nav-tab <?php echo $active_tab == 'chat' ? 'nav-tab-active' : ''; ?>">
                <?php esc_html_e('Chat With AI and Server Errors Checkup', 'wptools'); ?>
            </a>
        </h2>

        <div class="tab-content" style="margin-top: 20px;">
            <?php
            if ($active_tab == 'table') {
                wptools_show_error_table();
            } elseif ($active_tab == 'chat') {
                wptools_chat();
            }
            ?>
        </div>


    </div>
<?php
}



function wptools_render_tabs_page()
{
?>
    <div class="wrap">
        <?php wptools_show_logo(); ?>

        <?php
        $active_tab = isset($_GET['tab']) && in_array($_GET['tab'], ['table', 'summary', 'chat']) ? sanitize_key($_GET['tab']) : 'table';
        $page_slug = 'wptools_options21';
        ?>

        <h2 class="nav-tab-wrapper">
            <a href="?page=<?php echo esc_attr($page_slug); ?>&tab=table" class="nav-tab <?php echo $active_tab == 'table' ? 'nav-tab-active' : ''; ?>">
                <?php esc_html_e('Error Table', 'wptools'); ?>
            </a>
            <a href="?page=<?php echo esc_attr($page_slug); ?>&tab=summary" class="nav-tab <?php echo $active_tab == 'summary' ? 'nav-tab-active' : ''; ?>">
                <?php esc_html_e('Error Summary', 'wptools'); ?>
            </a>
            <a href="?page=<?php echo esc_attr($page_slug); ?>&tab=chat" class="nav-tab <?php echo $active_tab == 'chat' ? 'nav-tab-active' : ''; ?>">
                <?php esc_html_e('Chat With AI and Server Errors Checkup', 'wptools'); ?>
            </a>
        </h2>

        <div class="tab-content" style="margin-top: 20px;">
            <?php
            if ($active_tab == 'table') {
                wptools_show_error_table();
            } elseif ($active_tab == 'summary') {
                wptools_show_error_summary();
            } elseif ($active_tab == 'chat') {
                wptools_chat();
            }
            ?>
        </div>
    </div>
<?php
}


// Function for the new summary tab
function wptools_show_error_summary()
{
    echo '<h1 style="color: gray; text-align: center;">' . esc_attr__("Error Summary", 'wptools') . '</h1>';

    // Get the selected log file
    $default_file = ABSPATH . 'error_log';
    $selected_log_file = get_option('wptools_log_file_name_option', $default_file);

    // Display file information at the top
    if (file_exists($selected_log_file)) {
        $file_size = filesize($selected_log_file);
        $file_mtime = filemtime($selected_log_file);
        $file_date = date('Y-m-d H:i:s', $file_mtime);

        echo '<div style="background: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 5px; border-left: 4px solid #0073aa;">';
        echo '<div style="font-family: Arial, sans-serif; font-size: 14px; text-align: center; line-height: 1.6;">';
        echo '<span style="margin-right: 25px;"><strong>' . esc_attr__('Log File:', 'wptools') . '</strong> ' . esc_html(basename($selected_log_file)) . '</span>';
        echo '<span style="margin-right: 25px;"><strong>' . esc_attr__('Location:', 'wptools') . '</strong> ' . esc_html(dirname($selected_log_file)) . '</span>';
        echo '<span style="margin-right: 25px;"><strong>' . esc_attr__('Size:', 'wptools') . '</strong> ' . size_format($file_size, 2) . '</span>';
        echo '<span><strong>' . esc_attr__('Last Modified:', 'wptools') . '</strong> ' . esc_html($file_date) . '</span>';
        echo '</div>';
        echo '</div>';
    } else {
        echo '<div style="background: #f8d7da; padding: 12px; margin: 15px 0; border-radius: 5px; border-left: 4px solid #dc3545;">';
        echo '<div style="color: #dc3545; font-weight: bold; text-align: center;">';
        echo esc_attr__('Selected log file not found:', 'wptools') . ' ' . esc_html($selected_log_file);
        echo '</div>';
        echo '</div>';
        return;
    }

    // Get error types count from the SELECTED log file only
    $error_types_count = wptools_count_error_types($selected_log_file);

    // Display the summary table
    wptools_print_error_summary($error_types_count);
}

// Count error types from the SPECIFIED log file only
function wptools_count_error_types($log_file_path)
{
    // Enhanced error types count array
    $error_types_count = [
        "Deprecated" => 0,
        "Fatal" => 0,
        "Warning" => 0,
        "Notice" => 0,
        "Parse" => 0,
        "Strict" => 0,
        "Recoverable" => 0,
        "Core" => 0,
        "Compile" => 0,
        "User" => 0,
        "Database" => 0,
        "JavaScript" => 0,
        "Filesystem" => 0,
        "HTTP_API" => 0,
        "Other" => 0,
    ];

    // Global safety limits - JÁ EXISTIAM na função original
    $max_total_lines = 5000;      // Maximum lines to process across all files
    $max_execution_time = 15;     // Maximum execution time in seconds
    $start_time = time();         // Start time for timeout control
    $total_lines_processed = 0;   // Global line counter

    // Check if file exists
    if (!file_exists($log_file_path)) {
        return $error_types_count;
    }

    // Skip backup files
    if (strpos($log_file_path, "backup") !== false) {
        return $error_types_count;
    }

    // Process the SINGLE selected file line by line for memory efficiency
    $file = fopen($log_file_path, 'r');
    if ($file) {


        $ctd  = 0;

        while (($line = fgets($file)) !== false) {
            // Check global limits every 50 lines for performance - JÁ EXISTIA
            if ($total_lines_processed % 50 === 0) {
                if ($total_lines_processed >= $max_total_lines) {
                    break; // Exit loop
                }
                if (time() - $start_time >= $max_execution_time) {
                    break; // Exit loop
                }
            }

            $line = trim($line);

            ///

            /*
            if ($ctd > 5) {
                continue;
            }


            $first = substr($line, 0, 4);
            echo "First 4 chars (raw): " . implode(' ', array_map('ord', str_split($first))) . PHP_EOL;
            echo "Line exported: " . var_export($line, true) . PHP_EOL;
            $ctd++;
            ///
            */


            // *** MUDANÇA: FILTROS MAIS RESTRITIVOS PARA STACK TRACE ***
            if (
                empty($line) ||
                strpos($line, "[") !== 0 ||
                preg_match("/PHP Stack trace:/", $line) ||
                preg_match("/\d{4}-\w{3}-\d{4} \d{2}:\d{2}:\d{2} UTC\] PHP \d+\./", $line) ||
                substr($line, 0, 1) === '#' ||
                strpos($line, 'Stack trace:') !== false
            ) {
                continue;
            }

            // Check for JavaScript errors
            if (strpos($line, "Javascript") !== false || strpos($line, "JavaScript") !== false) {
                $apattern = [];
                $apattern[] = "/(JavaScript\s+)?(Error|SyntaxError|TypeError|ReferenceError|RangeError|EvalError|URIError):?\s*(.*?)\s*(at\s+.*)?(\s*URL:\s*(https?:\/\/\S+))?.*?(Line\s*:?[\s\d]+)?/i";

                $pattern = $apattern[0];
                for ($j = 0; $j < count($apattern); $j++) {
                    if (preg_match($apattern[$j], $line, $matches)) {
                        $pattern = $apattern[$j];
                        break;
                    }
                }

                if (preg_match($pattern, $line, $matches)) {
                    $error_types_count["JavaScript"]++;
                }
                $total_lines_processed++;
                continue;
            }

            // Process PHP errors
            $apattern = [];
            //$apattern[] = "/^\[.*\] PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*) in \/([^ ]+) on line (\d+)/";
            //$apattern[] = "/^\[.*\] PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*) in \/([^ ]+):(\d+)$/";


            //$apattern[] = "/^\[.*\] PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*)/";
            //$apattern[] = "/^\[.*\] PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*) in \/([^ ]+) on line (\d+)/";
            // $apattern[] = "/^\[.*\] PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*) in \/([^ ]+):(\d+)$/";


            // $apattern[] = "/PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*)/i";
            // $apattern[] = "/PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*) in \/([^ ]+) on line (\d+)/i";
            // $apattern[] = "/PHP (Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated): (.*) in \/([^ ]+):(\d+)$/i";


            // $apattern[] = "/-?\s*PHP\s+(Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated):\s*(.*)/i";
            // $apattern[] = "/-?\s*PHP\s+(Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated):\s*(.*)\s+in\s+\/([^ ]+)\s+on\s+line\s+(\d+)/i";
            // $apattern[] = "/-?\s*PHP\s+(Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated):\s*(.*)\s+in\s+\/([^ ]+):(\d+)$/i";









            // --- START: Replace existing $apattern definitions and selection loop ---
            // Build patterns that match error info anywhere na linha (ignoring the timestamp)
            $apattern = [];

            // standard PHP-style messages (PHP Warning: ... etc.) anywhere in the line
            $apattern[] = "/PHP\s+(Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated):\s*(.*)/i";

            // PHP message form used by WP: "PHP message: PHP Warning: ..." anywhere
            $apattern[] = "/PHP message:\s*PHP\s+(Warning|Error|Notice|Fatal error|Parse error|Recoverable fatal error|Core error|Core warning|Compile error|Compile warning|Deprecated|Strict Standards|User Error|User Warning|User Notice|User Deprecated):\s*(.*)/i";

            // uncaught errors/exceptions
            $apattern[] = "/Uncaught\s+(Error|Exception):?\s*(.*)/i";

            // plain lines that start with the type but may not include 'PHP' (match anywhere too)
            $apattern[] = "/(Warning|Error|Notice|Deprecated|Fatal error|Parse error|Recoverable fatal error|Strict Standards):\s*(.*)/i";

            // a fallback for lines containing "] PHP Warning" or similar after a timestamp+dash
            $apattern[] = "/\]\s*-?\s*PHP\s+(Warning|Error|Notice|Fatal error|Parse error):/i";

            // Choose the first pattern that matches (keep your existing approach)







            $pattern = $apattern[0];
            for ($j = 0; $j < count($apattern); $j++) {
                if (preg_match($apattern[$j], $line, $matches)) {
                    $pattern = $apattern[$j];
                    break;
                }
            }

            if (preg_match($pattern, $line, $matches)) {
                $error_type = $matches[1];
                $error_description = $matches[2];

                // Enhanced PHP error categorization
                if (stripos($error_type, "deprecated") !== false) {
                    $error_types_count["Deprecated"]++;
                } elseif (
                    stripos($error_type, "fatal") !== false &&
                    stripos($error_type, "recoverable") === false
                ) {
                    $error_types_count["Fatal"]++;
                } elseif (stripos($error_type, "recoverable") !== false) {
                    $error_types_count["Recoverable"]++;
                } elseif (
                    stripos($error_type, "warning") !== false &&
                    stripos($error_type, "core") === false &&
                    stripos($error_type, "compile") === false &&
                    stripos($error_type, "user") === false
                ) {
                    $error_types_count["Warning"]++;
                } elseif (
                    stripos($error_type, "notice") !== false &&
                    stripos($error_type, "user") === false
                ) {
                    $error_types_count["Notice"]++;
                } elseif (stripos($error_type, "parse") !== false) {
                    $error_types_count["Parse"]++;
                } elseif (stripos($error_type, "strict") !== false) {
                    $error_types_count["Strict"]++;
                } elseif (stripos($error_type, "core") !== false) {
                    $error_types_count["Core"]++;
                } elseif (stripos($error_type, "compile") !== false) {
                    $error_types_count["Compile"]++;
                } elseif (stripos($error_type, "user") !== false) {
                    $error_types_count["User"]++;
                } else {
                    $error_types_count["Other"]++;
                }

                // Enhanced database error detection
                if (preg_match("/(database|mysql|mysqli|wpdb|pdo|SQLSTATE|Query failed|Connection refused|Access denied|database connection|Unknown column|Syntax error in SQL)/i", $error_description)) {
                    $error_types_count["Database"]++;
                }

                // Filesystem error detection
                if (preg_match("/(fopen|fwrite|unlink|file_get_contents|permission denied|No such file)/i", $error_description)) {
                    $error_types_count["Filesystem"]++;
                }

                // HTTP/API error detection
                if (preg_match("/(curl|cURL error|HTTP error|timed out|Connection timed out|SSL)/i", $error_description)) {
                    $error_types_count["HTTP_API"]++;
                }
            }

            $total_lines_processed++;
        }
        fclose($file);
    }

    return $error_types_count;
}

// Print error summary table
function wptools_print_error_summary($error_types_count)
{
    echo '<div style="border: 1px solid #ccc; background-color: #ffffff; padding: 20px; margin-top: 20px; border-radius: 5px;">';
    echo '<h3 style="color: #0073aa;">' .
        esc_attr__("Partial Error Summary - Selected Log File", "wptools") .
        "</h3>";

    echo '<p>' . esc_attr__("This summary shows error types found in the selected log file with their occurrence count.", "wptools") . '</p>';

    echo '<table style="width: 100%; border-collapse: collapse; margin-top: 15px;">';
    echo '<tr style="background-color: #f8f9fa;">';
    echo '<th style="border: 1px solid #ddd; padding: 12px; text-align: left; font-weight: bold;">' .
        esc_attr__("Error Type", "wptools") .
        "</th>";
    echo '<th style="border: 1px solid #ddd; padding: 12px; text-align: center; font-weight: bold;">' .
        esc_attr__("Count", "wptools") .
        "</th>";
    echo "</tr>";

    $total_errors = 0;
    $has_errors = false;

    foreach ($error_types_count as $type => $count) {
        // Skip if count is 0
        if ($count === 0) {
            continue;
        }
        $has_errors = true;
        $total_errors += $count;
        echo "<tr>";
        echo '<td style="border: 1px solid #ddd; padding: 10px;">' .
            esc_html($type) .
            "</td>";
        echo '<td style="border: 1px solid #ddd; padding: 10px; text-align: center; font-weight: bold;">' .
            esc_html($count) .
            "</td>";
        echo "</tr>";
    }

    if (!$has_errors) {
        echo '<tr>';
        echo '<td colspan="2" style="border: 1px solid #ddd; padding: 20px; text-align: center; color: #666;">';
        echo esc_attr__('No errors found in the selected log file.', 'wptools');
        echo '</td>';
        echo '</tr>';
    } else {
        // Total row
        //echo '<tr style="background-color: #e9ecef; font-weight: bold;">';
        //echo '<td style="border: 1px solid #ddd; padding: 12px;">' . esc_attr__("Total Errors", "wptools") . '</td>';
        //echo '<td style="border: 1px solid #ddd; padding: 12px; text-align: center;">' . esc_html($total_errors) . '</td>';
        //echo "</tr>";
    }

    echo "</table>";
    echo "</div>";
}







// Get all log file paths (replace with your existing log discovery function)
function wptools_get_log_paths()
{
    // Use your existing function from the first script
    $logs = wptools_find_logs();
    $log_paths = [];

    foreach ($logs as $log) {
        if (isset($log['path']) && file_exists($log['path'])) {
            $log_paths[] = $log['path'];
        }
    }

    return $log_paths;
}

// ... resto do código ...

function wptools_chat()
{

?>





    <!-- chat -->
    <div id="chat-box" style="margin-top: -10px !important; max-height: 600px !important;">
        <div id="chat-header" style="padding: 10px !important;">
            <h2><?php echo esc_attr__("Artificial Intelligence Support Chat for Issues and Solutions", "wptools"); ?></h2>
        </div>
        <div id="gif-container">
            <div class="spinner999"></div>
        </div> <!-- Onde o efeito será exibido -->
        <div id="chat-messages" style="max-height: 380px !important;></div>
        <div id=" error-message" style="display:none;"></div> <!-- Mensagem de erro -->



        <form id="chat-form">
            <div id="input-group">
                <input type="text" id="chat-input" placeholder="<?php echo esc_attr__('Enter your message...', "wp-memory"); ?>" />
                <button type="submit"><?php echo esc_attr__('Send', "wp-memory"); ?></button>
            </div>
            <div id="action-instruction" style="text-align: center; margin-top: 10px;">
                <span><?php echo esc_attr__("Enter a message and click 'Send', or just click 'Auto Checkup' to analyze error log ou server info configuration.", "wp-memory"); ?></span>
            </div>
            <div class="auto-checkup-container" style="text-align: center; margin-top: 10px;">

                <button type="button" id="auto-checkup">
                    <img src="<?php echo plugin_dir_url(__FILE__) . 'robot2.png'; ?>" alt="" width="35" height="30">
                    <?php echo esc_attr__('Auto Checkup for Errors', "wp-memory"); ?>
                </button>
                &nbsp;&nbsp;&nbsp;
                <button type="button" id="auto-checkup2">
                    <img src="<?php echo plugin_dir_url(__FILE__) . 'robot2.png'; ?>" alt="" width="35" height="30">
                    <?php echo esc_attr__('Auto Checkup Server ', "wp-memory"); ?>
                </button>


            </div>
        </form>















    </div>
    <!-- end chat -->

<?php
}




























// =================================================================










function wptools_show_error_table()
{
    $default_file = ABSPATH . 'error_log';
    $file_path = get_option('wptools_log_file_name_option', $default_file);
?>
    <h1 style="color: gray; text-align: center;"><?php esc_attr_e("Error Log Table", 'wptools'); ?></h1>
    <?php
    if (file_exists($file_path)) {
        $file_size = filesize($file_path);
        $file_mtime = filemtime($file_path);
        $file_date = date('Y-m-d H:i:s', $file_mtime);

        echo '<div style="background: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 5px; border-left: 4px solid #0073aa;">';
        echo '<div style="font-family: Arial, sans-serif; font-size: 14px; text-align: center; line-height: 1.6;">';
        echo '<span style="margin-right: 25px;"><strong>' . esc_attr__('Log File:', 'wptools') . '</strong> ' . esc_html(basename($file_path)) . '</span>';
        echo '<span style="margin-right: 25px;"><strong>' . esc_attr__('Location:', 'wptools') . '</strong> ' . esc_html(dirname($file_path)) . '</span>';
        echo '<span style="margin-right: 25px;"><strong>' . esc_attr__('Size:', 'wptools') . '</strong> ' . size_format($file_size, 2) . '</span>';
        echo '<span><strong>' . esc_attr__('Last Modified:', 'wptools') . '</strong> ' . esc_html($file_date) . '</span>';
        echo '</div>';
        echo '</div>';
    } else {
        echo '<div style="background: #f8d7da; padding: 12px; margin: 15px 0; border-radius: 5px; border-left: 4px solid #dc3545;">';
        echo '<div style="color: #dc3545; font-weight: bold; text-align: center;">';
        echo esc_attr__('Log file not found:', 'wptools') . ' ' . esc_html($file_path);
        echo '</div>';
        echo '</div>';
    }
    ?>
    <!-- Indicador de carregamento -->
    <div id="wptools-loadingIndicator">
        <div class="wptools-loadingIndicator"></div>
        <div class="wptools-loadingIndicator"></div>
        <div class="wptools-loadingIndicator"></div>
    </div>
    <!-- Filtro por tipo -->
    <div class="filter-options">
        <label for="type-filter"><?php esc_attr_e("Filter by Type", 'wptools'); ?>:</label>
        <select id="type-filter">
            <option value="all">All</option>
        </select>
    </div>
    <!-- Tabela de logs -->
    <table id="wptools-error-log-table" class="display">
        <thead>
            <tr>
                <th><?php esc_attr_e("Date", 'wptools'); ?></th>
                <th><?php esc_attr_e("Type", 'wptools'); ?></th>
                <th><?php esc_attr_e("Description", 'wptools'); ?></th>
                <th><?php esc_attr_e("Action", 'wptools'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php echo wptools_get_error_log_data(); ?>
        </tbody>
    </table>
    <div id="error-detail-modal" style="display: none;">
        <div class="modal-content">
            <!-- Tab Headers -->
            <div id="tab-header" style="display: flex; border-bottom: 2px solid #ccc;">
                <input type="radio" id="tab-details" name="tabs" checked style="display: none;">
                <label for="tab-details" style="flex: 1; text-align: center; padding: 10px; cursor: pointer; font-weight: bold; color: #333; border-bottom: 2px solid #0073aa;">Details</label>
                <input type="radio" id="tab-analysis" name="tabs" style="display: none;">
                <label for="tab-analysis" style="flex: 1; text-align: center; padding: 10px; cursor: pointer; font-weight: bold; color: #333; border-bottom: 2px solid transparent;">AI Analysis</label>
            </div>
            <!-- Tab Content -->
            <div id="tab-content" style="padding: 20px;">
                <!-- Details Tab Content -->
                <div id="details-content">
                    <table id="error-detail-table">
                        <tbody></tbody>
                    </table>
                </div>
                <!-- AI Analysis Tab Content -->
                <div id="analysis-content" style="display: none;">
                    <!-- chat -->
                    <div id="chat-box" style="margin-top: -10px !important; max-height: 600px !important;">
                        <div id="chat-header" style="padding: 10px !important;">
                            <h2><?php echo esc_attr__("Artificial Intelligence Support Chat for Issues and Solutions", "wptools"); ?></h2>
                        </div>
                        <div id="gif-container">
                            <div class="spinner999"></div>
                        </div> <!-- Onde o efeito será exibido -->
                        <div id="chat-messages" style="max-height: 380px !important;></div>
                        <div id=" error-message" style="display:none;"></div> <!-- Mensagem de erro -->
                        <form id="chat-form">
                            <div id="input-group">
                                <input type="text" id="chat-input" placeholder="<?php echo esc_attr__('Enter your message...', 'wptools'); ?>" />
                                <button type="submit" id="wptools"><?php echo esc_attr__('Send', 'wptools'); ?></button>
                            </div>
                            <div id="action-instruction" style="text-align: center; margin-top: 10px;">
                                <span><?php echo esc_attr__("Enter a message and click 'Send', or just copy and paste the content of type and description column.", 'wptools'); ?></span>
                            </div>
                        </form>
                    </div>
                    <!-- end chat -->
                </div>
            </div>
            <!-- Modal Footer -->
            <div class="modal-footer">
                <button id="open-ai-analysis">AI Analysis</button>
                <button id="close-modal">Close</button>
            </div>
        </div>
        <!-- </div>
    </div> -->
    <?php
}

function wptools_get_error_log_data()
{
    $default =    $file_path = ABSPATH . 'error_log';
    $file_path = get_option('wptools_log_file_name_option', $default);
    $output = '';

    try {
        if (!file_exists($file_path)) {
            $file_path_error_log = ABSPATH . 'error_log';
            $file_path_debug_log = WP_CONTENT_DIR . 'debug.log';

            if (file_exists($file_path_error_log) || file_exists($file_path_debug_log)) {
                if (file_exists($file_path_error_log)) {
                    update_option('wptools_log_file_name_option', $file_path_error_log);
                } else {
                    update_option('wptools_log_file_name_option', $file_path_debug_log);
                }
            } else {
                return '<tr><td colspan="4">' . esc_attr("Error log file not found! Click Setup Button at top right corner.", "wptools") . '</td></tr>';
            }
        }
    } catch (Exception $e) {
        echo '<tr><td colspan="4">Error to open error log file.';
        echo '  ' . $e->getMessage();
        echo '</td></tr>';
        return;
    }
    try {
        $file = fopen($file_path, 'r');
        if ($file === false) {
            return '<tr><td colspan="4">Error log file not readable!</td></tr>';
        }
    } catch (Exception $e) {
        echo '<tr><td colspan="4">Error to open error log file.';
        echo '  ' . $e->getMessage();
        echo '</td></tr>';
        return;
    }

    $lines = [];
    $numLines = 3000;
    if (class_exists('SplFileObject')) {
        try {
            $fileObj = new SplFileObject($file_path, 'r');
            $fileObj->seek(PHP_INT_MAX);
            $totalLines = $fileObj->key();
            $startLine = max(0, $totalLines - $numLines);
            $fileObj->seek($startLine);
            $lines = [];
            while (!$fileObj->eof()) {
                $line = $fileObj->fgets();
                if ($line !== false) {
                    $lines[] = rtrim($line);
                }
            }
        } catch (Exception $e) {
            echo '<tr><td colspan="4">Error to process error log file.';
            echo '  ' . $e->getMessage();
            echo '</td></tr>';
            return;
        }
    } else {
        $ctd = 0;
        $lines = [];
        try {
            $transient_key = 'log_file_total_lines';
            $totalLines = get_transient($transient_key);
            if ($totalLines === false) {
                $totalLines = 0;
                $file = fopen($file_path, 'r');
                if ($file === false) {
                    return '<tr><td colspan="4">Error to open log file!</td></tr>';
                }
                while (fgets($file) !== false) {
                    $totalLines++;
                }
                fclose($file);
                set_transient($transient_key, $totalLines, 15 * MINUTE_IN_SECONDS);
            }
            if ($totalLines === 0) {
                return '<tr><td colspan="4">The log file is empty!</td></tr>';
            }
            $lines = [];
            $file = fopen($file_path, 'r');
            if ($file === false) {
                return '<tr><td colspan="4">Error to open log file!</td></tr>';
            }
            $startLine = max(0, $totalLines - $numLines);
            $currentLine = 0;
            while (($line = fgets($file)) !== false) {
                if ($currentLine >= $startLine) {
                    $lines[] = $line;
                }
                $currentLine++;
            }
            fclose($file);
        } catch (Exception $e) {
            echo '<tr><td colspan="4">Error to process error log file.';
            echo '  ' . $e->getMessage();
            echo '</td></tr>';
            return;
        }
    }

    if (empty($lines)) {
        return '<tr><td colspan="4">No errors found in the log file.</td></tr>';
    }

    $ctd_debug = 0;
    foreach ($lines as $line) {
        if (empty(trim($line))) continue;

        $line_orig = $line;
        $found = false;

        $pattern = "/Stack trace:/";
        if (preg_match($pattern, $line)) continue;
        if (substr($line, 0, 1) === '#') continue;

        /* ---------- data  -------------------------- */

        /* normalize line: remove BOM e controles invisíveis e normaliza unicode */
        $line = str_replace("\xEF\xBB\xBF", '', $line); // remove UTF-8 BOM se presente
        // remove controles ASCII (0x00-0x1F) mas mantém tab/newline removidos por trim abaixo
        $line = preg_replace('/[\x00-\x1F]+/u', ' ', $line);
        $line = trim($line);

        /* padrões (use flag u para Unicode) */
        $datePatterns = [
            '/\[\s*\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s*\]/u',                                   // [2025-11-06 10:14:11]
            '/\[\s*\d{2}-[A-Za-z]{3}-\d{4}\s+\d{2}:\d{2}:\d{2}(?:\s*\w+)?\s*\]/u',                 // [06-Nov-2025 10:47:01 UTC]
            '/\[\s*[A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+\d{2}:\d{2}:\d{2}(?:\.\d+)?\s+\d{4}\s*\]/u', // Apache: [Thu Nov 06 10:47:01.123456 2025]
            '/\[\s*\d{2}\/\d{2}\/\d{4}\s+\d{2}:\d{2}:\d{2}\s*\]/u',                                  // [06/11/2025 10:47:01]
            '/\[\s*\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\s*\]/u',                                  // [2025/11/06 10:47:01]
            '/\[\s*\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+\-]\d{2}:?\d{2})?\s*\]/u',   // ISO-like
            // catch words months fully written
            '/\[\s*\d{2}-[A-Za-z]+\-\d{4}\s+\d{2}:\d{2}:\d{2}(?:\s*\w+)?\s*\]/u',
        ];

        $filteredDate = false;

        if ($ctd_debug < 5) {
            // debug4("--- DEBUG DA LINHA " . ($ctd_debug + 1) . " ---");
            // debug4("Linha (normalized): " . $line);
        }

        foreach ($datePatterns as $p) {
            if (preg_match($p, $line, $m)) {
                $filteredDate = $m[0];
                if ($ctd_debug < 5) {
                    // debug4("Padrão de Data Usado: " . $p);
                    // debug4("REGEX MATCHED! Data Filtrada: " . $filteredDate);
                }
                break;
            }
        }

        /* Se nenhum padrão casar, tenta catch-all entre colchetes (mais permissivo) */
        if (!$filteredDate) {
            if (preg_match('/\[[^\]]{8,80}\]/u', $line, $m2)) { // pega qualquer bloco entre [] com tamanho razoável
                $filteredDate = $m2[0];
                if ($ctd_debug < 5) {
                    // debug4("Fallback catch-all usado. Data Filtrada: " . $filteredDate);
                }
            }
        }

        /* DEBUG extra: se a linha contém ano-começo '[YYYY-' e ainda NÃO casou, mostramos hexdump curto */
        if (!$filteredDate && preg_match('/\[\s*20\d{2}-\d{2}-\d{2}/', $line)) {
            // hexdump curto: imprime bytes hex dos primeiros 64 chars para detectar BOM/bytes estranhos
            $short = substr($line, 0, 64);
            $hex = implode(' ', array_map(function ($c) {
                return sprintf("%02X", ord($c));
            }, str_split($short)));
            // debug4("LINE CONTAINS [YYYY- BUT NO MATCH. short: " . $short);
            // debug4("HEXDUMP (first 64 chars): " . $hex);
        }

        if ($ctd_debug < 5) {
            // debug4("Valor final de \$filteredDate: " . ($filteredDate ? $filteredDate : "FALSE/NULL"));
            // debug4("--- FIM DEBUG DA LINHA " . ($ctd_debug + 1) . " ---");
        }

        /* ---------- fim data  -------------------------- */

        /* ---------- data  -------------------------- */
        // ----------------- Robust date removal (accept any $filteredDate) -----------------
        if ($filteredDate) {
            // debug opcional: mostra quando a data começa por ano (YYYY-)
            if ($ctd_debug < 5) {
                if (preg_match('/\[\s*20\d{2}-\d{2}-\d{2}/', $filteredDate)) {
                    // debug4("Nota: filteredDate é ano-primeiro (YYYY-): " . $filteredDate);
                } else {
                    // debug4("filteredDate não é ano-primeiro: " . $filteredDate);
                }
            }

            // Remove o bloco da data (primeira ocorrência) de forma segura e tolerante
            $quoted = preg_quote($filteredDate, '/');

            // Padrão: remove o bloco da data e quaisquer espaços, ' - ', ':' ou travessões que venham logo em seguida.
            // Limita a 1 substituição (apenas o primeiro encontro).
            $line = preg_replace('/' . $quoted . '\s*(?:[-–—:]\s*)?/', '', $line, 1);

            // Ainda remova se houver apenas um colchete fechado seguido por espaços/hífen (caso o $filteredDate não inclua ']' exatamente)
            $line = preg_replace('/^\s*\]\s*(?:[-–—:]\s*)?/', '', $line, 1);

            // Trim final pra limpar espaços remanescentes
            $line = trim($line);
        } else {
            if ($ctd_debug < 5) {
                // debug4("Skip: filteredDate FALSE. Linha original: " . $line_orig);
            }
            continue;
        }
        // ----------------------------------------------------------------------------------


        $filteredDate =  wptools_transformarData($filteredDate);

        $apattern = [];
        $line = wptools_removeAccents($line);
        $apattern[] = "/^(?:PHP\s+)?(.*?\b\w+\b)(.*)$/";
        $log_entry = array();

        for ($j = 0; $j < count($apattern); $j++) {
            if (preg_match($apattern[$j], $line, $matches)) {
                $pattern = $apattern[$j];
                $found = true;
                $type = replaceIfOnlyNumbers($matches[1]);
                $type = replaceMonthsWithOther($type);
                $description = removeNonAlphanumericStart($matches[2]);

                if (preg_match('/^PHP\s+\d+\./', $line)) {
                    $log_entry = false;
                    break;
                }
                if (empty($description) or empty($type) or empty($filteredDate)) {
                    $log_entry = false;
                    break;
                }

                $log_entry = [
                    "Date" => $filteredDate,
                    "Type" => $type,
                    "Description" => wptools_strip_strong($description),
                ];
                break;
            }
        }

        $ctd_debug++;

        if (!$log_entry)
            continue;

        if ($found) {
            $data = $log_entry["Date"];
            $type = limparString($log_entry["Type"]);
            $type = replaceIfOnlyNumbers($type);
            $description  = $log_entry["Description"];

            $output .= "<tr>\n";
            $output .= "<td>{$data}</td>\n";
            $type = preg_replace("/[^a-zA-Z0-9\s]/", "", $type);
            $output .= "<td>{$type}</td>\n";
            $output .= "<td>{$description}</td>\n";
            $output .= "<td><button class='view-details'>" . esc_attr__('View', 'wptools') . "</button></td>\n";
            $output .= "</tr>\n";
        } else {
            $output .= "<tr>\n";
            $output .= "<td>N/A</td>\n";
            $output .= "<td>Unknown</td>\n";
            $output .= "<td>" . htmlspecialchars($line) . "</td>\n";
            $output .= "<td><button class='view-details'>View22222</button></td>\n";
            $output .= "</tr>\n";
        }
    }
    return $output;
}


function wptools_get_error_log_data_boa()
{
    $default =    $file_path = ABSPATH . 'error_log';
    $file_path = get_option('wptools_log_file_name_option', $default);
    $output = '';




    try {
        // Verifica se o arquivo existe
        if (!file_exists($file_path)) {


            $file_path_error_log = ABSPATH . 'error_log';
            $file_path_debug_log = WP_CONTENT_DIR . 'debug.log';

            // Verifica se algum dos arquivos existe
            if (file_exists($file_path_error_log) || file_exists($file_path_debug_log)) {
                // Se pelo menos um arquivo existir, deixa o fluxo seguir adiante
                // Não retorna nada, apenas continua o processamento


                if (file_exists($file_path_error_log)) {

                    update_option('wptools_log_file_name_option', $file_path_error_log);
                } else {
                    update_option('wptools_log_file_name_option', $file_path_debug_log);
                }
            } else {
                // Se nenhum dos arquivos existir, retorna a mensagem de erro
                return '<tr><td colspan="4">' . esc_attr("Error log file not found! Click Setup Button at top right corner.", "wptools") . '</td></tr>';
            }
        }
    } catch (Exception $e) {
        echo '<tr><td colspan="4">Error to open error log file.';
        echo '  ' . $e->getMessage();
        echo '</td></tr>';
        return;
    }
    try {
        // Abre o arquivo em modo de leitura
        $file = fopen($file_path, 'r');
        if ($file === false) {
            return '<tr><td colspan="4">Error log file not readable!</td></tr>';
        }
    } catch (Exception $e) {
        echo '<tr><td colspan="4">Error to open error log file.';
        echo '  ' . $e->getMessage();
        echo '</td></tr>';
        return;
    }
    // Se chegou até aqui, o arquivo foi aberto com sucesso
    // Continue com o processamento do arquivo...
    // Inicializar o array para armazenar as linhas
    $lines = [];
    $numLines = 3000; // Número de linhas que você quer ler
    if (class_exists('SplFileObject')) {
        try {
            // Abre o arquivo com SplFileObject
            $fileObj = new SplFileObject($file_path, 'r');

            /*
            // Lê as primeiras $numLines linhas
            $ctd = 0;
            while (!$fileObj->eof() && $ctd < $numLines) {
                $line = $fileObj->current(); // Lê a linha atual
                if ($line !== false) {
                    $lines[] = $line; // Adiciona a linha ao array
                    $ctd++; // Incrementa o contador
                }
                $fileObj->next(); // Avança o ponteiro para a próxima linha
            }
            */

            $fileObj->seek(PHP_INT_MAX); // Move para o final do arquivo
            $totalLines = $fileObj->key(); // Obtém total de linhas

            // Calcula linha inicial
            $startLine = max(0, $totalLines - $numLines);

            // Reinicia ponteiro para linha inicial
            $fileObj->seek($startLine);

            // Limpa array de linhas
            $lines = [];

            // Lê linhas até o final
            while (!$fileObj->eof()) {
                $line = $fileObj->fgets();
                if ($line !== false) {
                    $lines[] = rtrim($line);
                }
            }
        } catch (Exception $e) {
            // echo "Erro ao processar o arquivo: " . $e->getMessage();
            echo '<tr><td colspan="4">Error to process error log file.';
            echo '  ' . $e->getMessage();
            echo '</td></tr>';
            return;
        }
    } else {
        // Ler o restante das linhas e armazená-las no array
        $ctd = 0;
        //$file_path = 'caminho/para/seu/arquivo.log'; // Substitua pelo caminho do seu arquivo
        $ctd = 0;
        $lines = [];
        try {
            //$numLines = 3000;
            // $file_path = '/path/to/your/logfile.log'; // Atualize o caminho para o arquivo
            $transient_key = 'log_file_total_lines';
            // Verifica se o número de linhas está armazenado no transiente
            $totalLines = get_transient($transient_key);
            if ($totalLines === false) {
                // Conta o número total de linhas do arquivo
                $totalLines = 0;
                $file = fopen($file_path, 'r');
                if ($file === false) {
                    return '<tr><td colspan="4">Error to open log file!</td></tr>';
                }
                while (fgets($file) !== false) {
                    $totalLines++;
                }
                fclose($file);
                // Grava o total de linhas no transiente por 15 minutos
                set_transient($transient_key, $totalLines, 15 * MINUTE_IN_SECONDS);
            }
            // Verifica se o arquivo está vazio
            if ($totalLines === 0) {
                return '<tr><td colspan="4">The log file is empty!</td></tr>';
            }
            // Lê as últimas $numLines linhas
            $lines = [];
            $file = fopen($file_path, 'r');
            if ($file === false) {
                return '<tr><td colspan="4">Error to open log file!</td></tr>';
            }
            // Determina o ponto de início para ler as últimas linhas
            $startLine = max(0, $totalLines - $numLines);
            $currentLine = 0;
            while (($line = fgets($file)) !== false) {
                if ($currentLine >= $startLine) {
                    $lines[] = $line;
                }
                $currentLine++;
            }
            // Fecha o arquivo
            fclose($file);
            // Agora, $lines contém as últimas linhas do arquivo
            // Você pode processar ou exibir essas linhas conforme necessário
        } catch (Exception $e) {
            echo '<tr><td colspan="4">Error to process error log file.';
            echo '  ' . $e->getMessage();
            echo '</td></tr>';
            return;
        }
    }
    // Se o arquivo estiver vazio após o corte inicial
    if (empty($lines)) {
        return '<tr><td colspan="4">No errors found in the log file.</td></tr>';
    }
    $ctd = 0;
    //debug20($log_entry);
    foreach ($lines as $line) {
        $line_orig = $line;
        $found = false; // Rastrea se algum padrão correspondeu
        if (empty(trim($line)))
            continue;
        /*
        if (trim($line) == '-------------------------===-----------------------------------') {
            continue; // Pular para a próxima linha
        }
        if (trim($line) == '------------------------------------------------------------') {
            continue; // Pular para a próxima linha
        }
        if (strpos($line, 'Undefined variable $xx') !== false) {
            //  continue; // Pular para a próxima linha
        }
        if (strpos($line, 'Automatic plugin updates complete') !== false) {
            continue; // Pular para a próxima linha
        }
        if (strpos($line, 'Automatic updates complete') !== false) {
            continue; // Pular para a próxima linha
        }
        if (strpos($line, 'Automatic ') !== false) {
            continue; // Pular para a próxima linha
        }
        if (strpos($line, 'Não') !== false) {
            continue; // Pular para a próxima linha
        }
        if (strpos($line, 'abeç') !== false) {
            continue; // Pular para a próxima linha
        }
        */
        // ---------------------------
        //$pattern = "/PHP Stack trace:/";
        $pattern = "/Stack trace:/";
        if (preg_match($pattern, $line, $matches)) {
            continue;
        }
        if (substr($line, 0, 1) === '#') {
            // Stack trace
            continue; // Pular para a próxima linha
        }
        $pattern =
            "/\d{4}-\w{3}-\d{4} \d{2}:\d{2}:\d{2} UTC\] PHP \d+\./";
        if (preg_match($pattern, $line, $matches)) {
            // continue;
        }
        /* ---------- data  -------------------------- */

        /*

        $datePattern = '/\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}/'; // sem colchetes...
        $datePattern = '/\[\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}.*?\]/';
        $filteredDate = false;
        if (preg_match($datePattern, $line, $matches2)) {
            $filteredDate = $matches2[0]; // Data capturada pela regex, incluindo colchetes
        } else {


            $filteredDate = $line;
            if (is_string($line) && strpos($line, '[') !== false && strpos($line, ']') !== false) {
                $start = strpos($line, '[');
                $end = strpos($line, ']');
                // Continue seu processamento aqui

                if ($start !== false && $end !== false) {
                    $filteredDate = substr($line, $start, $end - $start + 1); // Extrai a data com colchetes
                } else {
                    // $filteredDate = false; // Nenhuma data encontrada
                }
            } else {
                // Trate a situação onde $line é inválido ou não contém os caracteres esperados
                //error_log("Invalid line or missing '[' or ']' in the string: " . var_export($line, true));
            }



            //$start = strpos($line, '[');
            // $end = strpos($line, ']');




        }
*/


        //echo "Linha sem a data: $lineWithoutDate\n";
        /* ---------- data  -------------------------- */



        /* ---------- data  -------------------------- */
        // Nov 2025
        // Ajuste a regex para incluir o novo formato [YYYY-MM-DD HH:MM:SS]
        $datePattern = '/\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]|\[\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}.*?\]/';
        $filteredDate = false;

        if (preg_match($datePattern, $line, $matches2)) {
            $filteredDate = $matches2[0]; // Data capturada pela regex, incluindo colchetes
        } else {
            // Este bloco else trata de casos onde a data pode não estar entre colchetes
            // ou segue um padrão diferente.
            // Para o novo padrão [YYYY-MM-DD HH:MM:SS], ele já será capturado pela regex principal.
            // Para o padrão [05-Nov-2025 14:56:58 UTC], ele também será capturado.
            // Se houver outros formatos sem colchetes ou com formato diferente que você precise suportar,
            // você precisará adicionar mais padrões à $datePattern ou adicionar mais lógica aqui.

            // Removi a lógica redundante que tentava encontrar colchetes manualmente
            // após a falha da regex principal, pois a regex já deve ser abrangente.
            // Se um novo padrão de data não estiver entre colchetes, ele precisará de sua própria regex ou tratamento.

            // Por enquanto, vamos manter a lógica simplificada, confiando na regex principal.
            $filteredDate = $line; // Assume a linha inteira se a regex falhar, mas isso pode não ser o ideal dependendo do contexto.
            if (is_string($line) && strpos($line, '[') !== false && strpos($line, ']') !== false) {
                $start = strpos($line, '[');
                $end = strpos($line, ']');
                if ($start !== false && $end !== false) {
                    $filteredDate = substr($line, $start, $end - $start + 1);
                } else {
                    // $filteredDate = false; // Nenhuma data encontrada
                }
            } else {
                // error_log("Invalid line or missing '[' or ']' in the string: " . var_export($line, true));
            }
        }
        //echo "Linha sem a data: $lineWithoutDate\n";
        /* ---------- data  -------------------------- */


        // Aceita formatos dia-primeiro (DD-...) OU ano-primeiro (YYYY-MM-DD)
        // Mantém compatibilidade com wptools_has_two_digit_day se você quiser conservar essa lógica.
        $has_two_digit_day = function ($d) {
            // mantém comportamento existente se for dia-primeiro
            if (function_exists('wptools_has_two_digit_day') && wptools_has_two_digit_day($d)) {
                return true;
            }
            // aceita também formato [YYYY-MM-DD ...]
            if (preg_match('/\[\s*\d{4}-\d{2}-\d{2}/', $d)) {
                return true;
            }
            return false;
        };

        if ($filteredDate && $has_two_digit_day($filteredDate)) {
            // remove a data do começo/texto com mais tolerância a espaços e separadores
            $quoted = preg_quote($filteredDate, '/');
            // Remove o bloco da data e eventuais espaços e separadores imediatamente depois: " ] - " ou "] " etc.
            $line = preg_replace('/' . $quoted . '\s*[-–—:]?\s*/', '', $line, 1);
        } else {
            if ($ctd_debug < 5) {
                // debug4("Skip: filteredDate FALSE ou não reconhece dia/ano. Linha: " . $line_orig);
            }
            continue;
        }



        $filteredDate =  wptools_transformarData($filteredDate);




        $apattern = [];
        $apattern = []; // Inicializando o array vazio
        $line = wptools_removeAccents($line);
        // deepok 
        $apattern[] = "/^(?:PHP\s+)?(.*?\b\w+\b)(.*)$/";
        $log_entry = array();
        for ($j = 0; $j < count($apattern); $j++) {
            if (
                preg_match($apattern[$j], $line, $matches)
            ) {
                $pattern = $apattern[$j];
                $found = true; // Rastrea se algum padrão correspondeu
                $type = replaceIfOnlyNumbers($matches[1]);
                $type = replaceMonthsWithOther($type);
                $description = removeNonAlphanumericStart($matches[2]);
                // trace
                if (preg_match('/^PHP\s+\d+\./', $line)) {
                    $log_entry = false;
                    break;
                }
                if (empty($description) or empty($type) or empty($filteredDate)) {
                    $log_entry = false;
                    break;
                    // continue;
                }
                //  // // debug4();
                $log_entry = [
                    "Date" => $filteredDate,
                    "Type" => $type,
                    "Description" => wptools_strip_strong(
                        $description
                    ),
                ];
                break;
            }
        }
        $ctd++;
        if (!$log_entry)
            continue;
        if ($found) {
            $data = $log_entry["Date"];
            $type = $log_entry["Type"];
            $type = limparString($type);
            $type = replaceIfOnlyNumbers($type);
            $description  = $log_entry["Description"];
            //$description = htmlspecialchars($log_entry["Description"] ?? 'Unknown');
            //$url = htmlspecialchars($matches[4] ?? 'Unknown');
            // $line_number = htmlspecialchars($matches[5] ?? 'Unknown');
            // Adicionar a linha correspondente ao output
            $output .= "<tr>\n";
            $output .= "<td>{$data}</td>\n";
            //$type = str_replace(["[", "]"], "", $type);
            // $type = str_replace(["<", ">"], "", $type);
            $type = preg_replace("/[^a-zA-Z0-9\s]/", "", $type);
            $output .= "<td>{$type}</td>\n";
            //$description = htmlentities($description, ENT_QUOTES, 'UTF-8');
            $output .= "<td>{$description}</td>\n";
            $output .= "<td><button class='view-details'>" . esc_attr__('View', 'wptools') . "</button></td>\n";
            $output .= "</tr>\n";
        } else {
            // // debug4($line);
            // // debug4($line_orig);
            // debug3("Nenhuma correspondência para a linha: {$line}");
            $output .= "<tr>\n";
            $output .= "<td>N/A</td>\n";
            $output .= "<td>Unknown</td>\n";
            $output .= "<td>" . htmlspecialchars($line) . "</td>\n";
            $output .= "<td><button class='view-details'>View22222</button></td>\n";
            $output .= "</tr>\n";
        }
    }
    return $output;
}
function wptools_has_two_digit_day($line)
{
    // Padrão para verificar se há dois algarismos consecutivos para o dia
    $datePattern = '/\[(\d{2})-/';
    // Verifica se o padrão corresponde à data
    if (preg_match($datePattern, $line, $matches)) {
        // O dia é capturado em $matches[1]
        return true; // A data tem 2 algarismos para o dia
    }
    // Se não encontrar o padrão
    return false;
}
// Função para remover acentos de várias línguas
function wptools_removeAccents($string)
{
    // Mapa de caracteres com acentos para equivalentes sem acentos
    $unwantedChars = [
        // Letras maiúsculas
        'Á' => 'A',
        'À' => 'A',
        'Â' => 'A',
        'Ã' => 'A',
        'Ä' => 'A',
        'Å' => 'A',
        'Æ' => 'AE',
        'Ç' => 'C',
        'É' => 'E',
        'È' => 'E',
        'Ê' => 'E',
        'Ë' => 'E',
        'Í' => 'I',
        'Ì' => 'I',
        'Î' => 'I',
        'Ï' => 'I',
        'Ñ' => 'N',
        'Ó' => 'O',
        'Ò' => 'O',
        'Ô' => 'O',
        'Õ' => 'O',
        'Ö' => 'O',
        'Ø' => 'O',
        'Ú' => 'U',
        'Ù' => 'U',
        'Û' => 'U',
        'Ü' => 'U',
        'Ý' => 'Y',
        'Þ' => 'TH',
        'ß' => 'ss',
        'Ð' => 'D',
        'Š' => 'S',
        'Ž' => 'Z',
        // Letras minúsculas
        'á' => 'a',
        'à' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'å' => 'a',
        'æ' => 'ae',
        'ç' => 'c',
        'é' => 'e',
        'è' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'í' => 'i',
        'ì' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'ñ' => 'n',
        'ó' => 'o',
        'ò' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ø' => 'o',
        'ú' => 'u',
        'ù' => 'u',
        'û' => 'u',
        'ü' => 'u',
        'ý' => 'y',
        'þ' => 'th',
        'ÿ' => 'y',
        'đ' => 'd',
        'š' => 's',
        'ž' => 'z',
        // Outros caracteres especiais
        'Œ' => 'OE',
        'œ' => 'oe',
        'Ŕ' => 'R',
        'ŕ' => 'r',
    ];
    // Substitui os caracteres usando o mapa
    return strtr($string, $unwantedChars);
}
function wptools_transformarData($data)
{
    // Remove colchetes, se existirem
    $data = trim($data, "[]");
    // Lista de formatos possíveis
    $formatos = [
        'd-M-Y H:i:s e',  // Exemplo: 30-May-2024 03:13:57 UTC
        'd-M-Y H:i:s',    // Exemplo: 30-May-2024 03:13:57
        'Y-m-d H:i:s',    // Exemplo: 2024-05-30 03:13:57
        'd/m/Y H:i:s',    // Exemplo: 30/05/2024 03:13:57
        'm/d/Y H:i:s',    // Exemplo: 05/30/2024 03:13:57
        'd-M-Y',          // Exemplo: 30-May-2024
        'Y-m-d',          // Exemplo: 2024-05-30
        'd/m/Y',          // Exemplo: 30/05/2024
        'm/d/Y',          // Exemplo: 05/30/2024
        'd.m.Y H:i:s',    // Exemplo: 30.05.2024 03:13:57
        'd.m.Y',          // Exemplo: 30.05.2024
        'Y.m.d',          // Exemplo: 2024.05.30
        'd M Y H:i:s',    // Exemplo: 30 May 2024 03:13:57
        'd M Y',          // Exemplo: 30 May 2024
        'M d, Y H:i:s',   // Exemplo: May 30, 2024 03:13:57
        'M d, Y',         // Exemplo: May 30, 2024
        'D, d M Y H:i:s', // Exemplo: Thu, 30 May 2024 03:13:57
        'D, d M Y',       // Exemplo: Thu, 30 May 2024
    ];
    // Tenta cada formato
    foreach ($formatos as $formato) {
        $dateTime = DateTime::createFromFormat($formato, $data);
        if ($dateTime !== false) {
            // Retorna a data no formato 'YYYY-MM-DD'
            // return $dateTime->format('Y-m-d');
            return $dateTime->format('Y-m-d H:i:s');
        }
    }
    // Se nenhum formato for válido, retorna a string original
    return $data;
}
function replaceIfOnlyNumbers($script)
{
    // Remove espaços em branco no início e fim
    $script = trim($script);
    // Verifica se o conteúdo contém apenas números
    if (preg_match('/^\d+$/', $script)) {
        $script = "Other";
    }
    return $script;
}
function limparString($string)
{
    // Remove todos os caracteres que não são letras ou números
    $stringLimpa = preg_replace('/[^a-zA-Z0-9]/', '', $string);
    return $stringLimpa;
}
function removeNonAlphanumericStart($input)
{
    // Verifica se a entrada é uma string
    if (!is_string($input)) {
        return $input; // Retorna a entrada original se não for string
    }
    // Verifica se o primeiro caractere não é letra ou número
    // if (!ctype_alnum($input[0])) {
    if (!empty($input) && !ctype_alnum($input[0])) {
        // Remove o primeiro caractere não alfanumérico
        $input = substr($input, 1);
    }
    return $input;
}
function replaceMonthsWithOther($string)
{
    // Lista dos meses do ano em inglês (em maiúsculas e minúsculas)
    $months = [
        'january',
        'february',
        'march',
        'april',
        'may',
        'june',
        'july',
        'august',
        'september',
        'october',
        'november',
        'december',
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
    ];
    // Verifica se a string contém qualquer um dos meses
    foreach ($months as $month) {
        if (stripos($string, $month) !== false) {
            return "Other";
        }
    }
    // Se não encontrar nenhum mês, retorna a string original
    return $string;
}
    ?>