<?php

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\Abilities\Debug_Log_Abilities;

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

/**
 * WordPress admin dashboard widget showing recent PHP errors.
 *
 * Displays the last 5 error entries from debug.log with severity badges,
 * source info, and a 24-hour error count. Only visible to administrators
 * when the error_debugger module is enabled.
 *
 * @package AtlasAiDev\Awfah\Admin
 */
class Error_Dashboard_Widget {

	/**
	 * Register the dashboard widget hook.
	 */
	public function __construct() {
		if ( current_user_can( 'manage_options' ) ) {
			add_action( 'wp_dashboard_setup', [ $this, 'register_widget' ] );
		}
	}

	/**
	 * Register the widget with WordPress.
	 */
	public function register_widget(): void {
		wp_add_dashboard_widget(
			'awfah_error_widget',
			'AtlasAI Connector — ' . __( 'Recent Errors', 'ai-workflow-automation-ai-agent-hub' ),
			[ $this, 'render' ]
		);
	}

	/**
	 * Render the dashboard widget content.
	 */
	public function render(): void {
		$tracker = \AtlasAiDev\Awfah\Service\Error_Tracker::instance();

		// Get error groups sorted by most recent.
		$groups = $tracker->get_groups( 'last_seen', 50 );
		$now    = time();

		// Count errors in the last 24 hours.
		$day_ago      = $now - DAY_IN_SECONDS;
		$recent_count = 0;
		foreach ( $groups as $group ) {
			$ts = strtotime( $group['last_seen'] ?? '' );
			if ( $ts && $ts >= $day_ago ) {
				$recent_count += $group['count'];
			}
		}

		// Take only the last 5 groups for display.
		$display = array_slice( $groups, 0, 5 );

		// Severity badge colors.
		$badge_colors = [
			'fatal'      => 'background:#fef2f2;color:#991b1b;border:1px solid #fecaca;',
			'warning'    => 'background:#fffbeb;color:#92400e;border:1px solid #fde68a;',
			'notice'     => 'background:#fefce8;color:#854d0e;border:1px solid #fef08a;',
			'deprecated' => 'background:#f8fafc;color:#475569;border:1px solid #e2e8f0;',
			'unknown'    => 'background:#f8fafc;color:#475569;border:1px solid #e2e8f0;',
		];

		echo '<div class="awfah-dashboard-widget">';

		// Error count summary.
		if ( $recent_count > 0 ) {
			echo '<p style="margin:0 0 12px;padding:8px 12px;background:#fef2f2;border:1px solid #fecaca;border-radius:6px;font-size:13px;color:#991b1b;">';
			echo '<strong>' . esc_html(
				sprintf(
					/* translators: %d: number of errors */
					_n( '%d error in the last 24 hours', '%d errors in the last 24 hours', $recent_count, 'ai-workflow-automation-ai-agent-hub' ),
					$recent_count
				)
			) . '</strong>';
			echo '</p>';
		} else {
			echo '<p style="margin:0 0 12px;padding:8px 12px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:6px;font-size:13px;color:#166534;">';
			echo esc_html__( 'No errors in the last 24 hours.', 'ai-workflow-automation-ai-agent-hub' );
			echo '</p>';
		}

		if ( empty( $display ) ) {
			echo '<p style="color:#64748b;font-size:13px;">' . esc_html__( 'No recent PHP errors detected. Your site is running cleanly.', 'ai-workflow-automation-ai-agent-hub' ) . '</p>';
		} else {
			echo '<table class="widefat striped" style="border:none;">';
			echo '<tbody>';
			foreach ( $display as $group ) {
				$severity    = $group['severity'] ?? 'unknown';
				$badge_style = $badge_colors[ $severity ] ?? $badge_colors['unknown'];
				$message     = $group['message'] ?? '';
				if ( strlen( $message ) > 80 ) {
					$message = substr( $message, 0, 77 ) . '...';
				}
				$source = ucfirst( $group['source_type'] ?? '' );
				if ( ! empty( $group['source_name'] ) ) {
					$source .= ': ' . $group['source_name'];
				}
				$time = $group['last_seen'] ?? '';
				if ( $time ) {
					$ts = strtotime( $time );
					if ( $ts ) {
						$time = human_time_diff( $ts, $now ) . ' ' . __( 'ago', 'ai-workflow-automation-ai-agent-hub' );
					}
				}
				$count = (int) ( $group['count'] ?? 1 );

				echo '<tr>';
				echo '<td style="width:70px;padding:6px 8px;">';
				echo '<span style="display:inline-block;padding:2px 6px;border-radius:4px;font-size:11px;font-weight:600;text-transform:uppercase;' . esc_attr( $badge_style ) . '">' . esc_html( $severity ) . '</span>';
				echo '</td>';
				echo '<td style="padding:6px 8px;font-size:12px;">' . esc_html( $message ) . '</td>';
				echo '<td style="width:40px;padding:6px 8px;font-size:12px;font-weight:700;text-align:center;">' . esc_html( $count ) . '</td>';
				echo '<td style="width:100px;padding:6px 8px;font-size:11px;color:#64748b;">' . esc_html( $source ) . '</td>';
				echo '<td style="width:70px;padding:6px 8px;font-size:11px;color:#94a3b8;white-space:nowrap;">' . esc_html( $time ) . '</td>';
				echo '</tr>';
			}
			echo '</tbody>';
			echo '</table>';
		}

		// Footer link.
		$admin_url = admin_url( 'admin.php?page=ai-workflow-automation-ai-agent-hub' );
		echo '<p style="margin:12px 0 0;text-align:right;">';
		echo '<a href="' . esc_url( $admin_url ) . '" class="button button-primary button-small">' . esc_html__( 'View Error Debugger', 'ai-workflow-automation-ai-agent-hub' ) . ' &rarr;</a>';
		echo '</p>';

		echo '</div>';
	}
}
