<?php
/**
 * Statistics Page
 *
 * Renders the Relatedly → Statistics admin page.
 *
 * @package Relatedly\Admin\Statistics
 * @since   2.0.0
 * @since   2.3.0 Added comparison dates and richer initial payload.
 */

namespace Relatedly\Admin\Statistics;

use Relatedly\Core\Options;
use Relatedly\Core\Cache;
use Relatedly\Premium\FeatureGate;

defined( 'ABSPATH' ) || exit;

/**
 * Renders the statistics admin page.
 *
 * @since 2.0.0
 * @since 2.3.0 Passes comparison date ranges to the template.
 */
class Page {

	/**
	 * Plugin settings repository.
	 *
	 * @since 2.0.0
	 * @var Options
	 */
	private Options $options;

	/**
	 * Statistics data provider.
	 *
	 * @since 2.0.0
	 * @var DataProvider
	 */
	private DataProvider $data;

	/**
	 * Create the statistics page.
	 *
	 * @since 2.0.0
	 * @param Options $options Plugin settings repository.
	 * @param Cache   $cache   Cache service.
	 */
	public function __construct( Options $options, Cache $cache ) {
		$this->options = $options;
		$this->data    = new DataProvider( $cache );
	}

	/**
	 * Render the statistics page.
	 *
	 * @since 2.0.0
	 * @since 2.3.0 Prepared comparison and display-type data for the advanced dashboard.
	 */
	public function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$is_premium       = FeatureGate::can_use_statistics_dashboard();
		$tracking_enabled = (bool) $this->options->get( 'enable_click_tracking', true );
		$end_date         = gmdate( 'Y-m-d' );
		$start_date_30    = gmdate( 'Y-m-d', strtotime( '-30 days' ) );
		$start_date_7     = gmdate( 'Y-m-d', strtotime( '-7 days' ) );
		$start_date_60    = gmdate( 'Y-m-d', strtotime( '-60 days' ) );
		$start_date_31    = gmdate( 'Y-m-d', strtotime( '-31 days' ) );

		$summary_30  = $tracking_enabled ? $this->data->get_summary( $start_date_30, $end_date ) : [];
		$summary_7   = $tracking_enabled ? $this->data->get_summary( $start_date_7, $end_date ) : [];
		$top_posts   = $tracking_enabled ? $this->data->get_top_clicked( $start_date_30, $end_date, 10 ) : [];
		$top_sources = $tracking_enabled ? $this->data->get_top_sources( $start_date_30, $end_date, 10 ) : [];
		$daily       = $tracking_enabled ? $this->data->get_daily_counts( $start_date_30, $end_date ) : [];
		$total_rows  = $tracking_enabled ? $this->data->get_total_rows() : 0;

		$export_url = $is_premium
			? wp_nonce_url(
				add_query_arg(
					[
						'action'     => 'relatedly_export_csv',
						'start_date' => $start_date_30,
						'end_date'   => $end_date,
					],
					admin_url( 'admin-post.php' )
				),
				'relatedly_export_csv'
			)
			: '';

		include RELATEDLY_PLUGIN_DIR . 'templates/admin/statistics-page.php';
	}
}
