<?php
/**
 * Dashboard "home" stats overview widget for Fense Block VPN & Proxy.
 *
 * Registers a panel on the main WordPress Dashboard (index.php) showing a
 * quick traffic / proxy summary pulled from the *already cached* API data
 * (FENSE_BPVT_DEVOZON_api_data). It never triggers a live Fense.in API call
 * on dashboard load, so it costs nothing against the daily query limit and
 * never slows the admin screen.
 *
 * @package fense-block-vpn-proxy
 */

if ( !defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class FENSE_BPVT_Dashboard_Widget
{
	
	/** @var string Option holding the cached API stats JSON. */
	private $data_option = FENSE_BPVT_PLUGIN::DB_KEY . 'api_data';
	
	/** @var string Widget id (also used as the CSS scope). */
	private $widget_id = 'fense_bpvt_overview';
	
	/**
	 * Admin menu slug of the plugin's own dashboard page.
	 * Adjust to whatever you registered with add_menu_page().
	 *
	 * @var string
	 */
	private $page_slug = 'fense-bpvt';
	
	/**
	 * Hook registration. Safe to call on every admin load —
	 * wp_dashboard_setup only fires on the dashboard screen.
	 */
	public function register()
	{
		add_action( 'wp_dashboard_setup', [ $this, 'add_widget' ] );
	}
	
	public function add_widget()
	{
		// Only site managers should see traffic data.
		if ( !current_user_can( 'manage_options' ) ) {
			return;
		}
		
		wp_add_dashboard_widget(
			$this->widget_id,
			esc_html__( 'Fense — Proxy & VPN Overview', 'fense-block-vpn-proxy' ),
			[ $this, 'render' ],
			null,    // control callback
			null,    // callback args
			'normal',
			'high'   // surface it near the top of the dashboard
		);
	}
	
	public function render()
	{
		try {
			$data = $this->get_cached_data();
			
			if ( empty( $data ) ) {
				$this->render_empty();
				return;
			}
			
			$this->render_summary( $data );
		} catch ( Throwable $e ) {
			// Fail quiet: never break the dashboard over a stats panel.
			$this->render_empty();
		}
	}
	
	/**
	 * Reads the cached stats option. Never calls the API.
	 *
	 * @return array|null
	 */
	private function get_cached_data()
	{
		$data = FENSE_BPVT_Cache::wp_get( $this->data_option );
		
		if ( empty( $data ) ) {
			$data = ( new FENSE_BPVT_DATA_LOAD() )->run();
		} else {
			$data = json_decode( $data, true );
		}
		
		return is_array( $data ) ? $data : null;
	}
	
	private function render_summary( array $data )
	{
		$this->print_styles();
		
		$periods = [
			'today' => esc_html__( 'Today', 'fense-block-vpn-proxy' ),
			'last7days' => esc_html__( 'Last 7 Days', 'fense-block-vpn-proxy' ),
			'thismonth' => esc_html__( 'This Month', 'fense-block-vpn-proxy' ),
		];
		
		echo '<div class="fense-bpvt-dash">';
		
		foreach ( $periods as $key => $label ) {
			$node = $data[ $key ] ?? null;
			
			echo '<div class="fense-bpvt-tile">';
			echo '<span class="fense-bpvt-tile__visits">' . esc_html( $node ) . '</span>';
			echo '<span class="fense-bpvt-tile__label">' . esc_html( $label ) . '</span>';
			echo '</div>';
		}
		
		echo '</div>';
		
		
		$this->render_footer( $data );
	}
	
	private function render_footer( array $data )
	{
		$plan = isset( $data['plan'] ) ? (string)$data['plan'] : '';
		$perday = isset( $data['perday'] ) ? (string)$data['perday'] : '';
		$url = admin_url( 'admin.php?page=' . $this->page_slug );
		
		echo '<p class="fense-bpvt-foot">';
		
		if ( '' !== $plan ) {
			echo esc_html(
					sprintf(
					/* translators: 1: plan name, 2: daily query allowance. */
						__( ' %1$s · %2$s queries/day', 'fense-block-vpn-proxy' ),
						$plan,
						$perday
					)
				) . ' · ';
		}
		
		echo '<a href="' . esc_url( $url ) . '">'
			. esc_html__( 'Open full dashboard', 'fense-block-vpn-proxy' )
			. '</a>';
		
		echo '</p>';
	}
	
	private function render_empty()
	{
		$url = admin_url( 'admin.php?page=' . $this->page_slug );
		
		echo '<p>'
			. esc_html__( 'No statistics are cached yet.', 'fense-block-vpn-proxy' ) . ' '
			. '<a href="' . esc_url( $url ) . '">'
			. esc_html__( 'Open the Fense dashboard', 'fense-block-vpn-proxy' )
			. '</a> '
			. esc_html__( 'to load your latest traffic data.', 'fense-block-vpn-proxy' )
			. '</p>';
	}
	
	/**
	 * Extract a numeric count from a node that may be a scalar
	 * (e.g. 1500) or an array (e.g. ['total' => 1500, 'proxy' => 40]).
	 *
	 * @param mixed $node The period node from the cached payload.
	 * @param array $candidates Ordered list of keys to try when $node is an array.
	 * @return int
	 */
	private function count_of( $node, array $candidates )
	{
		if ( is_numeric( $node ) ) {
			return (int)$node;
		}
		
		if ( is_array( $node ) ) {
			foreach ( $candidates as $candidate ) {
				if ( isset( $node[ $candidate ] ) && is_numeric( $node[ $candidate ] ) ) {
					return (int)$node[ $candidate ];
				}
			}
		}
		
		return 0;
	}
	
	private function print_styles()
	{
		echo '<style>
		#fense_bpvt_overview .fense-bpvt-dash{display:flex;gap:12px;flex-wrap:wrap}
		#fense_bpvt_overview .fense-bpvt-tile{flex:1;min-width:90px;padding:10px;border:1px solid #e2e4e7;border-radius:6px;text-align:center;background:#f3f6f9;color:#405189;}
		#fense_bpvt_overview .fense-bpvt-tile__label{display:block;font-size:11px;text-transform:uppercase;letter-spacing:.03em;color:#646970}
		#fense_bpvt_overview .fense-bpvt-tile__visits{display:block;font-size:22px;font-weight:600;line-height:1.5}
		#fense_bpvt_overview .fense-bpvt-tile__blocked{display:block;font-size:12px;color:#d63638}
		#fense_bpvt_overview .fense-bpvt-foot{margin:10px 0 0;color:#646970;font-size:12px}
		</style>';
	}
}
