<?php
/**
 * Student dashboard shortcode.
 *
 * @package TutorHelper_Bookings
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Renders the student dashboard.
 */
final class TutorHelper_Student_Dashboard_Shortcode {

	/**
	 * Shortcode name.
	 *
	 * @var string
	 */
	const SHORTCODE =
		'tutorhelper_student_dashboard';

	/**
	 * Register shortcode hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_shortcode(
			self::SHORTCODE,
			array(
				__CLASS__,
				'render',
			)
		);
	}

	/**
	 * Render the dashboard.
	 *
	 * @return string
	 */
	public static function render() {
		if ( ! is_user_logged_in() ) {
			$login_url =
				TutorHelper_Settings::
					get_login_url();

			$dashboard_url =
				TutorHelper_Settings::
					get_student_dashboard_url();

			if ( $dashboard_url ) {
				$login_url =
					add_query_arg(
						'redirect_to',
						$dashboard_url,
						$login_url
					);
			}

			return self::render_notice(
				__(
					'Please log in to view your lessons.',
					'tutorhelper-bookings'
				),
				'warning',
				$login_url,
				__(
					'Log in',
					'tutorhelper-bookings'
				)
			);
		}

		$viewer_user_id =
			get_current_user_id();

		$student =
			TutorHelper_Students::get_student(
				$viewer_user_id
			);

		$is_student =
			$student instanceof WP_User;

		$is_tutor_preview =
			current_user_can(
				'manage_options'
			);

		if (
			! $is_student
			&& ! $is_tutor_preview
		) {
			return self::render_notice(
				__(
					'The student dashboard is only available to registered students.',
					'tutorhelper-bookings'
				),
				'warning'
			);
		}

		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only status parameter used only to render feedback after a protected action.
		$dashboard_status =
			isset(
				$_GET['tutorhelper_dashboard_status']
			)
				? sanitize_key(
					wp_unslash(
						$_GET[
							'tutorhelper_dashboard_status'
						]
					)
				)
				: '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended


		$student_user_id =
			$is_student
				? $viewer_user_id
				: 0;

		$pending =
			$is_student
				? TutorHelper_Student_Dashboard_Bookings::
					get_pending(
						$student_user_id
					)
				: array();

		$upcoming =
			$is_student
				? TutorHelper_Student_Dashboard_Bookings::
					get_upcoming(
						$student_user_id
					)
				: array();

        $past =
            $is_student
                ? TutorHelper_Student_Dashboard_Bookings::
                    get_past(
                        $student_user_id
                    )
                : array();

		TutorHelper_Student_Dashboard_Frontend::
			enqueue_assets();

		ob_start();
		?>
		<section
			class="tutorhelper-student-dashboard<?php echo $is_tutor_preview && ! $is_student ? ' tutorhelper-student-dashboard--preview' : ''; ?>"
			data-tutorhelper-student-dashboard
		>
		<?php if ( 'cancelled' === $dashboard_status ) : ?>
			<div
				class="tutorhelper-student-dashboard__notice tutorhelper-student-dashboard__notice--success"
				role="status"
			>
				<?php
				esc_html_e(
					'Your lesson has been cancelled.',
					'tutorhelper-bookings'
				);
				?>
			</div>
		<?php elseif ( 'error' === $dashboard_status ) : ?>
			<div
				class="tutorhelper-student-dashboard__notice tutorhelper-student-dashboard__notice--error"
				role="alert"
			>
				<?php
				esc_html_e(
					'That lesson could not be cancelled. Please refresh the page and check the cancellation policy.',
					'tutorhelper-bookings'
				);
				?>
			</div>
		<?php endif; ?>
			<?php if ( $is_tutor_preview && ! $is_student ) : ?>
				<div
					class="tutorhelper-student-dashboard__preview-notice"
					role="status"
				>
					<?php
					esc_html_e(
						'Preview mode: lesson data is hidden because this administrator account is not a student.',
						'tutorhelper-bookings'
					);
					?>
				</div>
			<?php endif; ?>

			<header
				class="tutorhelper-student-dashboard__header"
			>
				<p
					class="tutorhelper-student-dashboard__eyebrow"
				>
					<?php
					esc_html_e(
						'Student dashboard',
						'tutorhelper-bookings'
					);
					?>
				</p>

				<h2
					class="tutorhelper-student-dashboard__heading"
				>
					<?php
					esc_html_e(
						'My lessons',
						'tutorhelper-bookings'
					);
					?>
				</h2>

				<p
					class="tutorhelper-student-dashboard__introduction"
				>
					<?php
					esc_html_e(
						'View lesson requests awaiting approval, upcoming lessons and your lesson history.',
						'tutorhelper-bookings'
					);
					?>
				</p>
			</header>

			<div
				class="tutorhelper-student-dashboard__sections"
			>
				<?php
				self::render_booking_section(
					__(
						'Pending lesson requests',
						'tutorhelper-bookings'
					),
					__(
						'Requests waiting for your tutor to confirm.',
						'tutorhelper-bookings'
					),
					$pending,
					__(
						'You do not have any lesson requests awaiting confirmation.',
						'tutorhelper-bookings'
					),
					'pending'
				);

				self::render_booking_section(
					__(
						'Upcoming lessons',
						'tutorhelper-bookings'
					),
					__(
						'Your future lessons, including any that have been cancelled.',
						'tutorhelper-bookings'
					),
					$upcoming,
					__(
						'You do not have any future lessons booked at the moment.',
						'tutorhelper-bookings'
					),
					'confirmed'
				);

                self::render_booking_section(
                    __(
                        'Past lessons',
                        'tutorhelper-bookings'
                    ),
                    __(
                        'Your previous lessons and booking history, with the most recent first.',
                        'tutorhelper-bookings'
                    ),
                    $past,
                    __(
                        'You do not have any past lessons yet.',
                        'tutorhelper-bookings'
                    ),
                    'past'
                );

				?>
			</div>
		</section>
		<?php

		return ob_get_clean();
	}

	/**
	 * Render one booking section.
	 *
	 * @param string $heading       Section heading.
	 * @param string $description   Section description.
	 * @param array  $bookings      Prepared bookings.
	 * @param string $empty_message Empty-state message.
	 * @param string $section_type  Section key.
	 *
	 * @return void
	 */
	private static function render_booking_section(
		$heading,
		$description,
		$bookings,
		$empty_message,
		$section_type
	) {
		?>
		<section
			class="tutorhelper-student-dashboard__section tutorhelper-student-dashboard__section--<?php echo esc_attr( $section_type ); ?>"
		>
			<header
				class="tutorhelper-student-dashboard__section-header"
			>
				<div>
					<h3>
						<?php echo esc_html( $heading ); ?>
					</h3>

					<p>
						<?php echo esc_html( $description ); ?>
					</p>
				</div>

				<span
					class="tutorhelper-student-dashboard__count"
					aria-label="<?php echo esc_attr(
						sprintf(
							/* translators: %d: number of lessons. */
							_n(
								'%d lesson',
								'%d lessons',
								count( $bookings ),
								'tutorhelper-bookings'
							),
							count( $bookings )
						)
					); ?>"
				>
					<?php echo esc_html( count( $bookings ) ); ?>
				</span>
			</header>

			<?php if ( empty( $bookings ) ) : ?>
				<div
					class="tutorhelper-student-dashboard__empty"
				>
					<p>
						<?php echo esc_html( $empty_message ); ?>
					</p>
				</div>
			<?php else : ?>
				<div
					class="tutorhelper-student-dashboard__cards"
				>
					<?php
					foreach ( $bookings as $booking ) {
						self::render_booking_card(
                            $booking,
                            $section_type
                        );
					}
					?>
				</div>
			<?php endif; ?>
		</section>
		<?php
	}

	/**
     * Render one lesson card.
     *
     * @param array  $booking      Prepared booking.
     * @param string $section_type Dashboard section key.
     *
     * @return void
     */
    private static function render_booking_card(
        $booking,
        $section_type
    ) {
	$section_type =
		sanitize_key( $section_type );
		$start =
			$booking['start'];

		$end =
			$booking['end'];

		$date_label =
			wp_date(
				'l j F Y',
				$start->getTimestamp(),
				$start->getTimezone()
			);

		$time_label =
			sprintf(
				'%1$s–%2$s',
				wp_date(
					get_option(
						'time_format'
					),
					$start->getTimestamp(),
					$start->getTimezone()
				),
				wp_date(
					get_option(
						'time_format'
					),
					$end->getTimestamp(),
					$end->getTimezone()
				)
			);
		?>
		<article
            class="tutorhelper-student-dashboard__card tutorhelper-student-dashboard__card--<?php echo esc_attr( $section_type ); ?> tutorhelper-student-dashboard__card-status--<?php echo esc_attr( $booking['status'] ); ?>"
            style="--tutorhelper-booking-type-colour: <?php echo esc_attr( $booking['colour'] ); ?>;"
        >
                    <div
                class="tutorhelper-student-dashboard__card-header"
            >
                <div
                    class="tutorhelper-student-dashboard__card-top"
                >
				<div>
					<p
						class="tutorhelper-student-dashboard__date"
					>
						<?php echo esc_html( $date_label ); ?>
					</p>

					<h4>
						<?php echo esc_html( $booking['title'] ); ?>
					</h4>
				</div>

				<span
					class="tutorhelper-student-dashboard__status tutorhelper-student-dashboard__status--<?php echo esc_attr( $booking['status'] ); ?>"
				>
					<?php
					echo esc_html(
						$booking['status_label']
					);
					?>
				</span>
            </div>
        </div>

        <dl
            class="tutorhelper-student-dashboard__details"
        >
				<div>
					<dt>
						<?php
						esc_html_e(
							'Time',
							'tutorhelper-bookings'
						);
						?>
					</dt>

					<dd>
						<?php echo esc_html( $time_label ); ?>
					</dd>
				</div>

				<div>
					<dt>
						<?php
						esc_html_e(
							'Location',
							'tutorhelper-bookings'
						);
						?>
					</dt>

					<dd>
						<?php
						echo esc_html(
							$booking[
								'location_label'
							]
						);
						?>
					</dd>
				</div>
			</dl>

			<?php
			if (
				TutorHelper_Booking_Records::STATUS_CANCELLED
				=== $booking['status']
				&& ! empty(
					$booking['cancellation_reason']
				)
			) :
				?>
				<div
					class="tutorhelper-student-dashboard__cancellation-reason"
				>
					<h5>
						<?php
						if (
							isset(
								$booking['cancelled_by']
							)
							&& 'tutor'
							=== $booking['cancelled_by']
						) {
							esc_html_e(
								'Message from your tutor',
								'tutorhelper-bookings'
							);
						} else {
							esc_html_e(
								'Cancellation reason',
								'tutorhelper-bookings'
							);
						}
						?>
					</h5>
					<p>
						<?php
						echo esc_html(
							$booking[
								'cancellation_reason'
							]
						);
						?>
					</p>
				</div>
			<?php endif; ?>

            <?php
            if (
                'confirmed' === $section_type
                && TutorHelper_Booking_Records::STATUS_CONFIRMED
                    === $booking['status']
                && ! empty(
                    $booking['location_details']
                )
            ) :
                ?>
                <div
                    class="tutorhelper-student-dashboard__joining-details"
                >
                    <h5>
                        <?php
                        esc_html_e(
                            'How to join',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </h5>

                    <div>
                        <?php
                        echo wp_kses_post(
                            wpautop(
                                make_clickable(
                                    esc_html(
                                        $booking[
                                            'location_details'
                                        ]
                                    )
                                )
                            )
                        );
                        ?>
                    </div>
                </div>
            <?php endif; ?>

			<?php
			if (
				in_array(
					$section_type,
					array(
						'pending',
						'confirmed',
					),
					true
				)
			) :
				?>
				<div
					class="tutorhelper-student-dashboard__card-actions"
				>

				<?php
				/**
				 * Render additional actions for a student dashboard booking.
				 *
				 * Extensions can use this action to add contextual booking
				 * actions without changing Core dashboard behaviour.
				 *
				 * @param array  $booking      Prepared booking data.
				 * @param string $section_type Dashboard section key.
				 */
				do_action(
					'tutorhelper_student_dashboard_booking_actions',
					$booking,
					$section_type
				);
				?>
					<?php
					if (
						! empty(
							$booking[
								'cancellation'
							][
								'can_cancel'
							]
						)
					) :
						?>
						<form
							method="post"
							action="<?php echo esc_url(
								admin_url(
									'admin-post.php'
								)
							); ?>"
						>
							<input
								type="hidden"
								name="action"
								value="<?php echo esc_attr(
									TutorHelper_Student_Dashboard_Actions::
										CANCEL_ACTION
								); ?>"
							/>

							<input
								type="hidden"
								name="booking_id"
								value="<?php echo esc_attr(
									$booking['id']
								); ?>"
							/>

							<details
								class="tutorhelper-student-dashboard__cancel-panel"
							>
								<summary
									class="tutorhelper-student-dashboard__cancel-toggle"
								>
									<?php
									esc_html_e(
										'Cancel lesson',
										'tutorhelper-bookings'
									);
									?>
								</summary>

								<form
									method="post"
									action="<?php echo esc_url(
										admin_url(
											'admin-post.php'
										)
									); ?>"
									class="tutorhelper-student-dashboard__cancellation-form"
								>
									<input
										type="hidden"
										name="action"
										value="<?php echo esc_attr(
											TutorHelper_Student_Dashboard_Actions::
												CANCEL_ACTION
										); ?>"
									/>

									<input
										type="hidden"
										name="booking_id"
										value="<?php echo esc_attr(
											$booking['id']
										); ?>"
									/>

									<?php
									wp_nonce_field(
										TutorHelper_Student_Dashboard_Actions::
											CANCEL_ACTION
											. '_'
											. $booking['id']
									);
									?>

									<label
										for="tutorhelper-cancellation-reason-<?php echo esc_attr(
											$booking['id']
										); ?>"
									>
										<?php
										esc_html_e(
											'Why are you cancelling?',
											'tutorhelper-bookings'
										);
										?>
									</label>

									<p
										class="tutorhelper-student-dashboard__cancellation-help"
									>
										<?php
										esc_html_e(
											'Please briefly let your tutor know why you cannot attend.',
											'tutorhelper-bookings'
										);
										?>
									</p>

									<textarea
										id="tutorhelper-cancellation-reason-<?php echo esc_attr(
											$booking['id']
										); ?>"
										name="cancellation_reason"
										rows="3"
										maxlength="500"
										required
									></textarea>

									<button
										type="submit"
										class="tutorhelper-student-dashboard__cancel-confirm"
									>
										<?php
										esc_html_e(
											'Confirm cancellation',
											'tutorhelper-bookings'
										);
										?>
									</button>
								</form>
							</details>


					<?php elseif (
						! empty(
							$booking[
								'cancellation'
							][
								'message'
							]
						)
					) : ?>
						<p
							class="tutorhelper-student-dashboard__cancellation-note"
						>
							<?php
							echo esc_html(
								$booking[
									'cancellation'
								][
									'message'
								]
							);
							?>
						</p>
					<?php endif; ?>
				</div>
			<?php endif; ?>

            </article>
		<?php
	}

	/**
	 * Render an access notice.
	 *
	 * @param string $message Notice message.
	 * @param string $type    Notice type.
	 *
	 * @return string
	 */
	private static function render_notice(
		$message,
		$type = 'info',
		$action_url = '',
		$action_label = ''
	) {
		$action_html = '';

		if (
			$action_url
			&& $action_label
		) {
			$action_html =
				sprintf(
					'<p><a class="tutorhelper-student-booking-notice__action" href="%1$s">%2$s</a></p>',
					esc_url(
						$action_url
					),
					esc_html(
						$action_label
					)
				);
		}

		return sprintf(
			'<div class="tutorhelper-student-booking-notice tutorhelper-student-booking-notice--%1$s" role="status"><p>%2$s</p>%3$s</div>',
			esc_attr(
				sanitize_html_class(
					$type
				)
			),
			esc_html(
				$message
			),
			$action_html
		);
	}
}
