<?php
/**
 * Analytics REST Controller
 *
 * REST API endpoints for analytics and reporting.
 *
 * @package DonorCore\API
 */

namespace DonorCore\API;

defined( 'ABSPATH' ) || exit;

/**
 * Analytics Controller Class
 */
class Analytics_Controller extends REST_Controller_Base {

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'analytics';

	/**
	 * Donation repository.
	 *
	 * @var \DonorCore\Database\Donation_Log_Repository
	 */
	private $donation_repo;

	/**
	 * Analytics repository.
	 *
	 * @var \DonorCore\Database\Donor_Analytics_Repository
	 */
	private $analytics_repo;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->donation_repo  = new \DonorCore\Database\Donation_Log_Repository();
		$this->analytics_repo = new \DonorCore\Database\Donor_Analytics_Repository();
	}

	/**
	 * Register routes.
	 */
	public function register_routes() {
		// Dashboard overview.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/overview',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_overview' ),
				'permission_callback' => array( $this, 'check_write_permissions' ),
			)
		);

		// Top donors.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/donors/top',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_top_donors' ),
				'permission_callback' => array( $this, 'check_write_permissions' ),
			)
		);

		// Timeline data.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/timeline',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_timeline' ),
				'permission_callback' => array( $this, 'check_write_permissions' ),
			)
		);
	}

	/**
	 * Get dashboard overview stats.
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response
	 */
	public function get_overview( $request ) {
		global $wpdb;

		$logs_table = $wpdb->prefix . 'donorcore_donation_logs';

		// Total donations.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table aggregate query
		$total_donations = $wpdb->get_var(
			$wpdb->prepare( 'SELECT SUM(amount) FROM %i', $logs_table )
		);

		// Total donors.
		$total_donors = $this->analytics_repo->get_total_donor_count();

		// Active campaigns count.
		$active_campaigns = wp_count_posts( 'donorcore_campaign' )->publish;

		// This month's revenue.
		$month_start = gmdate( 'Y-m-01 00:00:00' );
		$month_end   = gmdate( 'Y-m-t 23:59:59' );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query prepared with %i
		$month_revenue = $wpdb->get_var(
			$wpdb->prepare(
				'SELECT SUM(amount) FROM %i WHERE created_at BETWEEN %s AND %s',
				$logs_table,
				$month_start,
				$month_end
			)
		);

		$result = array(
			'total_raised'     => floatval( $total_donations ),
			'total_donors'     => intval( $total_donors ),
			'active_campaigns' => intval( $active_campaigns ),
			'month_revenue'    => floatval( $month_revenue ),
		);
		
		return $this->success( $result );
	}

	/**
	 * Get top donors.
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response
	 */
	public function get_top_donors( $request ) {
		$limit  = absint( $request->get_param( 'limit' ) ?: 10 );
		$donors = $this->analytics_repo->get_top_donors( $limit );

		return $this->success( $donors );
	}

	/**
	 * Get donation timeline.
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response
	 */
	public function get_timeline( $request ) {
		$days = absint( $request->get_param( 'days' ) ?: 30 );
		$data = $this->donation_repo->get_donations_by_day( $days );

		return $this->success( $data );
	}
}
