<?php
/**
 * PostAnalytics AJAX handler
 *
 * Returns per-post related-post analytics for the statistics modal.
 *
 * @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 post-level analytics over AJAX.
 *
 * @since 2.3.0
 */
class PostAnalytics {

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

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

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

	/**
	 * Return analytics for a single post.
	 *
	 * @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' => __( 'Post analytics are available with a paid plan.', 'relatedly' ) ] );
		}

		$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
		$start   = sanitize_text_field( wp_unslash( $_POST['start_date'] ?? gmdate( 'Y-m-d', strtotime( '-30 days' ) ) ) );
		$end     = sanitize_text_field( wp_unslash( $_POST['end_date'] ?? gmdate( 'Y-m-d' ) ) );

		if ( ! $post_id ) {
			wp_send_json_error( [ 'message' => __( 'Invalid post ID.', 'relatedly' ) ] );
		}

		wp_send_json_success(
			$this->data->get_post_analytics( $post_id, $start, $end )
		);
	}
}
