<?php
/**
 * Dashboard Controller
 */

namespace RadiusTheme\RadiusBooking\Controllers;

use RadiusTheme\RadiusBooking\Core\Api\ApiResponse;
use RadiusTheme\RadiusBooking\Core\Api\Middleware\AuthMiddleware;
use RadiusTheme\RadiusBooking\Core\Api\Middleware\PermissionMiddleware;
use RadiusTheme\RadiusBooking\Core\Container\Container;
use RadiusTheme\RadiusBooking\Models\Appointment;
use RadiusTheme\RadiusBooking\Models\Payment;
use RadiusTheme\RadiusBooking\Models\Service;
use RadiusTheme\RadiusBooking\Models\User;
use RadiusTheme\RadiusBooking\Resources\AppointmentResource;
use RadiusTheme\RadiusBooking\Services\AppointmentService;
use RadiusTheme\RadiusBooking\Services\DashboardService;
use WP_REST_Request;
use RadiusTheme\RadiusBooking\Abstracts\BaseController;
use RadiusTheme\RadiusBooking\Core\Api\Validation\Rules\RequiredRule;
use RadiusTheme\RadiusBooking\Core\Api\Validation\Rules\IntegerRule;
use RadiusTheme\RadiusBooking\Repositories\DashboardRepository;
use RadiusTheme\RadiusBooking\Resources\DashboardResource;
use function Clue\StreamFilter\fun;
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Api/Controllers/DashboardController.php
 * Dashboard API controller
 */
class DashboardController extends BaseController {

	/**
	 * DashboardController constructor.
	 */
	public function __construct() {
		parent::__construct( new DashboardRepository() );
		$this->middleware[] = new AuthMiddleware();
		$this->middleware[] = new PermissionMiddleware( 'manage_options' );
	}

	/**
	 * Transforms a given item using the DashboardResource's transformation logic.
	 *
	 * @param mixed $item The item to transform.
	 *
	 * @return array The transformed item as an associative array.
	 */
	protected function transformItem( $item ): array {
		return ( new DashboardResource() )->transform( $item );
	}

	/**
	 * Transforms a collection of items into a resource collection.
	 *
	 * @param array $items The array of items to be transformed.
	 *
	 * @return array The transformed resource collection.
	 */
	protected function transformCollection( array $items ): array {
		return DashboardResource::collection( $items );
	}

	/**
	 * Retrieves the validation rules based on the request and context.
	 *
	 * @param mixed $request The request object or input from which the validation rules are determined.
	 * @param string $context The context in which the rules are being applied, e.g., 'create' or 'update'. Defaults to 'create'.
	 *
	 * @return array An array of validation rules based on the provided request and context.
	 */
	protected function getValidationRules( $request, string $context = 'create' ): array {
		$rules = array();
		return $rules;
	}

	/**
	 * Retrieves the resource type for this controller.
	 *
	 * @return string The resource type, which is 'user' in this case.
	 */
	protected function getResourceType(): string {
		return 'dashboard';
	}

	/**
	 * Handles the total report generation request and returns aggregated data.
	 *
	 * @param WP_REST_Request $request The REST request object containing request data.
	 *
	 * @return mixed The response generated by applying middleware and processing the request.
	 */
	public function totalReport( WP_REST_Request $request ) {
		return $this->applyMiddleware(
			$request,
			function () {

				$total_appointment = Appointment::totalAppointment();
				$total_customer    = User::totalCustomer();
				$total_employee    = User::totalEmployee();
				$total_revenue     = Payment::totalRevenue();
				$data              = array(
					'total_customer'    => $total_customer,
					'total_appointment' => $total_appointment,
					'total_employee'    => $total_employee,
					'total_revenue'     => $total_revenue,
					'currency_symbol'   => get_rtrb_currency_symbol(),
					'currency'          => get_rtrb_currency(),
				);

				return ApiResponse::success(
					$data
				)->send();
			}
		);
	}

	/**
	 * Handles the retrieval of upcoming appointments.
	 *
	 * @param WP_REST_Request $request The REST request object containing the input parameters, including an optional 'limit' parameter to specify the number of appointments to fetch.
	 */
	public function upcomingAppointment( WP_REST_Request $request ) {
		return $this->applyMiddleware(
			$request,
			function ( $request ) {
				$limit        = $request->get_param( 'limit' ) ?: 10; //phpcs:ignore
				$service      = Container::resolve( AppointmentService::class );
				$appointments = $service->getUpcomingAppointments( $limit );
				$upComing     = [];
				$upComing['currency']     = [
					'currency' => get_rtrb_currency(),
					'currency_symbol' => get_rtrb_currency_symbol(),
				];
				$upComing['data'] = $service->getUpcomingAppointmentsWithFormat( AppointmentResource::collection( $appointments ) );;
				return ApiResponse::success( $upComing )->send();
			}
		);
	}

	/**
	 * Generates and returns today's report for the dashboard.
	 *
	 * @param WP_REST_Request $request The REST request object containing the input parameters needed for generating the daily report.
	 */
	public function todayReport( WP_REST_Request $request ) {
		return $this->applyMiddleware(
			$request,
			function () {
				$today    = gmdate( 'Y-m-d' );
				$day_date = gmdate( 'Y-m-d', strtotime( $today ) );

				$appointment_service = Container::resolve( AppointmentService::class );
				$todayReport         = $appointment_service->dailyOverviewForDashboard( $day_date );
				return ApiResponse::success( $todayReport )->send();
			}
		);
	}

	/**
	 * Handles the retrieval of recent activities.
	 *
	 * @param WP_REST_Request $request The REST request object used to initiate and authorize the request for recent activity data.
	 */
	public function recentActivity( WP_REST_Request $request ) {
		return $this->applyMiddleware(
			$request,
			function () {
				$dashboard_service = Container::resolve( DashboardService::class );
				$recentActivities  = $dashboard_service->getRecentActivities();
				return ApiResponse::success( $recentActivities )->send();
			}
		);
	}

	/**
	 * Retrieves appointment statistics based on a specified time period.
	 *
	 * @param WP_REST_Request $request The REST request object containing the input parameters, including a 'period' parameter to specify the statistical view (e.g., month, week, yearly).
	 */
	public function appointmentStatistics( WP_REST_Request $request ) {
		return $this->applyMiddleware(
			$request,
			function ( $request ) {
				$view              = $request->get_param( 'period' ); // month | week | yearly
				$dashboard_service = Container::resolve( DashboardService::class );
				$statistics        = $dashboard_service->getStatistics( $view );
				return ApiResponse::success( $statistics )->send();
			}
		);
	}

	/**
	 * Retrieves revenue statistics based on the specified period.
	 *
	 * @param WP_REST_Request $request The REST request object containing the input parameters, including a 'period' parameter to specify the period for the statistics (e.g., month, week, yearly).
	 */
	public function revenueStatistics( WP_REST_Request $request ) {
		return $this->applyMiddleware(
			$request,
			function ( $request ) {
				$view              = $request->get_param( 'period' ); // month | week | yearly
				$dashboard_service = Container::resolve( DashboardService::class );
				$statistics = $dashboard_service->getRevenue( $view );
				return ApiResponse::success( $statistics )->send();
			}
		);
	}
}
