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

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

/**
 * Handles student dashboard form actions.
 */
final class TutorHelper_Student_Dashboard_Actions {

	/**
	 * Cancellation action.
	 *
	 * @var string
	 */
	const CANCEL_ACTION =
		'tutorhelper_student_cancel_booking';

	/**
	 * Initialise actions.
	 *
	 * @return void
	 */
	public static function init() {
		add_action(
			'admin_post_' . self::CANCEL_ACTION,
			array(
				__CLASS__,
				'handle_cancel',
			)
		);
	}

	/**
	 * Cancel one student's booking.
	 *
	 * @return void
	 */
	public static function handle_cancel() {
		if ( ! is_user_logged_in() ) {
			$login_url =
				TutorHelper_Settings::
					get_login_url();

			$dashboard_url =
				TutorHelper_Settings::
					get_student_dashboard_url();

			if ( '' === $dashboard_url ) {
				$dashboard_url =
					home_url( '/' );
			}

			$login_url =
				add_query_arg(
					'redirect_to',
					$dashboard_url,
					$login_url
				);

			wp_safe_redirect(
				$login_url
			);

			exit;
		}

		$student_user_id =
			get_current_user_id();

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

		if ( ! $student instanceof WP_User ) {
			wp_die(
				esc_html__(
					'You do not have permission to cancel this booking.',
					'tutorhelper-bookings'
				),
				esc_html__(
					'Permission denied',
					'tutorhelper-bookings'
				),
				array(
					'response' => 403,
				)
			);
		}

		$booking_id =
			isset( $_POST['booking_id'] )
				? absint(
					wp_unslash(
						$_POST['booking_id']
					)
				)
				: 0;

		check_admin_referer(
			self::CANCEL_ACTION
				. '_'
				. $booking_id
		);

		$allowed =
			TutorHelper_Student_Dashboard_Bookings::
				can_student_cancel(
					$booking_id,
					$student_user_id
				);

		if ( is_wp_error( $allowed ) ) {
			self::redirect(
				'error',
				$allowed->get_error_code()
			);
		}

		$cancellation_reason =
            isset( $_POST['cancellation_reason'] )
                ? sanitize_textarea_field(
                    wp_unslash(
                        $_POST['cancellation_reason']
                    )
                )
                : '';

        $cancellation_reason =
            trim( $cancellation_reason );

        if ( '' === $cancellation_reason ) {
            self::redirect(
                'error',
                'tutorhelper_student_cancel_reason_required'
            );
        }

        if ( function_exists( 'mb_substr' ) ) {
			$cancellation_reason =
				mb_substr(
					$cancellation_reason,
					0,
					500
				);
		} else {
			$cancellation_reason =
				substr(
					$cancellation_reason,
					0,
					500
				);
		}

        $result =
            TutorHelper_Booking_Records::cancel(
                $booking_id,
                $cancellation_reason,
				'student'
            );

		if ( is_wp_error( $result ) ) {
			self::redirect(
				'error',
				$result->get_error_code()
			);
		}

		self::redirect(
			'cancelled'
		);
	}

	/**
	 * Redirect back to the dashboard.
	 *
	 * @param string $status     Result status.
	 * @param string $error_code Optional error code.
	 *
	 * @return void
	 */
	private static function redirect(
		$status,
		$error_code = ''
	) {
		$url =
			wp_get_referer();

		if ( ! $url ) {
			$url = home_url( '/' );
		}

		$args = array(
			'tutorhelper_dashboard_status' =>
				sanitize_key( $status ),
		);

		if ( $error_code ) {
			$args[
				'tutorhelper_dashboard_error'
			] =
				sanitize_key(
					$error_code
				);
		}

		wp_safe_redirect(
			add_query_arg(
				$args,
				$url
			)
		);

		exit;
	}
}
