<?php
/**
 * Analytics Rest API.
 *
 * @since 1.3.9
 * @package tripzzy
 */

namespace Tripzzy\Core\RestApis;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

use Tripzzy\Core\Bases\RestApiBase;
use Tripzzy\Core\Helpers\Analytics;
use Tripzzy\Core\Helpers\MetaHelpers;
use Tripzzy\Core\Payment;
use Tripzzy\Core\Helpers\Amount;

if ( ! class_exists( 'Tripzzy\Core\RestApis\AnalyticsRestApi' ) ) {
	/**
	 * Analytics Rest API Class.
	 *
	 * @since 1.3.9
	 */
	class AnalyticsRestApi extends RestApiBase {

		/**
		 * API Name space
		 *
		 * @var string
		 */
		protected static $api_namespace = 'tripzzy/v1';

		/**
		 * Constructor.
		 */
		public function __construct() {
			add_filter( 'tripzzy_filter_rest_api_args', array( $this, 'init_args' ) );
		}

		/**
		 * Rest API arguments.
		 *
		 * $args = array( 'route_name' => $route_args );
		 *
		 * @since 1.3.9
		 */
		protected static function api_args() {
			$args = array(
				'/analytics/overview'  => array(
					array(
						'methods'             => \WP_REST_Server::READABLE,
						'callback'            => array( __CLASS__, 'get_overview_data' ),
						'permission_callback' => array( __CLASS__, 'get_permissions' ),
					),
				),
				'/analytics/trips'     => array(
					array(
						'methods'             => \WP_REST_Server::READABLE,
						'callback'            => array( __CLASS__, 'get_trips_data' ),
						'permission_callback' => array( __CLASS__, 'get_permissions' ),
					),
				),
				'/analytics/customers' => array(
					array(
						'methods'             => \WP_REST_Server::READABLE,
						'callback'            => array( __CLASS__, 'get_customers_data' ),
						'permission_callback' => array( __CLASS__, 'get_permissions' ),
					),
				),
			);
			return $args;
		}

		/**
		 * Check permissions.
		 *
		 * @since 1.3.9
		 */
		public static function get_permissions() {
			return apply_filters( 'tripzzy_filter_analytics_rest_api_permission', current_user_can( 'manage_options' ) );
		}

		/**
		 * Get Overview Data.
		 *
		 * @since 1.3.9
		 * @param object $request Http Request.
		 */
		public static function get_overview_data( $request ) {
			$analytics = new Analytics();

			$_GET['start_date'] = $request->get_param( 'start_date' );
			$_GET['end_date']   = $request->get_param( 'end_date' );
			$_GET['compare_to'] = $request->get_param( 'compare_to' );

			$stats = $analytics->get_stats();
			return rest_ensure_response( $stats );
		}

		/**
		 * Get Trips Data.
		 *
		 * @since 1.3.9
		 * @param object $request Http Request.
		 */
		public static function get_trips_data( $request ) {
			$_GET['start_date'] = $request->get_param( 'start_date' );
			$_GET['end_date']   = $request->get_param( 'end_date' );

			$analytics     = new Analytics();
			$stats         = $analytics->get_stats();
			$popular_trips = $stats['popular_trips'];
			$data          = array();
			foreach ( $popular_trips as $trip_id => $count ) {
				$data[] = array(
					'id'    => $trip_id,
					'title' => get_the_title( $trip_id ),
					'count' => $count,
				);
			}
			return rest_ensure_response( $data );
		}

		/**
		 * Get Customer Data.
		 *
		 * @since 1.3.9
		 * @param object $request Http Request.
		 */
		public static function get_customers_data( $request ) {
			$args = array(
				'post_type'      => 'tripzzy_booking',
				'posts_per_page' => -1,
				'post_status'    => 'publish',
			);

			$start_date = $request->get_param( 'start_date' );
			$end_date   = $request->get_param( 'end_date' );

			if ( ! empty( $start_date ) && ! empty( $end_date ) ) {
				$args['date_query'] = array(
					array(
						'after'     => $start_date,
						'before'    => $end_date,
						'inclusive' => true,
					),
				);
			}

			$bookings  = get_posts( $args );
			$customers = array();

			foreach ( $bookings as $booking ) {
				$booking_id    = $booking->ID;
				$checkout_info = MetaHelpers::get_post_meta( $booking_id, 'checkout_info' );
				$email         = $checkout_info['billing_email'] ?? '';

				if ( ! $email ) {
					continue;
				}

				if ( ! isset( $customers[ $email ] ) ) {
					$customers[ $email ] = array(
						'name'           => trim( ( $checkout_info['billing_first_name'] ?? '' ) . ' ' . ( $checkout_info['billing_last_name'] ?? '' ) ),
						'email'          => $email,
						'bookings_count' => 0,
						'total_spent'    => 0,
					);
				}

				++$customers[ $email ]['bookings_count'];
				$customers[ $email ]['total_spent'] += Payment::get_total( $booking_id );
			}

			// Format total spent.
			foreach ( $customers as &$customer ) {
				$customer['formatted_total_spent'] = Amount::display( $customer['total_spent'] );
			}

			return rest_ensure_response( array_values( $customers ) );
		}
	}
}
