<?php

declare(strict_types=1);

namespace AllCoach\Frontend\Controllers;

defined( 'ABSPATH' ) || exit;

use AllCoach\Application\Booking\SessionBookingQueryService;
use AllCoach\Application\Order\OrderQueryService;
use AllCoach\Domain\Booking\SessionBookingFilter;
use AllCoach\Domain\Order\OrderFilter;
use AllCoach\Domain\Session\SessionRepository;
use AllCoach\Support\TemplateLoader;

class DashboardController extends BaseController {

	public function __construct(
		TemplateLoader $templateLoader,
		private readonly OrderQueryService $orderQueryService,
		private readonly SessionBookingQueryService $bookingQueryService,
		private readonly SessionRepository $sessionRepository,
	) {
		parent::__construct( $templateLoader );
	}

	public function index(): void {
		$user  = wp_get_current_user();
		$today = wp_date( 'Y-m-d' );

		$enrollments = $this->orderQueryService->findWithFilter(
			new OrderFilter( clientId: $user->ID ),
			1,
			50
		);

		$todayBookings = $this->bookingQueryService->findWithFilter(
			new SessionBookingFilter(
				clientId: $user->ID,
				fromDate: $today,
				toDate: $today,
				excludeCancelled: true
			),
			1,
			10
		);

		$progressMap = [];
		foreach ( $enrollments as $enrollment ) {
			if ( $enrollment->status !== 'confirmed' ) {
				continue;
			}

			$session       = $this->sessionRepository->findOneByProgramId( $enrollment->programId );
			$totalSessions = $session ? $session->getRepetitionCount() : 0;

			$progressMap[ $enrollment->programId ] = $this->bookingQueryService->getProgress(
				$enrollment->enrollmentId,
				$totalSessions
			);
		}

		$this->render(
			'dashboard/index.php',
			[
				'pageTitle'     => __( 'Dashboard', 'allcoach' ),
				'enrollments'   => $enrollments,
				'todayBookings' => $todayBookings,
				'progressMap'   => $progressMap,
				'today'         => $today,
			]
		);
	}
}
