<?php

namespace AcademyProCalendar\Ajax;

use AcademyProCalendar\Events\{
	Mettings\MeetingData,
	Booking\Tutor
};

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class EventData {

	public static function init() : void {
		$ins = new self();

		add_action(
			'wp_ajax_academy_pro_calendar/get_events_data',
			[ $ins, 'get_events_data' ]
		);
	}

	public function get_events_data(): void {
		check_ajax_referer( 'academy_nonce', 'security' );
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		$year = abs( intval( sanitize_text_field( $_REQUEST['year'] ) ) );
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		$month = abs( intval( sanitize_text_field( $_REQUEST['month'] ) ) );
		if (
			empty( $year ) ||
			empty( $month )
		) {
			wp_send_json_error([
				'message' => __( 'year & month field is required.', 'academy-pro' )
			]);
		}

		$output = MeetingData::get( $year, $month ) ?? [];
		$output['booking'] = ( new Tutor( $year, $month ) )->get_events_data();

		foreach ( $output['booking']['data'] as $key => $data ) {
			$start_date = ( new \DateTime(
				$data['start_date']
			) )->format( 'c' );
			$output['booking']['data'][ $key ]['start_date'] = $start_date;

			$output['booking']['data'][ $key ]['end_date']  = ( new \DateTime(
				$start_date
			) )->modify( "+{$data['duration']} Minutes" )->format( 'c' );
			$output['booking']['data'][ $key ]['duration'] = sprintf(
				'%d %s',
				$data['duration'],
				__( 'min', 'academy-pro' ),
			);

		}
		wp_send_json_error( $output );
	}
}
