<?php

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

class Freefactu_Debug {

    /**
     * Constructor - initializes debug class.
     *
     * What this function does:
     * - Empty constructor (actions handled by Admin class via tabs)
     * - Class provides static methods for debug page rendering
     *
     * Where it's called from:
     * - freefactu.php: __construct() method during plugin initialization
     *
     * @return void
     */
    public function __construct() {
        // Actions handled in Admin class now via tabs
    }

    /**
     * Format a single log line with color-coded icon based on log level.
     *
     * What this function does:
     * - Parses log line format: [timestamp] [type] message
     * - Assigns color-coded icons based on log type (error, warning, info, debug)
     * - Returns formatted HTML with proper styling
     * - Handles lines that don't match expected format
     *
     * Where it's called from:
     * - class-freefactu-debug.php: render_debug_page() method
     *
     * @param string $log_line The raw log line.
     * @return string Formatted HTML for the log line.
     */
    private static function format_log_line( $log_line ) {
        $log_line = trim( $log_line );
        if ( empty( $log_line ) ) {
            return '';
        }

        // Parse log format: [timestamp] [type] message
        // Example: [2024-12-02 10:30:45] [error] Something went wrong
        if ( preg_match( '/^\[(.*?)\]\s*\[(.*?)\]\s*(.*)$/', $log_line, $matches ) ) {
            $timestamp = $matches[1];
            $type = strtolower( trim( $matches[2] ) );
            $message = $matches[3];

            // Determine icon and color based on type
            $icon = '●';
            $color = '#d4d4d4'; // default gray

            switch ( $type ) {
                case 'error':
                    $icon = '●';
                    $color = '#f44336'; // red
                    break;
                case 'warning':
                    $icon = '●';
                    $color = '#ff9800'; // orange/yellow
                    break;
                case 'info':
                    $icon = '●';
                    $color = '#4caf50'; // green
                    break;
                case 'debug':
                    $icon = '●';
                    $color = '#2196f3'; // blue
                    break;
            }

            return sprintf(
                '<div style="margin-bottom: 8px; font-family: \'Consolas\', \'Monaco\', \'Courier New\', monospace; font-size: 13px; line-height: 1.6;">
                    <span style="color: %s; font-size: 16px; margin-right: 8px;">%s</span>
                    <span style="color: #888; margin-right: 8px;">[%s]</span>
                    <span style="color: %s; font-weight: 600; margin-right: 8px;">[%s]</span>
                    <span style="color: #d4d4d4; word-wrap: break-word; overflow-wrap: break-word;">%s</span>
                </div>',
                esc_attr( $color ),
                esc_html( $icon ),
                esc_html( $timestamp ),
                esc_attr( $color ),
                esc_html( strtoupper( $type ) ),
                esc_html( $message )
            );
        }

        // Fallback for lines that don't match the expected format
        return sprintf(
            '<div style="margin-bottom: 8px; font-family: \'Consolas\', \'Monaco\', \'Courier New\', monospace; font-size: 13px; line-height: 1.6; color: #d4d4d4; word-wrap: break-word; overflow-wrap: break-word;">%s</div>',
            esc_html( $log_line )
        );
    }

    /**
     * Render the debug page with logs.
     *
     * What this function does:
     * - Handles "Clear Logs" form submission
     * - Retrieves last 200 log lines
     * - Displays formatted logs with color coding
     * - Shows clear logs button
     *
     * Where it's called from:
     * - class-freefactu-admin.php: render_main_page() method when debug tab is active
     *
     * @return void
     */
    public static function render_debug_page() {
        // Handle Clear Logs
        if ( isset( $_POST['clear_logs'] ) && check_admin_referer( 'freefactu_clear_logs' ) ) {
            Freefactu_Logger::clear_logs();
            echo '<div class="notice notice-success"><p>' . esc_html__( 'Logs cleared.', 'freefactu' ) . '</p></div>';
        }

        $logs = Freefactu_Logger::get_logs( 200 );
        ?>
        <div class="wrap">
            <h2><?php esc_html_e( 'Freefactu Debug Log', 'freefactu' ); ?></h2>
            


            <!-- Clear Logs Section -->
            <h3 style="margin-top: 30px;"><?php esc_html_e( 'Registros de Depuración', 'freefactu' ); ?></h3>
            <form method="post" style="margin-bottom: 20px;">
                <?php wp_nonce_field( 'freefactu_clear_logs' ); ?>
                <input type="submit" name="clear_logs" class="button button-secondary" value="<?php esc_attr_e( 'Clear Logs', 'freefactu' ); ?>" />
            </form>

            <div style="background: #1e1e1e; border-radius: 4px; padding: 15px; max-width: 100%; overflow: auto;">
                <?php if ( empty( $logs ) ) : ?>
                    <p style="color: #888; font-family: 'Consolas', 'Monaco', 'Courier New', monospace; font-size: 13px; margin: 0;"><?php esc_html_e( 'No logs yet.', 'freefactu' ); ?></p>
                <?php else : ?>
                    <?php foreach ( $logs as $log_line ) : ?>
                        <?php echo wp_kses_post( self::format_log_line( $log_line ) ); ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
}
