<?php
/**
 * Admin: WP Admin → BW Plugins → Installs dashboard.
 */

defined( 'ABSPATH' ) || exit;

class BW_Update_Server_Admin {

	const MENU_SLUG  = 'bw-update-server';
	const CAP        = 'manage_options';
	const STALE_DAYS = 30;

	public function register() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_init', array( $this, 'handle_csv_export' ) );
		add_action( 'wp_dashboard_setup', array( $this, 'register_dashboard_widget' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	public function register_menu() {
		add_menu_page(
			'BW Plugins',
			'BW Plugins',
			self::CAP,
			self::MENU_SLUG,
			array( $this, 'render_overview_page' ),
			'dashicons-admin-plugins',
			58
		);

		add_submenu_page(
			self::MENU_SLUG,
			'Installs',
			'Installs',
			self::CAP,
			self::MENU_SLUG,
			array( $this, 'render_overview_page' )
		);

		add_submenu_page(
			self::MENU_SLUG,
			'Activity',
			'Activity',
			self::CAP,
			self::MENU_SLUG . '-activity',
			array( $this, 'render_activity_page' )
		);
	}

	public function enqueue_assets( $hook ) {
		if ( false === strpos( (string) $hook, self::MENU_SLUG ) && 'index.php' !== $hook ) {
			return;
		}
		wp_enqueue_style(
			'bw-update-server-admin',
			BW_UPDATE_SERVER_URL . 'assets/css/admin.css',
			array(),
			BW_UPDATE_SERVER_VERSION
		);
	}

	public function render_overview_page() {
		if ( ! current_user_can( self::CAP ) ) {
			return;
		}

		$stats = BW_Update_Server_Stats::overview();

		echo '<div class="wrap bw-us-wrap">';
		echo '<h1>' . esc_html__( 'BW Plugin Installs', 'bw-update-server' ) . '</h1>';

		echo '<p class="bw-us-lead">' . sprintf(
			esc_html__( 'Tracking %1$d distinct sites across %2$d plugins.', 'bw-update-server' ),
			(int) $stats['total_sites'],
			(int) $stats['total_plugins']
		) . '</p>';

		echo '<div class="bw-us-summary">';
		echo '<div class="bw-us-card"><h3>' . esc_html__( 'Distinct Sites', 'bw-update-server' ) . '</h3><p class="bw-us-big">' . (int) $stats['total_sites'] . '</p></div>';
		echo '<div class="bw-us-card"><h3>' . esc_html__( 'Plugins Tracked', 'bw-update-server' ) . '</h3><p class="bw-us-big">' . (int) $stats['total_plugins'] . '</p></div>';
		echo '<div class="bw-us-card"><h3>' . esc_html__( 'Checks Today', 'bw-update-server' ) . '</h3><p class="bw-us-big">' . (int) $stats['checks_today'] . '</p></div>';
		echo '<div class="bw-us-card"><h3>' . esc_html__( 'Stale Installs', 'bw-update-server' ) . '</h3><p class="bw-us-big">' . (int) $stats['stale_sites'] . '</p></div>';
		echo '</div>';

		$by_plugin = BW_Update_Server_Stats::installs_by_plugin();

		echo '<h2>' . esc_html__( 'Per-Plugin Installs', 'bw-update-server' ) . '</h2>';

		if ( empty( $by_plugin ) ) {
			echo '<p>' . esc_html__( 'No installs logged yet. Once a BW plugin is installed on a client site and checks for updates, it will appear here.', 'bw-update-server' ) . '</p>';
		} else {
			foreach ( $by_plugin as $slug => $data ) {
				$this->render_plugin_section( $slug, $data );
			}
		}

		$export_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'      => self::MENU_SLUG,
					'bw_export' => 'csv',
				),
				admin_url( 'admin.php' )
			),
			'bw_us_export_csv'
		);

		echo '<h2>' . esc_html__( 'Export', 'bw-update-server' ) . '</h2>';
		echo '<p><a class="button button-secondary" href="' . esc_url( $export_url ) . '">' . esc_html__( 'Download CSV of all install logs', 'bw-update-server' ) . '</a></p>';

		echo '</div>';
	}

	private function render_plugin_section( $slug, $data ) {
		echo '<h3 class="bw-us-plugin-title">' . esc_html( $slug ) . ' <span class="bw-us-count">(' . (int) $data['sites_count'] . ' sites)</span></h3>';

		if ( ! empty( $data['version_distribution'] ) ) {
			echo '<div class="bw-us-version-dist">';
			echo '<strong>' . esc_html__( 'Version distribution:', 'bw-update-server' ) . '</strong> ';
			foreach ( $data['version_distribution'] as $ver => $count ) {
				$label = $ver ? $ver : '(unknown)';
				echo '<span class="bw-us-pill">' . esc_html( $label ) . ' &times; ' . (int) $count . '</span> ';
			}
			echo '</div>';
		}

		echo '<table class="wp-list-table widefat fixed striped bw-us-table">';
		echo '<thead><tr>';
		echo '<th>' . esc_html__( 'Site', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Installed', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'WP', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Last Check', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Checks', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Status', 'bw-update-server' ) . '</th>';
		echo '</tr></thead><tbody>';

		foreach ( $data['sites'] as $site ) {
			$site_url     = $site->site_url ? $site->site_url : '(unknown)';
			$age_seconds  = time() - strtotime( $site->last_check . ' UTC' );
			$is_stale     = $age_seconds > ( self::STALE_DAYS * DAY_IN_SECONDS );
			$status_class = $is_stale ? 'bw-us-stale' : 'bw-us-active';
			$status_text  = $is_stale ? __( 'stale', 'bw-update-server' ) : __( 'active', 'bw-update-server' );

			echo '<tr>';
			echo '<td>' . esc_html( $site_url ) . '</td>';
			echo '<td><code>' . esc_html( $site->installed_version ?: '?' ) . '</code></td>';
			echo '<td>' . esc_html( $site->wp_version ?: '-' ) . '</td>';
			echo '<td>' . esc_html( human_time_diff( strtotime( $site->last_check . ' UTC' ) ) . ' ' . __( 'ago', 'bw-update-server' ) ) . '</td>';
			echo '<td>' . (int) $site->check_count . '</td>';
			echo '<td><span class="' . esc_attr( $status_class ) . '">' . esc_html( $status_text ) . '</span></td>';
			echo '</tr>';
		}

		echo '</tbody></table>';
	}

	public function render_activity_page() {
		if ( ! current_user_can( self::CAP ) ) {
			return;
		}

		$limit = 100;
		$rows  = BW_Update_Server_Repository::recent_checks( null, $limit );

		echo '<div class="wrap bw-us-wrap">';
		echo '<h1>' . esc_html__( 'BW Plugins &mdash; Recent Activity', 'bw-update-server' ) . '</h1>';
		echo '<p>' . sprintf(
			esc_html__( 'Most recent %d update checks from client sites.', 'bw-update-server' ),
			$limit
		) . '</p>';

		echo '<table class="wp-list-table widefat striped">';
		echo '<thead><tr>';
		echo '<th>' . esc_html__( 'When', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Plugin', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Site', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Installed', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'Latest', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'WP', 'bw-update-server' ) . '</th>';
		echo '<th>' . esc_html__( 'IP', 'bw-update-server' ) . '</th>';
		echo '</tr></thead><tbody>';

		foreach ( $rows as $row ) {
			echo '<tr>';
			echo '<td>' . esc_html( $row->checked_at ) . '</td>';
			echo '<td><code>' . esc_html( $row->plugin_slug ) . '</code></td>';
			echo '<td>' . esc_html( $row->site_url ?: '-' ) . '</td>';
			echo '<td>' . esc_html( $row->installed_version ?: '-' ) . '</td>';
			echo '<td>' . esc_html( $row->latest_version ?: '-' ) . '</td>';
			echo '<td>' . esc_html( $row->wp_version ?: '-' ) . '</td>';
			echo '<td>' . esc_html( $row->ip_address ?: '-' ) . '</td>';
			echo '</tr>';
		}

		echo '</tbody></table></div>';
	}

	public function register_dashboard_widget() {
		if ( ! current_user_can( self::CAP ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'bw_update_server_widget',
			__( 'BW Plugins &mdash; Install Summary', 'bw-update-server' ),
			array( $this, 'render_dashboard_widget' )
		);
	}

	public function render_dashboard_widget() {
		$stats = BW_Update_Server_Stats::overview();
		$link  = admin_url( 'admin.php?page=' . self::MENU_SLUG );

		echo '<ul class="bw-us-widget">';
		echo '<li>' . sprintf(
			esc_html__( 'Tracking %d distinct sites', 'bw-update-server' ),
			(int) $stats['total_sites']
		) . '</li>';
		echo '<li>' . sprintf(
			esc_html__( '%d plugins with manifests', 'bw-update-server' ),
			(int) $stats['total_plugins']
		) . '</li>';
		echo '<li>' . sprintf(
			esc_html__( '%d checks in the last 24 hours', 'bw-update-server' ),
			(int) $stats['checks_today']
		) . '</li>';
		if ( $stats['stale_sites'] > 0 ) {
			echo '<li><strong>' . sprintf(
				esc_html__( '%d sites stale (no check > 30 days)', 'bw-update-server' ),
				(int) $stats['stale_sites']
			) . '</strong></li>';
		}
		echo '</ul>';
		echo '<p><a href="' . esc_url( $link ) . '">' . esc_html__( 'View all installs &rarr;', 'bw-update-server' ) . '</a></p>';
	}

	public function handle_csv_export() {
		if ( ! isset( $_GET['bw_export'] ) || 'csv' !== $_GET['bw_export'] ) {
			return;
		}
		if ( ! current_user_can( self::CAP ) ) {
			wp_die( 'Insufficient permissions' );
		}
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'bw_us_export_csv' ) ) {
			wp_die( 'Invalid nonce' );
		}

		global $wpdb;
		$table = BW_Update_Server_Installer::table_name();
		$rows  = $wpdb->get_results( "SELECT * FROM {$table} ORDER BY checked_at DESC" );

		nocache_headers();
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="bw-plugins-installs-' . gmdate( 'Ymd-His' ) . '.csv"' );

		$out = fopen( 'php://output', 'w' );
		fputcsv( $out, array( 'id', 'plugin_slug', 'site_url', 'installed_version', 'latest_version', 'wp_version', 'php_version', 'ip_address', 'user_agent', 'checked_at' ) );
		foreach ( $rows as $r ) {
			fputcsv( $out, array(
				$r->id,
				$r->plugin_slug,
				$r->site_url,
				$r->installed_version,
				$r->latest_version,
				$r->wp_version,
				$r->php_version,
				$r->ip_address,
				$r->user_agent,
				$r->checked_at,
			) );
		}
		fclose( $out );
		exit;
	}
}
