<?php
/**
 * Admin page: Monitoring & Dashboard
 *
 * Wyświetla status systemowy, logi synchronizacji, aktywne sesje, circuit breaker.
 *
 * @package KSEF\WordPress\Admin
 */

namespace KSEF\WordPress\Admin;

// phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.SlowDBQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Wlasne tabele gksef_*: wartosci przez $wpdb->prepare()/esc_like(), nazwy tabel z $wpdb->prefix, paginacja rzutowana (int); nonce weryfikowany w handlerze (check_ajax_referer/check_admin_referer).

// (Stare klasy Api\Session_Pool / Api\Ksef_Client usunięte w v1.6.8.
//  Circuit-breaker status czytany jest z wp_options, bez instancjonowania API.)

/**
 * Monitoring_Dashboard
 *
 * Obsługuje:
 * - Circuit breaker status
 * - Aktywne sesje
 * - Ostatnie synchronizacje
 * - Statystyki faktur
 * - Log błędów
 */
class Monitoring_Dashboard {

	/**
	 * Renderuj dashboard
	 *
	 * @return void
	 */
	public function render_page() {
		global $wpdb;

		// Sprawdź uprawnienia
		if ( ! current_user_can( 'ksef_view_monitoring' ) ) {
			wp_die( esc_html__( 'Brak uprawnień.', 'prostafaktura-ksef' ) );
		}

		// Pobierz dane
		$credentials      = $wpdb->get_results( "SELECT id, nip, ksef_environment FROM {$wpdb->prefix}gksef_credentials", ARRAY_A );
		$circuit_breakers = [];
		$active_sessions  = [];

		foreach ( $credentials as $cred ) {
			$circuit_breakers[ $cred['id'] ] = $this->get_circuit_breaker_status( $cred['id'] );
		}

		// Statystyki faktur wysyłanych
		$outgoing_stats = $wpdb->get_row(
			"SELECT
				COUNT(*) as total,
				SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
				SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
				SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
				SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
				SUM(CASE WHEN status = 'offline' THEN 1 ELSE 0 END) as offline,
				SUM(gross_amount) as total_amount
			FROM {$wpdb->prefix}gksef_outgoing_invoices",
			ARRAY_A
		);



		Modern_Shell::open( 'monitoring', [
			'crumbs'   => [ __( 'Analiza', 'prostafaktura-ksef' ), __( 'Monitoring', 'prostafaktura-ksef' ) ],
			'title'    => 'Monitoring | KSeF',
			'subtitle' => __( 'Stan połączenia, circuit breakery i statystyki wysyłek do KSeF. Wszystko czego nie widać w fakturach.', 'prostafaktura-ksef' ),
		] );
		try {
		?>

			<!-- Karty statusu -->
			<div class="ksef-dashboard-grid">
				<!-- Faktury wysyłane -->
				<div class="ksef-card">
					<h3><?php esc_html_e( 'Faktury wysyłane', 'prostafaktura-ksef' ); ?></h3>
					<div class="ksef-stat-large">
						<?php echo intval( $outgoing_stats['total'] ?? 0 ); ?>
						<small><?php esc_html_e( 'razem', 'prostafaktura-ksef' ); ?></small>
					</div>
					<div class="ksef-stat-row">
						<span class="status pending"><?php echo intval( $outgoing_stats['pending'] ?? 0 ); ?> <?php esc_html_e( 'Oczekujące', 'prostafaktura-ksef' ); ?></span>
						<span class="status sent"><?php echo intval( $outgoing_stats['sent'] ?? 0 ); ?> <?php esc_html_e( 'Wysłane', 'prostafaktura-ksef' ); ?></span>
					</div>
					<div class="ksef-stat-row">
						<span class="status confirmed"><?php echo intval( $outgoing_stats['confirmed'] ?? 0 ); ?> <?php esc_html_e( 'Potwierdzone', 'prostafaktura-ksef' ); ?></span>
						<span class="status offline"><?php echo intval( $outgoing_stats['offline'] ?? 0 ); ?> <?php esc_html_e( 'Offline', 'prostafaktura-ksef' ); ?></span>
					</div>
					<div class="ksef-amount">
						<?php echo esc_html( number_format_i18n( $outgoing_stats['total_amount'] ?? 0, 2 ) ); ?> PLN
					</div>
				</div>


				<!-- Circuit Breaker Status -->
				<div class="ksef-card">
					<h3><?php esc_html_e( 'Circuit Breaker', 'prostafaktura-ksef' ); ?></h3>
					<?php foreach ( $credentials as $cred ) : ?>
						<?php
						$cb_status = $circuit_breakers[ $cred['id'] ];
						$is_open   = 'open' === $cb_status['status'];
						?>
						<div class="ksef-cb-item">
							<strong><?php echo esc_html( $cred['nip'] ); ?></strong>
							<span class="cb-status <?php echo $is_open ? 'open' : 'closed'; ?>">
								<?php echo $is_open ? '🔴 ' : '🟢 '; ?>
								<?php echo $is_open ? esc_html__( 'OTWARTY', 'prostafaktura-ksef' ) : esc_html__( 'ZAMKNIĘTY', 'prostafaktura-ksef' ); ?>
							</span>
							<?php if ( $is_open && isset( $cb_status['reset_at'] ) ) : ?>
								<div class="reset-time">
									<?php
									$reset_time = strtotime( $cb_status['reset_at'] );
									$now        = current_time( 'timestamp' );
									$diff       = $reset_time - $now;
									if ( $diff > 0 ) {
										// translators: %d = liczba minut do resetu
										echo esc_html( sprintf( __( 'Reset za %d min', 'prostafaktura-ksef' ), ceil( $diff / 60 ) ) );
									}
									?>
								</div>
							<?php endif; ?>
						</div>
					<?php endforeach; ?>
				</div>
			</div>

			<!-- Ostatnie synchronizacje (Pro) -->
			<div class="ksef-section">
				<h2><?php esc_html_e( 'Ostatnie synchronizacje', 'prostafaktura-ksef' ); ?> <span style="color:#b26a00;font-weight:normal;font-size:13px;">🔒 Pro</span></h2>
				<p class="description" style="margin:0 0 10px;"><?php esc_html_e( 'Automatyczna synchronizacja faktur z KSeF (pobieranie faktur zakupowych i sprzedażowych) to funkcja Pro. Tutaj zobaczysz historię i statusy synchronizacji.', 'prostafaktura-ksef' ); ?></p>
				<table class="wp-list-table widefat striped" style="opacity:.55;">
					<thead><tr>
						<th><?php esc_html_e( 'Typ', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Status', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Przetworzone / Poprawne / Błędy', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Data', 'prostafaktura-ksef' ); ?></th>
					</tr></thead>
					<tbody>
						<tr><td><strong><?php esc_html_e( 'Pobieranie', 'prostafaktura-ksef' ); ?></strong><br><small><?php esc_html_e( 'zakup', 'prostafaktura-ksef' ); ?></small></td><td><?php echo $this->get_sync_status_badge( 'completed' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td><td>12 / 12 / 0</td><td><?php echo esc_html( date_i18n( 'Y-m-d' ) ); ?></td></tr>
						<tr><td><strong><?php esc_html_e( 'Pobieranie', 'prostafaktura-ksef' ); ?></strong><br><small><?php esc_html_e( 'sprzedaż', 'prostafaktura-ksef' ); ?></small></td><td><?php echo $this->get_sync_status_badge( 'completed' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td><td>5 / 5 / 0</td><td><?php echo esc_html( date_i18n( 'Y-m-d' ) ); ?></td></tr>
					</tbody>
				</table>
				<p style="margin-top:10px;"><a href="https://prostafakturaksef.pl/cennik" target="_blank" rel="noopener" class="button button-primary"><?php esc_html_e( 'Odblokuj synchronizację w Pro →', 'prostafaktura-ksef' ); ?></a></p>
			</div>



		<?php ob_start(); ?>
			.ksef-dashboard-grid {
				display: grid;
				grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
				gap: 20px;
				margin-bottom: 30px;
			}
			.ksef-card {
				background: white;
				border: 1px solid #ddd;
				border-radius: 8px;
				padding: 20px;
				box-shadow: 0 1px 3px rgba(0,0,0,0.1);
			}
			.ksef-card h3 {
				margin-top: 0;
				margin-bottom: 20px;
				border-bottom: 2px solid #0073aa;
				padding-bottom: 10px;
			}
			.ksef-stat-large {
				font-size: 36px;
				font-weight: bold;
				color: #0073aa;
				margin-bottom: 15px;
			}
			.ksef-stat-large small {
				display: block;
				font-size: 12px;
				color: #666;
				font-weight: normal;
				margin-top: 5px;
			}
			.ksef-stat-row {
				display: flex;
				gap: 10px;
				margin-bottom: 10px;
				flex-wrap: wrap;
			}
			.ksef-stat-row .status {
				padding: 5px 10px;
				border-radius: 4px;
				font-size: 12px;
				white-space: nowrap;
			}
			.status.pending {
				background: #fff8dc;
			}
			.status.sent {
				background: #cce5ff;
			}
			.status.confirmed {
				background: #ccf0dd;
				color: #006400;
			}
			.status.imported {
				background: #cce5ff;
			}
			.ksef-amount {
				font-size: 18px;
				font-weight: bold;
				color: #006400;
				margin-top: 15px;
				border-top: 1px solid #ddd;
				padding-top: 10px;
			}
			.ksef-cb-item {
				padding: 10px 0;
				border-bottom: 1px solid #eee;
				display: flex;
				justify-content: space-between;
				align-items: center;
				gap: 10px;
			}
			.ksef-cb-item strong {
				font-family: monospace;
			}
			.cb-status {
				font-weight: bold;
			}
			.cb-status.open {
				color: #990000;
			}
			.cb-status.closed {
				color: #006400;
			}
			.reset-time {
				font-size: 12px;
				color: #999;
			}
			.ksef-section {
				background: white;
				border: 1px solid #ddd;
				border-radius: 8px;
				padding: 20px;
				margin-bottom: 30px;
			}
			.ksef-section h2 {
				margin-top: 0;
				border-bottom: 2px solid #0073aa;
				padding-bottom: 10px;
			}
		<?php Modern_Shell::inline_style( 'ksef-monitoring', ob_get_clean() ); ?>
		<?php
		} finally {
			Modern_Shell::close();
		}
	}

	/**
	 * Pobierz status circuit breaker
	 *
	 * @param int $credential_id ID kredencjału.
	 * @return array Status ['status' => 'open'|'closed', 'reset_at' => timestamp]
	 */
	private function get_circuit_breaker_status( $credential_id ) {
		$error_count = intval( get_option( "gksef_circuit_breaker_errors_{$credential_id}", 0 ) );
		$paused_until = intval( get_option( "gksef_circuit_breaker_paused_{$credential_id}", 0 ) );
		$now = current_time( 'timestamp' );

		// Jeśli pause czasowa wciąż aktualna → circuit breaker otwarty
		if ( $paused_until > $now ) {
			return [
				'status'   => 'open',
				'errors'   => $error_count,
				'reset_at' => gmdate( 'Y-m-d H:i:s', $paused_until ),
			];
		}

		// Reset pause
		if ( $paused_until > 0 && $paused_until <= $now ) {
			delete_option( "gksef_circuit_breaker_paused_{$credential_id}" );
			delete_option( "gksef_circuit_breaker_errors_{$credential_id}" );
		}

		return [
			'status' => 'closed',
			'errors' => 0,
		];
	}

	/**
	 * Pobierz badge statusu synchronizacji
	 *
	 * @param string $status Status.
	 * @return string HTML
	 */
	private function get_sync_status_badge( $status ) {
		$labels = [
			'started'   => __( 'Uruchomiona', 'prostafaktura-ksef' ),
			'completed' => __( 'Zakończona', 'prostafaktura-ksef' ),
			'error'     => __( 'Błąd', 'prostafaktura-ksef' ),
		];

		$classes = [
			'started'   => 'sync-started',
			'completed' => 'sync-completed',
			'error'     => 'sync-error',
		];

		$class = $classes[ $status ] ?? 'sync-unknown';
		$label = $labels[ $status ] ?? $status;

		$styles = [
			'sync-started'   => 'background: #fff8dc; color: #333;',
			'sync-completed' => 'background: #ccf0dd; color: #006400;',
			'sync-error'     => 'background: #ffcccc; color: #990000;',
		];

		$style = $styles[ $class ] ?? '';

		return sprintf( '<span style="%s padding: 3px 8px; border-radius: 3px; font-weight: bold;">%s</span>', $style, esc_html( $label ) );
	}
}
