<?php

// If user not in admin area, abort.
defined('DRAGONIZER_ADMIN_INIT') || die();

function display_debugging($obj)
{
?>
    <link href="https://cdn.datatables.net/1.13.8/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>

    <style>
        #logTable {
            direction: ltr !important;
            margin-bottom: 20px !important;
            text-align: center
        }

        #logTable td {
            vertical-align: middle;
        }

        .inline-svg-icons {
            display: inline-block;
            vertical-align: middle;
            margin-top: -2px;
        }

        #logTable .error-type-column {
            width: 90px;
        }

        #logTable .last-occurrence-column {
            width: 170px;
        }

        #logTable th {
            text-align: center;
        }

        .dataTables_filter,
        .dataTables_length {
            margin: 15px 0;
        }

        .dataTables_filter input {
            margin: 0 5px;
        }

        #logTable .details {
            text-align: left;
            direction: ltr;
            padding: 10px 15px;
            max-width: 700px;
        }

        #logTable .count {
            direction: <?php echo is_rtl() ? 'rtl' : 'ltr' ?>;
        }

        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 6px;
        }

        .dataTables_wrapper .dataTables_filter input {
            border-radius: 6px;
        }

        .log-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #eff0f1;
            box-shadow: rgba(0, 0, 0, .05) 0 1px 2px 0 !important
        }

        .log-footer a {
            color: #0073aa;
            text-decoration: none;
            font-weight: bold;
        }
    </style>

    <div>

        <div class="dragon-hidden dragonizer-warning-box" style="text-align:justify;padding-bottom:15px">
            <p>
                <?php _e('This section is designed to help developers and site administrators identify and fix WordPress errors. By enabling advanced debugging mode, the plugin adds WP_DEBUG, SCRIPT_DEBUG, and WP_DEBUG_LOG values to the wp-config.php file. These settings allow errors to be logged in a specific log file while preventing their display to site visitors. It then displays these errors in a categorized manner in the table below, allowing you to efficiently review and resolve issues.', 'dragonizer'); ?>
            </p>
            <p style="color: #ff4d4d">
                <?php _e('Enabling debug mode (WP_DEBUG) and using development versions of CSS and JavaScript files (SCRIPT_DEBUG) can reduce site loading speed and pose security risks on live sites. These risks include potential exposure of sensitive information to visitors.', 'dragonizer'); ?>
            </p>
        </div>

        <table id="logTable" class="dragon-hidden hover wp-list-table dragonizer_options-table widefat" width="100%">
            <thead>
                <tr>
                    <th class="number-column">#</th>
                    <th class="error-type-column"><?= __('Error Type', 'dragonizer') ?></th>
                    <th class="details-column"><?= __('Details', 'dragonizer') ?></th>
                    <th class="last-occurrence-column"><?= __('Last Occurrence', 'dragonizer') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php
                // Include your parseLogFile function here

                $filePath = DRAGONIZER_UP_DIR . "/" . dr_get_log_filename();
                $fileURL  = DRAGONIZER_UP_URL . "/" . dr_get_log_filename();
                dr_trim_log_file($filePath);
                usleep(500);
                $errorEntries = parseLogFile($filePath);
                $index = 1;

                foreach ($errorEntries as $entry) {
                    // Format date using wp_date or date_i18n
                    if (function_exists('wp_date')) {
                        $date_time = wp_date('M j, Y - H:i:s', strtotime($entry['lastOccurrence']));
                    } else {
                        $date_time = date_i18n('M j, Y - H:i:s', strtotime($entry['lastOccurrence']));
                    }

                    echo "<tr>";
                    echo "<td>" . $index++ . "</td>";
                    echo "<td>" . htmlspecialchars($entry['errorType']) . "</td>";
                    // Displaying message, source, and position within the details column
                    echo "<td class='details'>";
                    echo DRFS::read(DRAGONIZER_ASE_DIR . '/images/other/message.svg') . " " . "<strong>Message:</strong> " . htmlspecialchars($entry['details']['message']) . "<br>";
                    echo DRFS::read(DRAGONIZER_ASE_DIR . '/images/other/source.svg') . " " . "<strong>Source:</strong> " . htmlspecialchars($entry['details']['source']) . "<br>";
                    echo DRFS::read(DRAGONIZER_ASE_DIR . '/images/other/position.svg') . " " . "<strong>Position:</strong> " . htmlspecialchars($entry['details']['position']);
                    echo "</td>";
                    echo "<td class='count'>" . htmlspecialchars($date_time) . "<br>(" . __('Logged', 'dragonizer') . " " . htmlspecialchars($entry['count']) . " " . __('times', 'dragonizer') . ")" . "</td>";
                    echo "</tr>";
                }
                ?>
            </tbody>
        </table>
    </div>
    <?php if (file_exists($filePath)) { ?>

        <br>
        <div class="dragon-hidden log-footer">
            <a class="button" id="ajax-clear-log">Clear Log</a>
            <a target="_blank" href="<?= $fileURL ?>"><?= dr_get_log_filename() ?></a>
        </div>
        <br>

        <script>
            jQuery(document).ready(function($) {
                $('#logTable').DataTable({
                    pageLength: 15,
                    initComplete: function() {
                        $('#logTable_filter').addClass('dragon-hidden');
                        $('#logTable_length').addClass('dragon-hidden');
                        $('#logTable_info').addClass('dragon-hidden');
                        $('#logTable_paginate').addClass('dragon-hidden');
                    },
                    "language": {
                        "lengthMenu": "<?php echo __('Display _MENU_ records per page', 'dragonizer'); ?>",
                        "zeroRecords": "<?php echo __('Nothing found - sorry', 'dragonizer'); ?>",
                        "info": "<?php echo __('Showing page _PAGE_ of _PAGES_', 'dragonizer'); ?>",
                        "infoEmpty": "<?php echo __('No records available', 'dragonizer'); ?>",
                        "infoFiltered": "<?php echo __('(filtered from _MAX_ total records)', 'dragonizer'); ?>",
                        "search": "<?php echo __('Search:', 'dragonizer'); ?>",
                        "paginate": {
                            "first": "<?php echo __('First', 'dragonizer'); ?>",
                            "last": "<?php echo __('Last', 'dragonizer'); ?>",
                            "next": "<?php echo __('Next', 'dragonizer'); ?>",
                            "previous": "<?php echo __('Previous', 'dragonizer'); ?>"
                        }
                    }
                });

                $('#ajax-clear-log').click(function() {
                    var dra_loader = $('.dragonizer_tab_group #loader-wrapper');
                    if (confirm('Are you sure you want to clear the log file?')) {
                        $.ajax({
                            url: '<?php echo admin_url('admin-ajax.php') ?>',
                            type: 'POST',
                            data: {
                                action: 'dragonizer_clear_log_file'
                            },
                            success: function(response) {
                                toastr["success"]("<?= __('Log file cleared!', 'dragonizer') ?>", "<?= __('Success', 'dragonizer') ?>");
                                location.reload();
                            },
                            error: function() {
                                toastr["error"]("<?= __('Error clearing the log file.', 'dragonizer') ?>", "<?= __('Failed', 'dragonizer') ?>");
                            },
                            beforeSend: function beforeSend() {
                                dra_loader.removeClass('loaded');
                            },
                            complete: function complete() {
                                dra_loader.addClass('loaded');
                            },
                        });
                    }
                });

            });
        </script>

    <?php } ?>

<?php
}

function parseLogFile($filePath): array
{
    if (!file_exists($filePath) || !is_readable($filePath)) {
        // echo "Error: file does not exist or is not readable.";
        return [];
    }

    $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if ($lines === false) {
        // echo "Error: Unable to read the file.";
        return [];
    }

    $errors = [];
    $isFatalError = false;
    $fatalErrorContent = '';
    $fatalErrorStartLine = '';

    foreach ($lines as $line) {
        if ($isFatalError) {
            // Continue reading the stack trace
            if (preg_match('/^\#/', $line)) {
                $fatalErrorContent .= "\n" . $line;
            } else {
                // End of stack trace, process the fatal error
                $errors[$fatalErrorStartLine]['details']['message'] .= "\n" . $fatalErrorContent;
                $isFatalError = false;
                $fatalErrorContent = '';
            }
        } elseif (preg_match('/\[(.*?)\] PHP Fatal error:  (.*?) in (.*?):(\d+)/', $line, $matches)) {
            // Start of a new fatal error
            $timestamp = $matches[1];
            $errorMessage = $matches[2];
            $errorSource = dr_make_relative_path($matches[3]);
            $errorPosition = 'line ' . $matches[4];

            $errorKey = md5($errorMessage . $errorSource . $errorPosition);
            $fatalErrorStartLine = $errorKey;

            if (!isset($errors[$errorKey])) {
                $errors[$errorKey] = [
                    'lastOccurrence' => $timestamp,
                    'errorType' => 'PHP Fatal error',
                    'count' => 1,
                    'details' => [
                        'message' => $errorMessage,
                        'source' => $errorSource,
                        'position' => $errorPosition,
                    ],
                ];
            } else {
                $errors[$errorKey]['count']++;
                $errors[$errorKey]['lastOccurrence'] = $timestamp;
            }
            $isFatalError = true;
        } elseif (preg_match('/\[(.*?)\] (PHP|JavaScript) (.*?): (.*?) in (.*?) on line (\d+)/', $line, $matches)) {
            $timestamp = $matches[1];
            $errorType = $matches[2] . ' ' . $matches[3];
            $errorMessage = $matches[4];
            $errorSource = dr_make_relative_path($matches[5]);
            $errorPosition = 'line ' . $matches[6];

            $errorKey = md5($errorType . $errorMessage . $errorSource . $errorPosition);
            if (!isset($errors[$errorKey])) {
                $errors[$errorKey] = [
                    'lastOccurrence' => $timestamp,
                    'errorType' => $errorType,
                    'count' => 1,
                    'details' => [
                        'message' => $errorMessage,
                        'source' => $errorSource,
                        'position' => $errorPosition,
                    ],
                ];
            } else {
                $errors[$errorKey]['count']++;
                $errors[$errorKey]['lastOccurrence'] = $timestamp;
            }
        }
        // Match Other Errors
        elseif (preg_match('/\[(.*?)\] (.*)/', $line, $matches)) {
            $timestamp = $matches[1];
            $errorMessage = $matches[2];

            $errorKey = md5('Other' . $errorMessage);
            if (!isset($errors[$errorKey])) {
                $errors[$errorKey] = [
                    'lastOccurrence' => $timestamp,
                    'errorType' => 'Other',
                    'count' => 1,
                    'details' => [
                        'message' => $errorMessage,
                        'source' => '-',
                        'position' => '-',
                    ],
                ];
            } else {
                $errors[$errorKey]['count']++;
                $errors[$errorKey]['lastOccurrence'] = $timestamp;
            }
        }
    }

    return array_values($errors);
}
