<?php
/**
 * Builds batched Insights snapshot responses for the admin dashboard.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class LinkCentral_Insights_Snapshot_Service {

	/** @var LinkCentral_Total_Clicks */
	private $total_clicks;

	/** @var LinkCentral_Most_Popular_Links */
	private $most_popular_links;

	/** @var LinkCentral_Recent_Clicks */
	private $recent_clicks;

	/** @var LinkCentral_Top_Countries|null */
	private $top_countries;

	/** @var LinkCentral_User_Agents|null */
	private $user_agents;

	/** @var LinkCentral_Top_Referrers|null */
	private $top_referrers;

	/**
	 * @param LinkCentral_Total_Clicks        $total_clicks        Total clicks aggregator.
	 * @param LinkCentral_Most_Popular_Links  $most_popular_links  Top links aggregator.
	 * @param LinkCentral_Recent_Clicks       $recent_clicks       Recent clicks aggregator.
	 * @param LinkCentral_Top_Countries|null  $top_countries       Premium geo aggregator.
	 * @param LinkCentral_User_Agents|null    $user_agents         Premium UA aggregator.
	 * @param LinkCentral_Top_Referrers|null  $top_referrers       Premium referrers aggregator.
	 */
	public function __construct( $total_clicks, $most_popular_links, $recent_clicks, $top_countries = null, $user_agents = null, $top_referrers = null ) {
		$this->total_clicks       = $total_clicks;
		$this->most_popular_links = $most_popular_links;
		$this->recent_clicks      = $recent_clicks;
		$this->top_countries      = $top_countries;
		$this->user_agents        = $user_agents;
		$this->top_referrers      = $top_referrers;
	}

	/**
	 * Parse widgets list from request.
	 *
	 * @param mixed $raw Raw widgets value.
	 * @return array<string>
	 */
	public static function parse_requested_widgets( $raw ) {
		if ( $raw === 'all' || $raw === null || $raw === '' ) {
			return array( 'all' );
		}

		if ( is_string( $raw ) ) {
			$decoded = json_decode( $raw, true );
			if ( is_array( $decoded ) ) {
				$raw = $decoded;
			} else {
				return array( sanitize_key( $raw ) );
			}
		}

		if ( ! is_array( $raw ) ) {
			return array( 'all' );
		}

		return array_map( 'sanitize_key', $raw );
	}

	/**
	 * Parse pagination map from request.
	 *
	 * @param array $post $_POST payload.
	 * @return array
	 */
	public static function parse_pagination( $post ) {
		$pagination = isset( $post['pagination'] ) && is_array( $post['pagination'] )
			? $post['pagination']
			: array();

		$defaults = array(
			'top_links'      => array( 'page' => 1 ),
			'recent_clicks'  => array( 'page' => 1 ),
			'geo'            => array(
				'tab'  => 'countries',
				'page' => 1,
			),
			'referrers'      => array(
				'tab'  => 'channels',
				'page' => 1,
			),
		);

		$merged = wp_parse_args( $pagination, $defaults );

		$merged['top_links']['page']     = max( 1, intval( $merged['top_links']['page'] ?? 1 ) );
		$merged['recent_clicks']['page'] = max( 1, intval( $merged['recent_clicks']['page'] ?? 1 ) );
		$merged['geo']['tab']            = sanitize_key( $merged['geo']['tab'] ?? 'countries' );
		$merged['geo']['page']           = max( 1, intval( $merged['geo']['page'] ?? 1 ) );
		$merged['referrers']['tab']      = sanitize_key( $merged['referrers']['tab'] ?? 'channels' );
		$merged['referrers']['page']    = max( 1, intval( $merged['referrers']['page'] ?? 1 ) );

		return $merged;
	}

	/**
	 * @param LinkCentral_Insights_Filters $filters    Filter context.
	 * @param array                        $widgets    Requested widget keys.
	 * @param array                        $pagination Pagination state.
	 * @return array
	 */
	public function build( LinkCentral_Insights_Filters $filters, array $widgets, array $pagination ) {
		LinkCentral_Insights_Query_Builder::reset_request_cache();

		$load_all = in_array( 'all', $widgets, true );
		$is_premium = function_exists( 'linkcentral_fs' ) && linkcentral_fs()->can_use_premium_code__premium_only();

		$result = array(
			'context' => array(
				'filters'         => $filters->to_public_array(),
				'resolved_period' => LinkCentral_Insights_Query_Builder::resolved_period_for_response( $filters ),
			),
			'widgets' => array(),
		);

		if ( $load_all || in_array( 'clicks_over_time', $widgets, true ) ) {
			$result['widgets']['clicks_over_time'] = $this->total_clicks->get_click_data_for_filters( $filters );
		}

		if ( $load_all || in_array( 'top_links', $widgets, true ) ) {
			$result['widgets']['top_links'] = $this->most_popular_links->get_top_links_data(
				$filters,
				$pagination['top_links']['page'],
				10
			);
		}

		if ( $load_all || in_array( 'recent_clicks', $widgets, true ) ) {
			$result['widgets']['recent_clicks'] = $this->recent_clicks->get_recent_clicks_data(
				$filters,
				$pagination['recent_clicks']['page']
			);
		}

		if ( $is_premium && $this->top_countries && ( $load_all || in_array( 'geo', $widgets, true ) ) ) {
			$result['widgets']['geo'] = $this->top_countries->get_geo_snapshot(
				$filters,
				$pagination['geo'],
				$load_all
			);
		}

		if ( $is_premium && $this->user_agents && ( $load_all || in_array( 'user_agents', $widgets, true ) ) ) {
			$result['widgets']['user_agents'] = $this->user_agents->get_all_breakdowns( $filters );
		}

		if ( $is_premium && $this->top_referrers && ( $load_all || in_array( 'referrers', $widgets, true ) ) ) {
			$result['widgets']['referrers'] = $this->top_referrers->get_referrers_snapshot(
				$filters,
				$pagination['referrers'],
				$load_all
			);
		}

		return $result;
	}
}
