<?php
/**
 * Student Management admin interface.
 *
 * @package TutorHelper_Bookings
 */

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

/**
 * Connects Student Management to the Booking Hub.
 */
final class TutorHelper_Students_Admin {

	/**
	 * Booking Hub tab identifier.
	 *
	 * This matches the existing third tab in the Booking Hub.
	 *
	 * @var string
	 */
	const TAB_KEY = 'students';


    /**
     * Student-details save action.
     *
     * @var string
     */
    const SAVE_ACTION =
        'tutorhelper_save_student';

    /**
     * Password-reset email action.
     *
     * @var string
     */
    const RESET_EMAIL_ACTION =
        'tutorhelper_send_student_password_reset';

    /**
     * Manual password action.
     *
     * @var string
     */
    const PASSWORD_ACTION =
        'tutorhelper_set_student_password';


     /**
     * AJAX action used to search Parent Account candidates.
     *
     * @var string
     */
    const PARENT_SEARCH_ACTION = 'tutorhelper_search_parent_accounts';


	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_filter(
			'tutorhelper_booking_hub_tabs',
			array( __CLASS__, 'enable_students_tab' )
		);

		add_action(
			'tutorhelper_booking_hub_render_tab',
			array( __CLASS__, 'render_hub_tab' ),
			10,
			2
		);

        add_action(
            'admin_post_' . self::SAVE_ACTION,
            array( __CLASS__, 'handle_save_student' )
        );

        add_action(
            'admin_post_' . self::RESET_EMAIL_ACTION,
            array( __CLASS__, 'handle_send_password_reset' )
        );

        add_action(
            'admin_post_' . self::PASSWORD_ACTION,
            array( __CLASS__, 'handle_set_password' )
        );

        add_action(
            'wp_ajax_' . self::PARENT_SEARCH_ACTION,
            array( __CLASS__, 'handle_parent_account_search' )
        );


	}

	/**
	 * Make the existing Students tab available.
	 *
	 * The tab has already been created by the Booking Hub. This module
	 * changes only its status and keeps its existing third position.
	 *
	 * @param array $tabs Booking Hub tab definitions.
	 *
	 * @return array
	 */
	public static function enable_students_tab( $tabs ) {
		if (
			! is_array( $tabs )
			|| ! isset( $tabs[ self::TAB_KEY ] )
		) {
			return $tabs;
		}

		$tabs[ self::TAB_KEY ]['status'] =
			'available';

		$tabs[ self::TAB_KEY ]['description'] =
			__(
				'Manage student accounts, parent details and booking access.',
				'tutorhelper-bookings'
			);

		return $tabs;
	}

	/**
	 * Render Student Management inside the Students Hub tab.
	 *
	 * @param string $selected_tab Selected Booking Hub tab.
	 * @param array  $active_tab   Active tab definition.
	 *
	 * @return void
	 */
	public static function render_hub_tab(
		$selected_tab,
		$active_tab
	) {
		if ( self::TAB_KEY !== $selected_tab ) {
			return;
		}

		if (
			! current_user_can(
				TutorHelper_Admin::CAPABILITY
			)
		) {
			return;
		}

		self::render_workspace( $active_tab );
	}

	/**
	 * Render the initial Student Management workspace.
	 *
	 * @param array $active_tab Active Booking Hub tab definition.
	 *
	 * @return void
	 */
	private static function render_workspace(
		$active_tab
	) {
		$tab_label = isset( $active_tab['label'] )
			? $active_tab['label']
			: __(
				'Students',
				'tutorhelper-bookings'
			);

        $student_user_id = isset(
            $_GET['student_id'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
        )
            ? absint( $_GET['student_id'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
            : 0;

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

        $has_custom_workspace =
            (bool) apply_filters(
                'tutorhelper_students_has_custom_workspace',
                false,
                $active_tab
            );

        if ( $has_custom_workspace ) {
            do_action(
                'tutorhelper_students_render_custom_workspace',
                $active_tab
            );

            return;
        }


		?>
		<section class="tutorhelper-students-workspace">
            
                <header class="tutorhelper-workspace__header">
                    <div>
                        <h2>
                            <?php echo esc_html( $tab_label ); ?>
                        </h2>

                        <p>
                            <?php
                            echo esc_html__(
                                'Manage WordPress student accounts, parent details and booking permissions.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>
                </header>


			<div class="tutorhelper-students-workspace__grid <?php echo $student_user_id
                ? 'is-detail-view'
                : ''; ?>">
				<main class="tutorhelper-students-workspace__main">
                    <?php
                    if ( $student_user_id && $student ) {
                        self::render_student_detail_shell(
                            $student
                        );
                    } elseif ( $student_user_id ) {
                        self::render_student_not_found();
                    } else {
                        self::render_student_list();
                    }
                    ?>
                </main>

                <?php if ( ! $student_user_id ) : ?>

                    <aside class="tutorhelper-students-workspace__sidebar">
                        <?php
                        if (
                            has_action(
                                'tutorhelper_students_registration_sidebar'
                            )
                        ) {
                            do_action(
                                'tutorhelper_students_registration_sidebar'
                            );
                        } else {
                            self::render_pro_feature(
                                __(
                                    'Student Registrations',
                                    'tutorhelper-bookings'
                                ),
                                __(
                                    'Review new registrations and onboarding answers with TutorHelper Bookings Pro.',
                                    'tutorhelper-bookings'
                                ),
                                'dashicons-id'
                            );
                        }
                        ?>
                    </aside>
                <?php endif; ?>
			</div>
		</section>
		<?php
	}

	/**
     * Render the searchable Student Accounts list.
     *
     * @return void
     */
    private static function render_student_list() {
        $search = isset( $_GET['student_search'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
            ? sanitize_text_field(
                wp_unslash(
                    $_GET['student_search'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
                )
            )
            : '';

        $page = isset( $_GET['student_page'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
            ? max(
                1,
                absint( $_GET['student_page'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
            )
            : 1;

        $result = TutorHelper_Students::get_students(
            array(
                'search'   => $search,
                'page'     => $page,
                'per_page' => 20,
            )
        );

        ?>
        <section class="tutorhelper-main-section tutorhelper-students-panel">
            <header class="tutorhelper-main-section__header">
                <div class="tutorhelper-main-section__header-content">
                    <h2>
                        <?php
                        echo esc_html__(
                            'Student Accounts',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </h2>

                    <p>
                        <?php
                        printf(
                            esc_html(
                                /* translators: %d: Student account count. */
                                _n(
                                    '%d TH Student account',
                                    '%d TH Student accounts',
                                    $result['total'],
                                    'tutorhelper-bookings'
                                )
                            ),
                            absint( $result['total'] )
                        );
                        ?>
                    </p>
                </div>
            </header>

            <div class="tutorhelper-main-section__body">

            <?php
            self::render_student_search_form(
                $search
            );
            ?>

            <?php if ( empty( $result['students'] ) ) : ?>
                <?php
                self::render_student_empty_state(
                    $search
                );
                ?>
            <?php else : ?>
                <?php
                self::render_student_table(
                    $result['students']
                );

                self::render_student_pagination(
                    $result,
                    $search
                );
                ?>
            <?php endif; ?>
        	</div>
        </section>
        <?php
    }

    /**
     * Render the student search form.
     *
     * @param string $search Current search term.
     *
     * @return void
     */
    private static function render_student_search_form(
        $search
    ) {
        ?>
        <form
            method="get"
            action="<?php echo esc_url(
                admin_url( 'admin.php' )
            ); ?>"
            class="tutorhelper-student-search"
        >
            <input
                type="hidden"
                name="page"
                value="<?php echo esc_attr(
                    TutorHelper_Booking_Hub::PAGE_SLUG
                ); ?>"
            />

            <input
                type="hidden"
                name="tab"
                value="<?php echo esc_attr(
                    self::TAB_KEY
                ); ?>"
            />

            <div class="tutorhelper-input-field tutorhelper-student-search__field">
                <label
                    for="tutorhelper-student-search"
                    class="screen-reader-text"
                >
                    <?php
                    echo esc_html__(
                        'Search student accounts',
                        'tutorhelper-bookings'
                    );
                    ?>
                </label>

                <input
                    type="search"
                    id="tutorhelper-student-search"
                    name="student_search"
                    value="<?php echo esc_attr(
                        $search
                    ); ?>"
                    placeholder="<?php echo esc_attr__(
                        'Search by name, username or email',
                        'tutorhelper-bookings'
                    ); ?>"
                />
            </div>

            <button
                type="submit"
                class="button tutorhelper-action-button"
            >
                <span
                    class="dashicons dashicons-search"
                    aria-hidden="true"
                ></span>

                <?php
                echo esc_html__(
                    'Search students',
                    'tutorhelper-bookings'
                );
                ?>
            </button>

            <?php if ( '' !== $search ) : ?>
                <a
                    class="button tutorhelper-hub-pill-button"
                    href="<?php echo esc_url(
                        self::get_students_url()
                    ); ?>"
                >
                    <span
                        class="dashicons dashicons-dismiss"
                        aria-hidden="true"
                    ></span>

                    <?php
                    echo esc_html__(
                        'Clear search',
                        'tutorhelper-bookings'
                    );
                    ?>
                </a>
            <?php endif; ?>
        </form>
        <?php
    }

    /**
     * Render the student list table.
     *
     * @param array $students Student WP_User objects.
     *
     * @return void
     */
    private static function render_student_table(
        $students
    ) {
        ?>
        <div class="tutorhelper-student-table-wrap">
            <table class="widefat striped tutorhelper-student-table">
                <thead>
                    <tr>
                        <th scope="col">
                            <?php
                            echo esc_html__(
                                'Student',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </th>

                        <th scope="col">
                            <?php
                            echo esc_html__(
                                'Parent / Guardian',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </th>

                        <th scope="col">
                            <?php
                            echo esc_html__(
                                'Account created',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </th>

                        <th scope="col">
                            <?php
                            echo esc_html__(
                                'Booking access',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </th>

                        <th scope="col">
                            <span class="screen-reader-text">
                                <?php
                                echo esc_html__(
                                    'Actions',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </span>
                        </th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ( $students as $student ) : ?>
                        <?php
                        self::render_student_row(
                            $student
                        );
                        ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

    /**
     * Render one student table row.
     *
     * @param WP_User $student Student user.
     *
     * @return void
     */
    private static function render_student_row(
        $student
    ) {
        $parent = TutorHelper_Students::get_parent_summary(
            $student->ID
        );

        $is_blocked =
            TutorHelper_Students::is_booking_blocked(
                $student->ID
            );

        ?>
        <tr>
            <td data-label="<?php echo esc_attr__(
                'Student',
                'tutorhelper-bookings'
            ); ?>">
                <div class="tutorhelper-student-identity">
                    <?php
                    echo get_avatar(
                        $student->ID,
                        40,
                        '',
                        $student->display_name
                    );
                    ?>

                    <div>
                        <strong>
                            <?php
                            echo esc_html(
                                $student->display_name
                            );
                            ?>
                        </strong>

                        <a href="mailto:<?php echo esc_attr(
                            $student->user_email
                        ); ?>">
                            <?php
                            echo esc_html(
                                $student->user_email
                            );
                            ?>
                        </a>

                        <small>
                            <?php
                            printf(
                                /* translators: %s: WordPress username. */
                                esc_html__(
                                    'Username: %s',
                                    'tutorhelper-bookings'
                                ),
                                esc_html(
                                    $student->user_login
                                )
                            );
                            ?>
                        </small>
                    </div>
                </div>
            </td>

            <td data-label="<?php echo esc_attr__(
                'Parent / Guardian',
                'tutorhelper-bookings'
            ); ?>">
                <?php if ( $parent['name'] || $parent['email'] ) : ?>
                    <strong>
                        <?php
                        echo esc_html(
                            $parent['name']
                                ? $parent['name']
                                : __(
                                    'Name not provided',
                                    'tutorhelper-bookings'
                                )
                        );
                        ?>
                    </strong>

                    <?php if ( $parent['email'] ) : ?>
                        <a href="mailto:<?php echo esc_attr(
                            $parent['email']
                        ); ?>">
                            <?php
                            echo esc_html(
                                $parent['email']
                            );
                            ?>
                        </a>
                    <?php endif; ?>
                <?php else : ?>
                    <span class="tutorhelper-student-muted">
                        <?php
                        echo esc_html__(
                            'Not provided',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </span>
                <?php endif; ?>
            </td>

            <td data-label="<?php echo esc_attr__(
                'Account created',
                'tutorhelper-bookings'
            ); ?>">
                <?php
                echo esc_html(
                    get_date_from_gmt(
                        $student->user_registered,
                        get_option( 'date_format' )
                    )
                );
                ?>
            </td>

            <td data-label="<?php echo esc_attr__(
                'Booking access',
                'tutorhelper-bookings'
            ); ?>">
                <span class="tutorhelper-student-status <?php echo $is_blocked
                    ? 'is-blocked'
                    : 'is-allowed'; ?>">
                    <?php
                    echo esc_html(
                        $is_blocked
                            ? __(
                                'Blocked',
                                'tutorhelper-bookings'
                            )
                            : __(
                                'Allowed',
                                'tutorhelper-bookings'
                            )
                    );
                    ?>
                </span>
            </td>

            <td class="tutorhelper-student-table__actions">
                <a
                    class="tutorhelper-hub-pill-button-small"
                    href="<?php echo esc_url(
                        self::get_student_url(
                            $student->ID
                        )
                    ); ?>"
                >
                    <?php
                    echo esc_html__(
                        'Open student',
                        'tutorhelper-bookings'
                    );
                    ?>
                </a>
            </td>
        </tr>
        <?php
    }

    /**
     * Render student-list pagination.
     *
     * @param array  $result Student query result.
     * @param string $search Current search term.
     *
     * @return void
     */
    private static function render_student_pagination(
        $result,
        $search
    ) {
        if ( $result['total_pages'] <= 1 ) {
            return;
        }

        $base_url = add_query_arg(
            array(
                'page'           =>
                    TutorHelper_Booking_Hub::PAGE_SLUG,
                'tab'            => self::TAB_KEY,
                'student_search' => $search,
                'student_page'   => '%#%',
            ),
            admin_url( 'admin.php' )
        );

        $links = paginate_links(
            array(
                'base'      => str_replace(
                    '%25%23%25',
                    '%#%',
                    esc_url( $base_url )
                ),
                'format'    => '',
                'current'   => absint(
                    $result['page']
                ),
                'total'     => absint(
                    $result['total_pages']
                ),
                'type'      => 'list',
                'prev_text' => __(
                    'Previous',
                    'tutorhelper-bookings'
                ),
                'next_text' => __(
                    'Next',
                    'tutorhelper-bookings'
                ),
            )
        );

        if ( ! $links ) {
            return;
        }

        ?>
        <nav
            class="tutorhelper-student-pagination"
            aria-label="<?php echo esc_attr__(
                'Student account pages',
                'tutorhelper-bookings'
            ); ?>"
        >
            <?php echo wp_kses_post( $links ); ?>
        </nav>
        <?php
    }

    /**
     * Render the student-list empty state.
     *
     * @param string $search Current search term.
     *
     * @return void
     */
    private static function render_student_empty_state(
        $search
    ) {
        ?>
        <div class="tutorhelper-students-empty">
            <span
                class="dashicons dashicons-groups"
                aria-hidden="true"
            ></span>

            <h3>
                <?php
                echo esc_html(
                    '' !== $search
                        ? __(
                            'No matching students',
                            'tutorhelper-bookings'
                        )
                        : __(
                            'No TH Student accounts',
                            'tutorhelper-bookings'
                        )
                );
                ?>
            </h3>

            <p>
                <?php
                echo esc_html(
                    '' !== $search
                        ? __(
                            'Try a different name, username or email address.',
                            'tutorhelper-bookings'
                        )
                        : __(
                            'Assign the TH Student role to a WordPress user to show them here.',
                            'tutorhelper-bookings'
                        )
                );
                ?>
            </p>
        </div>
        <?php
    }


    /**
     * Render an invalid-student message.
     *
     * @return void
     */
    private static function render_student_not_found() {
        ?>
        <section class="tutorhelper-students-panel">
            <div class="tutorhelper-students-empty">
                <span
                    class="dashicons dashicons-warning"
                    aria-hidden="true"
                ></span>

                <h3>
                    <?php
                    echo esc_html__(
                        'Student not found',
                        'tutorhelper-bookings'
                    );
                    ?>
                </h3>

                <p>
                    <?php
                    echo esc_html__(
                        'The requested user does not exist or is not assigned the TH Student role.',
                        'tutorhelper-bookings'
                    );
                    ?>
                </p>

                <a
                    class="button"
                    href="<?php echo esc_url(
                        self::get_students_url()
                    ); ?>"
                >
                    <?php
                    echo esc_html__(
                        'Return to students',
                        'tutorhelper-bookings'
                    );
                    ?>
                </a>
            </div>
        </section>
        <?php
    }



    /**
     * Render the complete student detail view.
     *
     * Tutors can switch between a read-only account view and the
     * editable account form.
     *
     * @param WP_User $student Student user.
     *
     * @return void
     */
    private static function render_student_detail_shell(
        $student
    ) {
        $details = TutorHelper_Students::get_student_details(
            $student
        );

        if ( ! is_array( $details ) ) {
            self::render_student_not_found();

            return;
        }

        $student_mode = isset(
            $_GET['student_mode'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
        )
            ? sanitize_key(
                wp_unslash(
                    $_GET['student_mode'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
                )
            )
            : 'view';

        $is_editing = 'edit' === $student_mode;

        $view_url = self::get_student_url(
            $details['id'],
            array(
                'student_mode' => 'view',
            )
        );

        $edit_url = self::get_student_url(
            $details['id'],
            array(
                'student_mode' => 'edit',
            )
        );

        ?>
        <section class="tutorhelper-student-detail">
            <header class="tutorhelper-student-detail__header">
                <div class="tutorhelper-student-detail__identity">
                    <?php
                    echo get_avatar(
                        $details['id'],
                        64,
                        '',
                        $details['student_name']
                    );
                    ?>

                    <div>
                        <h2>
                            <?php
                            echo esc_html(
                                $details['student_name']
                            );
                            ?>
                        </h2>

                        <a
                            href="mailto:<?php echo esc_attr(
                                $details['email']
                            ); ?>"
                        >
                            <?php
                            echo esc_html(
                                $details['email']
                            );
                            ?>
                        </a>
                    </div>
                </div>

                <div class="tutorhelper-student-detail__header-actions">
                    <div
                        class="tutorhelper-booking-hub__view-switcher"
                        aria-label="<?php echo esc_attr__(
                            'Student detail mode',
                            'tutorhelper-bookings'
                        ); ?>"
                    >
                        <a
                            class="button <?php echo ! $is_editing
                                ? 'button-primary'
                                : ''; ?>"
                            href="<?php echo esc_url(
                                $view_url
                            ); ?>"
                            <?php echo ! $is_editing
                                ? 'aria-current="page"'
                                : ''; ?>
                        >
                            <span
                                class="dashicons dashicons-visibility"
                                aria-hidden="true"
                            ></span>

                            <?php
                            echo esc_html__(
                                'View',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </a>

                        <a
                            class="button <?php echo $is_editing
                                ? 'button-primary'
                                : ''; ?>"
                            href="<?php echo esc_url(
                                $edit_url
                            ); ?>"
                            <?php echo $is_editing
                                ? 'aria-current="page"'
                                : ''; ?>
                        >
                            <span
                                class="dashicons dashicons-edit"
                                aria-hidden="true"
                            ></span>

                            <?php
                            echo esc_html__(
                                'Edit',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </a>
                    </div>

                    <a
                        class="button tutorhelper-hub-pill-button"
                        href="<?php echo esc_url(
                            self::get_students_url()
                        ); ?>"
                    >
                        <span aria-hidden="true">&larr;</span>

                        <?php
                        echo esc_html__(
                            'Back to students',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </a>
                </div>
            </header>

            <div class="tutorhelper-student-detail__body">
                <?php
                self::render_student_notice();
                ?>

                <?php if ( $is_editing ) : ?>
                    <?php
                    self::render_student_edit_form(
                        $details,
                        $view_url
                    );
                    ?>
                <?php else : ?>
                    <div class="tutorhelper-student-detail__columns">
                        <?php
                        self::render_student_account_details(
                            $details,
                            false
                        );

                        self::render_parent_details(
                            $details,
                            false
                        );
                        ?>
                    </div>

                    <?php
                    self::render_booking_access_details(
                        $details,
                        false
                    );
                    ?>
                <?php endif; ?>

                <?php
                self::render_password_management(
                    $details
                );
                ?>

                <div class="tutorhelper-student-detail__pro-grid">
                    <?php
                    /**
                     * Render additional student-registration and account extensions.
                     *
                     * Add-ons can use this hook to display additional
                     * student information without Core knowing about
                     * the feature implementation.
                     *
                     * @param WP_User $student Student user.
                     */
                    if (
                        has_action(
                            'tutorhelper_students_registration_detail'
                        )
                    ) {

                        do_action(
                            'tutorhelper_students_registration_detail',
                            $student
                        );

                    } else {

                        self::render_pro_feature(
                            __(
                                'Student Registration & Onboarding',
                                'tutorhelper-bookings'
                            ),
                            __(
                                'Review registration details and onboarding answers with TutorHelper Bookings Pro.',
                                'tutorhelper-bookings'
                            ),
                            'dashicons-id'
                        );
                    }

                    $show_pricing_placeholder =
                        apply_filters(
                            'tutorhelper_students_show_pricing_placeholder',
                            true,
                            $student
                        );

                    if ( $show_pricing_placeholder ) {
                        self::render_pro_feature(
                            __(
                                'Lesson Pricing & Payment Options',
                                'tutorhelper-bookings'
                            ),
                            __(
                                'Set individual prices, invoice options and payment methods with TutorHelper Bookings Pro.',
                                'tutorhelper-bookings'
                            ),
                            'dashicons-money-alt'
                        );
                    }

                    /**
                     * Render additional student pricing controls.
                     *
                     * Extensions can use this hook to provide pricing
                     * functionality for an individual student.
                     *
                     * @param WP_User $student Student user.
                     */
                    do_action(
                        'tutorhelper_students_render_pricing',
                        $student
                    );

                    /**
                     * Render additional student-detail extensions.
                     *
                     * Add-ons can use this hook to display additional
                     * student information without Core knowing about
                     * the feature implementation.
                     *
                     * @param WP_User $student Student user.
                     */
                    do_action(
                        'tutorhelper_students_render_extensions',
                        $student
                    );


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


    /**
     * Render the editable student details form.
     *
     * @param array  $details Student details.
     * @param string $cancel_url Read-only student view URL.
     *
     * @return void
     */
    private static function render_student_edit_form(
        $details,
        $cancel_url
    ) {
        ?>
        <form
            method="post"
            action="<?php echo esc_url(
                admin_url( 'admin-post.php' )
            ); ?>"
            class="tutorhelper-student-edit-form"
        >
            <input
                type="hidden"
                name="action"
                value="<?php echo esc_attr(
                    self::SAVE_ACTION
                ); ?>"
            />

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

            <?php
            wp_nonce_field(
                self::SAVE_ACTION
            );
            ?>

            <div class="tutorhelper-student-detail__columns">
                <?php
                self::render_student_account_details(
                    $details,
                    true
                );

                self::render_parent_details(
                    $details,
                    true
                );
                ?>
            </div>

            <?php
            self::render_booking_access_details(
                $details,
                true
            );
            ?>

            <div class="tutorhelper-student-edit-form__actions">
                <button
                    type="submit"
                    class="button button-primary tutorhelper-action-button"
                >
                    <span
                        class="dashicons dashicons-saved"
                        aria-hidden="true"
                    ></span>

                    <?php
                    echo esc_html__(
                        'Save student details',
                        'tutorhelper-bookings'
                    );
                    ?>
                </button>

                <a
                    class="button tutorhelper-hub-pill-button"
                    href="<?php echo esc_url(
                        $cancel_url
                    ); ?>"
                >
                    <?php
                    echo esc_html__(
                        'Cancel editing',
                        'tutorhelper-bookings'
                    );
                    ?>
                </a>
            </div>
        </form>
        <?php
    }


    /**
     * Render a Student Management notice.
     *
     * @return void
     */
    private static function render_student_notice() {
        $notice_code = isset(
            $_GET['student_notice'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
        )
            ? sanitize_key(
                wp_unslash(
                    $_GET['student_notice'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
                )
            )
            : '';

        if ( '' === $notice_code ) {
            return;
        }

        $notice_type = isset(
            $_GET['student_notice_type'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
        )
            ? sanitize_key(
                wp_unslash(
                    $_GET['student_notice_type'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
                )
            )
            : 'success';

        $messages = array(
            'student_saved' => __(
                'Student details saved.',
                'tutorhelper-bookings'
            ),

            'student_not_found' => __(
                'The student account could not be found.',
                'tutorhelper-bookings'
            ),

            'tutorhelper_student_invalid_email' => __(
                'Enter a valid student email address.',
                'tutorhelper-bookings'
            ),

            'tutorhelper_student_email_exists' => __(
                'That email address is already used by another WordPress account.',
                'tutorhelper-bookings'
            ),

            'tutorhelper_student_display_name_required' => __(
                'Enter a display name for the student.',
                'tutorhelper-bookings'
            ),

            'password_email_sent' => __(
                'The WordPress password-reset email was sent.',
                'tutorhelper-bookings'
            ),

            'password_email_failed' => __(
                'The password-reset email could not be sent.',
                'tutorhelper-bookings'
            ),

            'password_updated' => __(
                'The student password was updated.',
                'tutorhelper-bookings'
            ),

            'password_too_short' => __(
                'The new password must contain at least 12 characters.',
                'tutorhelper-bookings'
            ),

            'password_mismatch' => __(
                'The new passwords do not match.',
                'tutorhelper-bookings'
            ),

            'tutorhelper_parent_same_as_student' => __(
                'A student cannot be linked as their own Parent Account.',
                'tutorhelper-bookings'
            ),

            'tutorhelper_parent_not_found' => __(
                'The selected Parent Account could not be found.',
                'tutorhelper-bookings'
            ),
        );

        if ( ! isset( $messages[ $notice_code ] ) ) {
            return;
        }

        $classes = array(
            'notice',
            'error' === $notice_type
                ? 'notice-error'
                : 'notice-success',
            'is-dismissible',
            'tutorhelper-student-notice',
        );

        ?>
        <div class="<?php echo esc_attr(
            implode( ' ', $classes )
        ); ?>">
            <p>
                <?php echo esc_html(
                    $messages[ $notice_code ]
                ); ?>
            </p>
        </div>
        <?php
    }

    /**
     * Render expandable student password-management controls.
     *
     * @param array $details Student details.
     *
     * @return void
     */
    private static function render_password_management(
        $details
    ) {
        ?>
        <details class="tutorhelper-student-accordion">
            <summary class="tutorhelper-student-accordion__summary">
                <span
                    class="dashicons dashicons-lock"
                    aria-hidden="true"
                ></span>

                <span class="tutorhelper-student-accordion__title">
                    <strong>
                        <?php
                        echo esc_html__(
                            'Password Management',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </strong>

                    <small>
                        <?php
                        echo esc_html__(
                            'Send a reset email or set a new password manually.',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </small>
                </span>

                <span
                    class="dashicons dashicons-arrow-down-alt2 tutorhelper-student-accordion__icon"
                    aria-hidden="true"
                ></span>
            </summary>

            <div class="tutorhelper-student-accordion__content">
                <div class="tutorhelper-student-password__grid">
                    <section class="tutorhelper-student-password__option">
                        <h4>
                            <?php
                            echo esc_html__(
                                'Send password reset email',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </h4>

                        <p>
                            <?php
                            printf(
                                /* translators: %s: Student email address. */
                                esc_html__(
                                    'WordPress will send a secure reset link to %s.',
                                    'tutorhelper-bookings'
                                ),
                                esc_html(
                                    $details['email']
                                )
                            );
                            ?>
                        </p>

                        <form
                            method="post"
                            action="<?php echo esc_url(
                                admin_url( 'admin-post.php' )
                            ); ?>"
                        >
                            <input
                                type="hidden"
                                name="action"
                                value="<?php echo esc_attr(
                                    self::RESET_EMAIL_ACTION
                                ); ?>"
                            />

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

                            <?php
                            wp_nonce_field(
                                self::RESET_EMAIL_ACTION
                            );
                            ?>

                            <button
                                type="submit"
                                class="button tutorhelper-hub-pill-button"
                            >
                                <span
                                    class="dashicons dashicons-email-alt"
                                    aria-hidden="true"
                                ></span>

                                <?php
                                echo esc_html__(
                                    'Send reset email',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </button>
                        </form>
                    </section>

                    <section class="tutorhelper-student-password__option">
                        <h4>
                            <?php
                            echo esc_html__(
                                'Set a new password manually',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </h4>

                        <p>
                            <?php
                            echo esc_html__(
                                'The student will be signed out and must use this new password. For security, no confirmation email will be sent containing passwords.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>

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

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

                            <?php
                            wp_nonce_field(
                                self::PASSWORD_ACTION
                            );
                            ?>

                            <div class="tutorhelper-student-field">
                                <label for="tutorhelper-new-password">
                                    <?php
                                    echo esc_html__(
                                        'New password',
                                        'tutorhelper-bookings'
                                    );
                                    ?>
                                </label>

                                <input
                                    type="password"
                                    id="tutorhelper-new-password"
                                    name="new_password"
                                    minlength="12"
                                    autocomplete="new-password"
                                    required
                                />
                            </div>

                            <div class="tutorhelper-student-field">
                                <label for="tutorhelper-confirm-password">
                                    <?php
                                    echo esc_html__(
                                        'Confirm password',
                                        'tutorhelper-bookings'
                                    );
                                    ?>
                                </label>

                                <input
                                    type="password"
                                    id="tutorhelper-confirm-password"
                                    name="confirm_password"
                                    minlength="12"
                                    autocomplete="new-password"
                                    required
                                />
                            </div>

                            <button
                                type="submit"
                                class="button tutorhelper-action-button"
                            >
                                <span
                                    class="dashicons dashicons-saved"
                                    aria-hidden="true"
                                ></span>

                                <?php
                                echo esc_html__(
                                    'Set new password',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </button>
                        </form>
                    </section>
                </div>
            </div>
        </details>
        <?php
    }




    /**
     * Render student account details.
     *
     * @param array $details  Student details.
     * @param bool  $editable Whether to display editable fields.
     *
     * @return void
     */
    private static function render_student_account_details(
        $details,
        $editable = false
    ) {
        ?>
        <section class="tutorhelper-student-detail__section">
            <h3>
                <?php
                echo esc_html__(
                    'Student Details',
                    'tutorhelper-bookings'
                );
                ?>
            </h3>

            <?php if ( $editable ) : ?>
                <div class="tutorhelper-student-fields">
                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-first-name">
                            <?php
                            echo esc_html__(
                                'First name',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            id="tutorhelper-first-name"
                            name="first_name"
                            value="<?php echo esc_attr(
                                $details['first_name']
                            ); ?>"
                            autocomplete="given-name"
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-last-name">
                            <?php
                            echo esc_html__(
                                'Last name',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            id="tutorhelper-last-name"
                            name="last_name"
                            value="<?php echo esc_attr(
                                $details['last_name']
                            ); ?>"
                            autocomplete="family-name"
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-display-name">
                            <?php
                            echo esc_html__(
                                'Display name',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            id="tutorhelper-display-name"
                            name="display_name"
                            value="<?php echo esc_attr(
                                $details['display_name']
                            ); ?>"
                            required
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label>
                            <?php
                            echo esc_html__(
                                'Username',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            value="<?php echo esc_attr(
                                $details['username']
                            ); ?>"
                            disabled
                        />

                        <p class="description">
                            <?php
                            echo esc_html__(
                                'WordPress usernames cannot be changed here.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>

                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-student-email">
                            <?php
                            echo esc_html__(
                                'Email',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="email"
                            id="tutorhelper-student-email"
                            name="user_email"
                            value="<?php echo esc_attr(
                                $details['email']
                            ); ?>"
                            autocomplete="email"
                            required
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-student-phone">
                            <?php
                            echo esc_html__(
                                'Phone',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="tel"
                            id="tutorhelper-student-phone"
                            name="phone"
                            value="<?php echo esc_attr(
                                $details['phone']
                            ); ?>"
                            autocomplete="tel"
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label>
                            <?php
                            echo esc_html__(
                                'Account created',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            value="<?php echo esc_attr(
                                get_date_from_gmt(
                                    $details['registered'],
                                    get_option( 'date_format' )
                                    . ', '
                                    . get_option( 'time_format' )
                                )
                            ); ?>"
                            disabled
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label>
                            <?php
                            echo esc_html__(
                                'Account role',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            value="<?php echo esc_attr__(
                                'TH Student',
                                'tutorhelper-bookings'
                            ); ?>"
                            disabled
                        />
                    </div>
                </div>
            <?php else : ?>
                <dl class="tutorhelper-student-detail__list">
                    <?php
                    self::render_detail_row(
                        __(
                            'Student name',
                            'tutorhelper-bookings'
                        ),
                        $details['student_name']
                    );

                    self::render_detail_row(
                        __(
                            'Display name',
                            'tutorhelper-bookings'
                        ),
                        $details['display_name']
                    );

                    self::render_detail_row(
                        __(
                            'Username',
                            'tutorhelper-bookings'
                        ),
                        $details['username']
                    );

                    self::render_detail_row(
                        __(
                            'Email',
                            'tutorhelper-bookings'
                        ),
                        $details['email'],
                        'email'
                    );

                    self::render_detail_row(
                        __(
                            'Phone',
                            'tutorhelper-bookings'
                        ),
                        $details['phone']
                    );

                    self::render_detail_row(
                        __(
                            'Account created',
                            'tutorhelper-bookings'
                        ),
                        get_date_from_gmt(
                            $details['registered'],
                            get_option( 'date_format' )
                            . ', '
                            . get_option( 'time_format' )
                        )
                    );

                    self::render_detail_row(
                        __(
                            'Account role',
                            'tutorhelper-bookings'
                        ),
                        __(
                            'TH Student',
                            'tutorhelper-bookings'
                        )
                    );
                    ?>
                </dl>
            <?php endif; ?>
        </section>
        <?php
    }


    /**
     * Render parent, guardian and postal-address details.
     *
     * @param array $details  Student details.
     * @param bool  $editable Whether to display editable fields.
     *
     * @return void
     */
    private static function render_parent_details(
        $details,
        $editable = false
    ) {
        $parent  = $details['parent'];
        $address = $details['address'];

        ?>
        <section class="tutorhelper-student-detail__section">
            <h3>
                <?php
                echo esc_html__(
                    'Parent / Guardian',
                    'tutorhelper-bookings'
                );
                ?>
            </h3>

            <?php if ( $editable ) : ?>
                <div class="tutorhelper-student-fields">
                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-parent-name">
                            <?php
                            echo esc_html__(
                                'Name',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="text"
                            id="tutorhelper-parent-name"
                            name="parent_name"
                            value="<?php echo esc_attr(
                                $parent['legacy_name']
                            ); ?>"
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-parent-email">
                            <?php
                            echo esc_html__(
                                'Email',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="email"
                            id="tutorhelper-parent-email"
                            name="parent_email"
                            value="<?php echo esc_attr(
                                $parent['legacy_email']
                            ); ?>"
                        />
                    </div>

                    <div class="tutorhelper-student-field">
                        <label for="tutorhelper-parent-phone">
                            <?php
                            echo esc_html__(
                                'Phone',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <input
                            type="tel"
                            id="tutorhelper-parent-phone"
                            name="parent_phone"
                            value="<?php echo esc_attr(
                                $parent['legacy_phone']
                            ); ?>"
                        />
                    </div>
                </div>

                <section class="tutorhelper-parent-account">
                    <div class="tutorhelper-parent-account__header">
                        <span
                            class="dashicons dashicons-admin-links"
                            aria-hidden="true"
                        ></span>

                        <div>
                            <h4>
                                <?php
                                echo esc_html__(
                                    'Linked Parent Account',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </h4>

                            <p>
                                <?php
                                echo esc_html__(
                                    'Search for an existing WordPress user to link to this student.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </p>
                        </div>
                    </div>

                    <div
                        class="tutorhelper-user-search"
                        data-student-user-id="<?php echo esc_attr(
                            $details['id']
                        ); ?>"
                    >
                        <input
                            type="hidden"
                            name="parent_user_id"
                            class="tutorhelper-user-search__value"
                            value="<?php echo esc_attr(
                                $parent['linked_parent_user_id']
                            ); ?>"
                        />

                        <div class="tutorhelper-input-field">
                            <label for="tutorhelper-parent-account-search">
                                <?php
                                echo esc_html__(
                                    'Parent Account',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <div class="tutorhelper-user-search__control">
                                <input
                                    type="search"
                                    id="tutorhelper-parent-account-search"
                                    class="tutorhelper-user-search__input"
                                    placeholder="<?php echo esc_attr__(
                                        'Search by name, username or email',
                                        'tutorhelper-bookings'
                                    ); ?>"
                                    autocomplete="off"
                                    aria-autocomplete="list"
                                    aria-controls="tutorhelper-parent-account-results"
                                />

                                <span
                                    class="spinner tutorhelper-user-search__spinner"
                                    aria-hidden="true"
                                ></span>

                                <div
                                    id="tutorhelper-parent-account-results"
                                    class="tutorhelper-user-search__results"
                                    role="listbox"
                                    aria-label="<?php echo esc_attr__(
                                        'Parent Account search results',
                                        'tutorhelper-bookings'
                                    ); ?>"
                                    hidden
                                ></div>
                            </div>
                        </div>

                        <p
                            class="tutorhelper-user-search__status"
                            aria-live="polite"
                        ></p>

                        <div class="tutorhelper-user-search__selection">
                            <?php if ( $parent['linked_parent'] ) : ?>
                                <div class="tutorhelper-user-search__selected">
                                    <div>
                                        <strong>
                                            <?php
                                            echo esc_html(
                                                $parent['linked_name']
                                            );
                                            ?>
                                        </strong>

                                        <span>
                                            <?php
                                            echo esc_html(
                                                $parent['linked_email']
                                            );
                                            ?>
                                        </span>
                                    </div>

                                    <button
                                        type="button"
                                        class="button tutorhelper-hub-pill-button-small tutorhelper-user-search__remove"
                                    >
                                        <?php
                                        echo esc_html__(
                                            'Remove link',
                                            'tutorhelper-bookings'
                                        );
                                        ?>
                                    </button>
                                </div>
                            <?php else : ?>
                                <p class="tutorhelper-user-search__empty">
                                    <?php
                                    echo esc_html__(
                                        'No Parent Account selected.',
                                        'tutorhelper-bookings'
                                    );
                                    ?>
                                </p>
                            <?php endif; ?>
                        </div>

                        <p class="description">
                            <?php
                            echo esc_html__(
                                'The TH Parent role will be added automatically when the student is saved.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>

                    <label class="tutorhelper-toggle-row">
                        <input
                            type="checkbox"
                            name="use_linked_parent"
                            value="1"
                            class="tutorhelper-use-linked-parent"
                            <?php checked(
                                $parent['use_linked_parent']
                            ); ?>
                            <?php disabled(
                                ! $parent['linked_parent_user_id']
                            ); ?>
                        />

                        <span>
                            <strong>
                                <?php
                                echo esc_html__(
                                    'Use details from the linked Parent Account',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </strong>

                            <small>
                                <?php
                                echo esc_html__(
                                    'Overrides the separately stored parent name, email and phone. Those details remain available as a fallback.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </small>
                        </span>
                    </label>
                </section>


                <div class="tutorhelper-student-address-fields">
                    <h4>
                        <?php
                        echo esc_html__(
                            'Postal Address',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </h4>

                    <div class="tutorhelper-student-fields">
                        <div class="tutorhelper-student-field is-full-width">
                            <label for="tutorhelper-address-line-1">
                                <?php
                                echo esc_html__(
                                    'Address line 1',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-address-line-1"
                                name="address_line_1"
                                value="<?php echo esc_attr(
                                    $address['line_1']
                                ); ?>"
                                autocomplete="address-line1"
                            />
                        </div>

                        <div class="tutorhelper-student-field is-full-width">
                            <label for="tutorhelper-address-line-2">
                                <?php
                                echo esc_html__(
                                    'Address line 2',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-address-line-2"
                                name="address_line_2"
                                value="<?php echo esc_attr(
                                    $address['line_2']
                                ); ?>"
                                autocomplete="address-line2"
                            />
                        </div>

                        <div class="tutorhelper-student-field">
                            <label for="tutorhelper-address-city">
                                <?php
                                echo esc_html__(
                                    'Town / City',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-address-city"
                                name="address_city"
                                value="<?php echo esc_attr(
                                    $address['city']
                                ); ?>"
                                autocomplete="address-level2"
                            />
                        </div>

                        <div class="tutorhelper-student-field">
                            <label for="tutorhelper-address-county">
                                <?php
                                echo esc_html__(
                                    'County / State',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-address-county"
                                name="address_county"
                                value="<?php echo esc_attr(
                                    $address['county']
                                ); ?>"
                                autocomplete="address-level1"
                            />
                        </div>

                        <div class="tutorhelper-student-field">
                            <label for="tutorhelper-address-postcode">
                                <?php
                                echo esc_html__(
                                    'Postcode',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-address-postcode"
                                name="address_postcode"
                                value="<?php echo esc_attr(
                                    $address['postcode']
                                ); ?>"
                                autocomplete="postal-code"
                            />
                        </div>

                        <div class="tutorhelper-student-field">
                            <label for="tutorhelper-address-country">
                                <?php
                                echo esc_html__(
                                    'Country',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-address-country"
                                name="address_country"
                                value="<?php echo esc_attr(
                                    $address['country']
                                ); ?>"
                                autocomplete="country-name"
                            />
                        </div>
                    </div>
                </div>
            <?php else : ?>
                <dl class="tutorhelper-student-detail__list">
                    <?php
                    self::render_detail_row(
                        __(
                            'Name',
                            'tutorhelper-bookings'
                        ),
                        $parent['name']
                    );

                    self::render_detail_row(
                        __(
                            'Email',
                            'tutorhelper-bookings'
                        ),
                        $parent['email'],
                        'email'
                    );

                    self::render_detail_row(
                        __(
                            'Phone',
                            'tutorhelper-bookings'
                        ),
                        $parent['phone']
                    );
                    ?>
                </dl>

                
                <section class="tutorhelper-parent-account">
                    <div class="tutorhelper-parent-account__header">
                        <span
                            class="dashicons dashicons-admin-links"
                            aria-hidden="true"
                        ></span>

                        <div>
                            <h4>
                                <?php
                                echo esc_html__(
                                    'Linked Parent Account',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </h4>

                            <?php if ( $parent['linked_parent'] ) : ?>
                                <p>
                                    <strong>
                                        <?php
                                        echo esc_html(
                                            $parent['linked_name']
                                        );
                                        ?>
                                    </strong>

                                    <span>
                                        <?php
                                        echo esc_html(
                                            $parent['linked_email']
                                        );
                                        ?>
                                    </span>
                                </p>
                            <?php else : ?>
                                <p>
                                    <?php
                                    echo esc_html__(
                                        'No Parent Account is currently linked.',
                                        'tutorhelper-bookings'
                                    );
                                    ?>
                                </p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if ( $parent['linked_parent'] ) : ?>
                        <span class="tutorhelper-parent-account__status">
                            <?php
                            echo esc_html(
                                $parent['use_linked_parent']
                                    ? __(
                                        'Using linked account details',
                                        'tutorhelper-bookings'
                                    )
                                    : __(
                                        'Using separately stored parent details',
                                        'tutorhelper-bookings'
                                    )
                            );
                            ?>
                        </span>
                    <?php endif; ?>
                </section>


                <section class="tutorhelper-student-address-section">
                <div class="tutorhelper-student-address">
                    <h4>
                        <?php
                        echo esc_html__(
                            'Postal Address',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </h4>

                        <?php if ( $address['is_empty'] ) : ?>
                            <p class="tutorhelper-student-muted">
                                <?php
                                echo esc_html__(
                                    'Not provided',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </p>
                        <?php else : ?>
                            <address>
                                <?php foreach ( $address['lines'] as $line ) : ?>
                                    <span>
                                        <?php echo esc_html( $line ); ?>
                                    </span>
                                <?php endforeach; ?>
                            </address>
                        <?php endif; ?>
                    </div>
                </section>

            <?php endif; ?>

           
        </section>
        <?php
    }


    /**
     * Render one label and value within a details list.
     *
     * @param string $label Label.
     * @param string $value Display value.
     * @param string $type  Optional value type.
     *
     * @return void
     */
    private static function render_detail_row(
        $label,
        $value,
        $type = 'text'
    ) {
        $value = trim(
            (string) $value
        );

        ?>
        <div class="tutorhelper-student-detail__row">
            <dt>
                <?php echo esc_html( $label ); ?>
            </dt>

            <dd>
                <?php if ( '' === $value ) : ?>
                    <span class="tutorhelper-student-muted">
                        <?php
                        echo esc_html__(
                            'Not provided',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </span>
                <?php elseif ( 'email' === $type ) : ?>
                    <a href="mailto:<?php echo esc_attr(
                        $value
                    ); ?>">
                        <?php echo esc_html( $value ); ?>
                    </a>
                <?php else : ?>
                    <?php echo esc_html( $value ); ?>
                <?php endif; ?>
            </dd>
        </div>
        <?php
    }


    /**
     * Render Booking Access details or controls.
     *
     * @param array $details  Student details.
     * @param bool  $editable Whether to display editable fields.
     *
     * @return void
     */
    private static function render_booking_access_details(
        $details,
        $editable = false
    ) {
        $is_blocked = ! empty(
            $details['booking']['blocked']
        );

        ?>
        <section class="tutorhelper-student-booking-access">
            <div class="tutorhelper-student-booking-access__header">
                <div>
                    <h3>
                        <?php
                        echo esc_html__(
                            'Booking Access',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </h3>

                    <p>
                        <?php
                        echo esc_html__(
                            'Control whether this student can make lesson bookings.',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </p>
                </div>

                <span class="tutorhelper-student-status <?php echo esc_attr(
                    $is_blocked
                        ? 'is-blocked'
                        : 'is-allowed'
                ); ?>">
                    <?php
                    echo esc_html(
                        $is_blocked
                            ? __(
                                'Booking blocked',
                                'tutorhelper-bookings'
                            )
                            : __(
                                'Booking allowed',
                                'tutorhelper-bookings'
                            )
                    );
                    ?>
                </span>
            </div>

            <?php if ( $editable ) : ?>
                <div class="tutorhelper-student-booking-access__controls">
                    <label class="tutorhelper-toggle-row">
                        <input
                            type="checkbox"
                            name="booking_blocked"
                            value="1"
                            <?php checked( $is_blocked ); ?>
                        />

                        <span>
                            <strong>
                                <?php
                                echo esc_html__(
                                    'Block this student from booking lessons',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </strong>

                            <small>
                                <?php
                                echo esc_html__(
                                    'Existing bookings are not changed.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </small>
                        </span>
                    </label>

                    <div class="tutorhelper-student-field is-full-width">
                        <label for="tutorhelper-booking-message">
                            <?php
                            echo esc_html__(
                                'Message shown to student',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </label>

                        <textarea
                            id="tutorhelper-booking-message"
                            name="booking_blocked_message"
                            rows="3"
                        ><?php echo esc_textarea(
                            $details['booking']['message']
                        ); ?></textarea>
                    </div>
                </div>
            <?php elseif ( $is_blocked ) : ?>
                <div class="tutorhelper-student-booking-access__message">
                    <strong>
                        <?php
                        echo esc_html__(
                            'Message shown to student',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </strong>

                    <p>
                        <?php
                        echo esc_html(
                            $details['booking']['message']
                                ? $details['booking']['message']
                                : __(
                                    'Online booking is temporarily unavailable. Please contact us.',
                                    'tutorhelper-bookings'
                                )
                        );
                        ?>
                    </p>
                </div>
            <?php endif; ?>
        </section>
        <?php
    }



    /**
     * Return the Student Management list URL.
     *
     * @param array $args Additional query arguments.
     *
     * @return string
     */
    private static function get_students_url(
        $args = array()
    ) {
        $query_args = array_merge(
            array(
                'page' =>
                    TutorHelper_Booking_Hub::PAGE_SLUG,
                'tab'  => self::TAB_KEY,
            ),
            is_array( $args )
                ? $args
                : array()
        );

        return add_query_arg(
            $query_args,
            admin_url( 'admin.php' )
        );
    }

    /**
     * Return the Student Management detail URL.
     *
     * @param int   $student_user_id Student user ID.
     * @param array $args            Additional query arguments.
     *
     * @return string
     */
    private static function get_student_url(
        $student_user_id,
        $args = array()
    ) {
        return self::get_students_url(
            array_merge(
                array(
                    'student_id' => absint(
                        $student_user_id
                    ),
                ),
                is_array( $args )
                    ? $args
                    : array()
            )
        );
    }





	/**
	 * Render a disabled Pro feature placeholder.
	 *
	 * @param string $title       Feature title.
	 * @param string $description Feature description.
	 * @param string $icon        Dashicon class.
	 *
	 * @return void
	 */
	private static function render_pro_feature(
		$title,
		$description,
		$icon
	) {
		?>
		<section
			class="tutorhelper-students-pro-feature"
			aria-disabled="true"
		>
			<div class="tutorhelper-students-pro-feature__header">
				<span
					class="dashicons <?php echo esc_attr( $icon ); ?>"
					aria-hidden="true"
				></span>

				<h3>
					<?php echo esc_html( $title ); ?>
				</h3>

				<span class="tutorhelper-pro-badge">
					<?php
					echo esc_html__(
						'Pro',
						'tutorhelper-bookings'
					);
					?>
				</span>
			</div>

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

			<p class="tutorhelper-students-pro-feature__status">
				<?php
				echo esc_html__(
					'Available with TutorHelper Bookings Pro',
					'tutorhelper-bookings'
				);
				?>
			</p>
		</section>
		<?php
	}



    /**
     * Search WordPress users who may be linked as Parent Accounts.
     *
     * @return void
     */
    public static function handle_parent_account_search() {
        if (
            ! current_user_can(
                TutorHelper_Admin::CAPABILITY
            )
        ) {
            wp_send_json_error(
                array(
                    'message' => __(
                        'You do not have permission to search user accounts.',
                        'tutorhelper-bookings'
                    ),
                ),
                403
            );
        }

        check_ajax_referer(
            self::PARENT_SEARCH_ACTION,
            'nonce'
        );

        $search = isset( $_GET['search'] )
            ? sanitize_text_field(
                wp_unslash(
                    $_GET['search']
                )
            )
            : '';

        $student_user_id = isset(
            $_GET['student_user_id']
        )
            ? absint(
                $_GET['student_user_id']
            )
            : 0;

        if (
            ! $student_user_id
            || ! TutorHelper_Students::get_student(
                $student_user_id
            )
        ) {
            wp_send_json_error(
                array(
                    'message' => __(
                        'The student account could not be found.',
                        'tutorhelper-bookings'
                    ),
                ),
                400
            );
        }

        if ( strlen( $search ) < 2 ) {
            wp_send_json_success(
                array(
                    'results' => array(),
                )
            );
        }

        $users = TutorHelper_Students::search_parent_accounts(
            $search,
            $student_user_id,
            20
        );

        $results = array();

        foreach ( $users as $user ) {
            if ( ! $user instanceof WP_User ) {
                continue;
            }

            $results[] = array(
                'id' => absint(
                    $user->ID
                ),

                'name' => sanitize_text_field(
                    $user->display_name
                ),

                'email' => sanitize_email(
                    $user->user_email
                ),

                'username' => sanitize_user(
                    $user->user_login
                ),

                'is_parent' => in_array(
                    TutorHelper_Students::PARENT_ROLE,
                    (array) $user->roles,
                    true
                ),
            );
        }

        wp_send_json_success(
            array(
                'results' => $results,
            )
        );
    }




    /**
     * Save editable student details.
     *
     * @return void
     */
    public static function handle_save_student() {
        if (
            ! current_user_can(
                TutorHelper_Admin::CAPABILITY
            )
        ) {
            wp_die(
                esc_html__(
                    'You do not have permission to edit student accounts.',
                    'tutorhelper-bookings'
                )
            );
        }

        check_admin_referer(
            self::SAVE_ACTION
        );

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

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

        if ( ! $student ) {
            self::redirect_student_notice(
                $student_user_id,
                'student_not_found',
                'error'
            );
        }

        $data = array(
            'display_name' => isset(
                $_POST['display_name']
            )
                ? sanitize_text_field(
                    wp_unslash(
                        $_POST['display_name']
                    )
                )
                : '',

            'user_email' => isset(
                $_POST['user_email']
            )
                ? sanitize_email(
                    wp_unslash(
                        $_POST['user_email']
                    )
                )
                : '',
        );

        foreach (
            TutorHelper_Students::get_editable_meta_fields()
            as $field_key => $definition
        ) {
            $data[ $field_key ] = isset(
                $_POST[ $field_key ]
            )
                ? sanitize_text_field(
                    wp_unslash(
                        $_POST[ $field_key ]
                    )
                )
                : '';
        }

        $result =
            TutorHelper_Students::update_student(
                $student_user_id,
                $data
            );

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

        $blocked = isset(
            $_POST['booking_blocked']
        );

        $booking_message = isset(
            $_POST['booking_blocked_message']
        )
            ? sanitize_textarea_field(
                wp_unslash(
                    $_POST['booking_blocked_message']
                )
            )
            : '';
        
        $parent_user_id = isset(
            $_POST['parent_user_id']
        )
            ? absint(
                $_POST['parent_user_id']
            )
            : 0;

        $use_linked_parent = isset(
            $_POST['use_linked_parent']
        );

        $parent_link_result =
            TutorHelper_Students::update_parent_link(
                $student_user_id,
                $parent_user_id,
                $use_linked_parent
            );

        if ( is_wp_error( $parent_link_result ) ) {
            self::redirect_student_notice(
                $student_user_id,
                $parent_link_result->get_error_code(),
                'error',
                array(
                    'student_mode' => 'edit',
                )
            );
        }


        $access_result =
            TutorHelper_Students::update_booking_access(
                $student_user_id,
                $blocked,
                $booking_message
            );

        if ( is_wp_error( $access_result ) ) {
            self::redirect_student_notice(
                $student_user_id,
                $access_result->get_error_code(),
                'error'
            );
        }

        self::redirect_student_notice(
            $student_user_id,
            'student_saved',
            'success',
            array(
                'student_mode' => 'view',
            )
        );

    }


    /**
     * Send WordPress's standard password-reset email.
     *
     * @return void
     */
    public static function handle_send_password_reset() {
        if (
            ! current_user_can(
                TutorHelper_Admin::CAPABILITY
            )
        ) {
            wp_die(
                esc_html__(
                    'You do not have permission to reset student passwords.',
                    'tutorhelper-bookings'
                )
            );
        }

        check_admin_referer(
            self::RESET_EMAIL_ACTION
        );

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

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

        if ( ! $student ) {
            self::redirect_student_notice(
                $student_user_id,
                'student_not_found',
                'error'
            );
        }

        $result = retrieve_password(
            $student->user_login
        );

        if ( is_wp_error( $result ) ) {
            self::redirect_student_notice(
                $student_user_id,
                'password_email_failed',
                'error'
            );
        }

        TutorHelper_Student_Audit_Log::record(
            $student_user_id,
            'password_reset_email_sent',
            'password'
        );

        self::redirect_student_notice(
            $student_user_id,
            'password_email_sent',
            'success'
        );
    }


    /**
     * Manually set a new student password.
     *
     * @return void
     */
    public static function handle_set_password() {
        if (
            ! current_user_can(
                TutorHelper_Admin::CAPABILITY
            )
        ) {
            wp_die(
                esc_html__(
                    'You do not have permission to reset student passwords.',
                    'tutorhelper-bookings'
                )
            );
        }

        check_admin_referer(
            self::PASSWORD_ACTION
        );

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

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

        if ( ! $student ) {
            self::redirect_student_notice(
                $student_user_id,
                'student_not_found',
                'error'
            );
        }

        $password = isset(
            $_POST['new_password']
        )
            ? (string) wp_unslash(
                $_POST['new_password'] // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Passwords must remain byte-for-byte unchanged; the nonce-protected handler intentionally unslashes but does not text-sanitize the password.
            )
            : '';

        $confirmation = isset(
            $_POST['confirm_password']
        )
            ? (string) wp_unslash(
                $_POST['confirm_password'] // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Passwords must remain byte-for-byte unchanged; the nonce-protected handler intentionally unslashes but does not text-sanitize the password.
            )
            : '';

        if ( strlen( $password ) < 12 ) {
            self::redirect_student_notice(
                $student_user_id,
                'password_too_short',
                'error'
            );
        }

        if ( $password !== $confirmation ) {
            self::redirect_student_notice(
                $student_user_id,
                'password_mismatch',
                'error'
            );
        }

        wp_set_password(
            $password,
            $student_user_id
        );

        TutorHelper_Student_Audit_Log::record(
            $student_user_id,
            'password_manually_reset',
            'password'
        );

        self::redirect_student_notice(
            $student_user_id,
            'password_updated',
            'success'
        );
    }


    /**
     * Redirect back to one student with a notice.
     *
     * @param int    $student_user_id Student user ID.
     * @param string $notice          Notice code.
     * @param string $type            Notice type.
     *
     * @return void
     */
    private static function redirect_student_notice(
        $student_user_id,
        $notice,
        $type,
        $args = array()
    ) {
        $redirect_args = array_merge(
            array(
                'student_notice' =>
                    sanitize_key( $notice ),

                'student_notice_type' =>
                    sanitize_key( $type ),
            ),
            is_array( $args )
                ? $args
                : array()
        );

        wp_safe_redirect(
            self::get_student_url(
                $student_user_id,
                $redirect_args
            )
        );

        exit;
    }


}
