<?php
/**
 * ComparisonData AJAX handler
 *
 * Returns period-over-period comparison data for the statistics page.
 *
 * @package Relatedly\Admin\Ajax
 * @since   2.3.0
 */

namespace Relatedly\Admin\Ajax;

use Relatedly\Core\Cache;
use Relatedly\Admin\Statistics\DataProvider;
use Relatedly\Premium\FeatureGate;

defined( 'ABSPATH' ) || exit;

/**
 * Returns period comparison data over AJAX.
 *
 * @since 2.3.0
 */
class ComparisonData {

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

	/**
	 * Create the comparison AJAX handler.
	 *
	 * @since 2.3.0
	 * @param Cache $cache Cache service.
	 */
	public function __construct( Cache $cache ) {
		$this->data = new DataProvider( $cache );
	}

	/**
	 * Register the comparison AJAX action.
	 *
	 * @since 2.3.0
	 */
	public function init_hooks(): void {
		add_action( 'wp_ajax_relatedly_get_comparison', [ $this, 'handle' ] );
	}

	/**
	 * Return comparison between two date ranges.
	 *
	 * @since 2.3.0
	 */
	public function handle(): void {
		check_ajax_referer( 'relatedly_statistics', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'relatedly' ) ] );
		}

		if ( ! FeatureGate::can_use_statistics_dashboard() ) {
			wp_send_json_error( [ 'message' => __( 'Period comparison is available with a paid plan.', 'relatedly' ) ] );
		}

		$period1_start = sanitize_text_field( wp_unslash( $_POST['period1_start'] ?? '' ) );
		$period1_end   = sanitize_text_field( wp_unslash( $_POST['period1_end'] ?? '' ) );
		$period2_start = sanitize_text_field( wp_unslash( $_POST['period2_start'] ?? '' ) );
		$period2_end   = sanitize_text_field( wp_unslash( $_POST['period2_end'] ?? '' ) );

		if ( ! $period1_start || ! $period1_end || ! $period2_start || ! $period2_end ) {
			wp_send_json_error( [ 'message' => __( 'Invalid date ranges.', 'relatedly' ) ] );
		}

		wp_send_json_success(
			$this->data->get_comparison( $period1_start, $period1_end, $period2_start, $period2_end )
		);
	}
}
