<?php

namespace TotalPoll\Admin\Ajax;
! defined( 'ABSPATH' ) && exit();


use TotalPoll\Contracts\Log\Repository as LogRepository;
use TotalPoll\Contracts\Poll\Model;
use TotalPoll\Contracts\Poll\Repository as PollRepository;
use TotalPollVendors\TotalCore\Contracts\Http\Request;

/**
 * Class Insights
 * @package TotalPoll\Admin\Ajax
 * @since   1.0.0
 */
class Insights {
	/**
	 * @var Request $request
	 */
	protected $request;
	/**
	 * @var LogRepository $log
	 */
	protected $log;
	/**
	 * @var PollRepository $poll
	 */
	protected $poll;
	/**
	 * @var array $criteria
	 */
	protected $criteria = [];

	/**
	 * Insights constructor.
	 *
	 * @param Request        $request
	 * @param LogRepository  $log
	 * @param PollRepository $poll
	 */
	public function __construct( Request $request, LogRepository $log, PollRepository $poll ) {
		$this->request = $request;
		$this->log     = $log;
		$this->poll    = $poll;

		$this->criteria = [
			'poll'   => $this->request->request( 'poll', null ),
			'from'   => $this->request->request( 'from', null ),
			'to'     => $this->request->request( 'to', null ),
			'format' => $this->request->request( 'format', null ),
		];
	}

	/**
	 * Get metrics AJAX endpoint.
	 * @action-callback wp_ajax_totalpoll_insights_metrics
	 */
	public function metrics() {
		$args = [ 'conditions' => [ 'status' => 'accepted', 'action' => 'vote','date' => [] ] ];

		if ( $this->criteria['poll'] && current_user_can( 'edit_poll', $this->criteria['poll'] ) ):
			$args['conditions']['poll_id'] = $this->criteria['poll'];
		endif;

		if ( $this->criteria['from'] && strptime( $this->criteria['from'], '%Y-%m-%d 00:00:00' ) ):
			$args['conditions']['date'][] = [ 'operator' => '>=', 'value' => $this->criteria['from'] ];
		endif;

		if ( $this->criteria['to'] && strptime( $this->criteria['to'], '%Y-%m-%d 00:00:00' ) ):
			$args['conditions']['date'][] = [ 'operator' => '<=', 'value' => $this->criteria['to'] ];
		endif;

		$period = $this->log->countVotesPerPeriod( $args );

		$platforms = $this->log->countVotesPerUserAgent( $args );

		unset( $args['conditions']['status'], $args['conditions']['date'], $args['conditions']['action'] );

		$poll        = $this->poll->getById( $args['conditions']['poll_id'] );
		$choicesUids = array_keys( $poll->getChoices() );
		if ( ! empty( $choicesUids ) ):
			$args['conditions']['choice_uid'] = [ $choicesUids ];
		endif;
		$choices = $this->log->countVotesPerChoices( $args );

		$insights = [ 'period' => $period, 'choices' => $choices, 'platforms' => $platforms, ];

		/**
		 * Filters the data sent to insights browser.
		 *
		 * @param Model[] $polls    Array of poll models.
		 * @param array   $criteria Array of criteria.
		 *
		 * @since 4.0.0
		 * @return array
		 */
		$insights = apply_filters( 'totalpoll/filters/admin/insights/metrics', $insights, $this->criteria );

		wp_send_json( $insights );
	}

	/**
	 * Get polls AJAX endpoint.
	 * @action-callback wp_ajax_totalpoll_insights_polls
	 */
	public function polls() {
		$query = [ 'post_type' => TP_POLL_CPT_NAME, 'posts_per_page' => - 1 ];
		if ( ! current_user_can( 'edit_others_polls' ) ):
			$query['author'] = get_current_user_id();
		endif;

		$polls = get_posts( $query );
		$polls = array_map( function ( $poll ) {
			return [ 'id' => $poll->ID, 'title' => $poll->post_title ];
		}, $polls );

		/**
		 * Filters the polls list sent to insights browser.
		 *
		 * @param Model[] $polls Array of poll models.
		 *
		 * @since 4.0.0
		 * @return array
		 */
		$polls = apply_filters( 'totalpoll/filters/admin/insights/polls', $polls );

		wp_send_json( $polls );
	}
}