<?php
/**
 * TutorHelper Bookings settings page.
 *
 * @package TutorHelper_Bookings
 */

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

/**
 * Registers and renders TutorHelper Bookings settings.
 */
final class TutorHelper_Settings {

	/**
	 * Settings page slug.
	 *
	 * @var string
	 */
	const PAGE_SLUG = 'tutorhelper-settings';

	/**
	 * WordPress settings group.
	 *
	 * @var string
	 */
	const SETTINGS_GROUP =
		'tutorhelper_bookings_settings';

    /**
     * WordPress settings group for page settings.
     *
     * @var string
     */
    const PAGES_SETTINGS_GROUP =
        'tutorhelper_bookings_page_settings';

    /**
     * WordPress settings group for booking settings.
     *
     * @var string
     */
    const BOOKING_SETTINGS_GROUP =
        'tutorhelper_bookings_booking_settings';


    /**
     * TutorHelper settings whose values are safe to include in logs.
     *
     * Never add secrets, API credentials or personal data here.
     *
     * @var array
     */
    const LOGGABLE_OPTIONS = array(
        TutorHelper_Currency::OPTION_CURRENCY,
    );


    /**
     * Default Settings tab.
     *
     * @var string
     */
    const DEFAULT_TAB =
        'currency';

    /**
     * Save shared email settings action.
     *
     * @var string
     */
    const SAVE_EMAIL_ACTION =
        'tutorhelper_save_email_settings';


    /**
     * Student booking page option.
     *
     * @var string
     */
    const OPTION_STUDENT_BOOKING_PAGE =
        'tutorhelper_student_booking_page_id';

    /**
     * Student dashboard page option.
     *
     * @var string
     */
    const OPTION_STUDENT_DASHBOARD_PAGE =
        'tutorhelper_student_dashboard_page_id';

    /**
     * Student login page option.
     *
     * @var string
     */
    const OPTION_LOGIN_PAGE =
        'tutorhelper_login_page_id';


	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action(
			'admin_menu',
			array(
				__CLASS__,
				'register_menu',
			)
		);

		add_action(
			'admin_init',
			array(
				__CLASS__,
				'register_settings',
			)
		);

        add_action(
            'added_option',
            array(
                __CLASS__,
                'log_changed_option',
            ),
            10,
            2
        );

        add_action(
            'updated_option',
            array(
                __CLASS__,
                'log_changed_option',
            ),
            10,
            3
        );

        add_action(
            'admin_enqueue_scripts',
            array(
                __CLASS__,
                'enqueue_assets',
            )
        );

        add_action(
            'admin_post_' . self::SAVE_EMAIL_ACTION,
            array(
                __CLASS__,
                'handle_save_email_settings',
            )
        );

	}


	/**
	 * Register the Settings submenu.
	 *
	 * @return void
	 */
	public static function register_menu() {
		add_submenu_page(
			TutorHelper_Admin::MENU_SLUG,
			__(
				'TutorHelper Settings',
				'tutorhelper-bookings'
			),
			__(
				'Settings',
				'tutorhelper-bookings'
			),
			TutorHelper_Admin::CAPABILITY,
			self::PAGE_SLUG,
			array(
				__CLASS__,
				'render_page',
			)
		);
	}

    /**
     * Load the shared Booking Hub stylesheet on the Settings page.
     *
     * @param string $hook_suffix Current WordPress admin page hook.
     *
     * @return void
     */
    public static function enqueue_assets(
        $hook_suffix
    ) {
        $expected_hook =
            'tutorhelper_page_' . self::PAGE_SLUG;

        if ( $expected_hook !== $hook_suffix ) {
            return;
        }

        $css_path =
            TUTORHELPER_BOOKINGS_PATH
            . 'assets/css/booking-hub.css';

        wp_enqueue_style(
            'tutorhelper-booking-hub',
            TUTORHELPER_BOOKINGS_URL
                . 'assets/css/booking-hub.css',
            array(),
            file_exists( $css_path )
                ? (string) filemtime( $css_path )
                : TUTORHELPER_BOOKINGS_VERSION
        );
    }



	/**
     * Register TutorHelper options.
     *
     * @return void
     */
    public static function register_settings() {
        register_setting(
            self::SETTINGS_GROUP,
            TutorHelper_Currency::OPTION_CURRENCY,
            array(
                'type'              => 'string',
                'sanitize_callback' => array(
                    'TutorHelper_Currency',
                    'sanitize_currency',
                ),
                'default'           =>
                    TutorHelper_Currency::
                        DEFAULT_CURRENCY,
            )
        );

        register_setting(
            self::PAGES_SETTINGS_GROUP,
            self::OPTION_STUDENT_BOOKING_PAGE,
            array(
                'type' =>
                    'integer',

                'sanitize_callback' =>
                    array(
                        __CLASS__,
                        'sanitize_page_id',
                    ),

                'default' =>
                    0,
            )
        );

        register_setting(
            self::PAGES_SETTINGS_GROUP,
            self::OPTION_STUDENT_DASHBOARD_PAGE,
            array(
                'type' =>
                    'integer',

                'sanitize_callback' =>
                    array(
                        __CLASS__,
                        'sanitize_page_id',
                    ),

                'default' =>
                    0,
            )
        );

        register_setting(
            self::PAGES_SETTINGS_GROUP,
            self::OPTION_LOGIN_PAGE,
            array(
                'type' =>
                    'integer',

                'sanitize_callback' =>
                    array(
                        __CLASS__,
                        'sanitize_page_id',
                    ),

                'default' =>
                    0,
            )
        );

        register_setting(
            self::BOOKING_SETTINGS_GROUP,
            TutorHelper_Booking_Tutor_Resolver::OPTION_KEY,
            array(
                'type' =>
                    'integer',

                'sanitize_callback' =>
                    array(
                        __CLASS__,
                        'sanitize_tutor_user_id',
                    ),

                'default' =>
                    0,
            )
        );

    }


    /**
     * Sanitise a selected WordPress page ID.
     *
     * @param mixed $page_id Submitted page ID.
     *
     * @return int
     */
    public static function sanitize_page_id(
        $page_id
    ) {
        $page_id =
            absint( $page_id );

        if ( ! $page_id ) {
            return 0;
        }

        $page =
            get_post(
                $page_id
            );

        if (
            ! $page
            || 'page'
            !== $page->post_type
        ) {
            return 0;
        }

        return $page_id;
    }


    /**
     * Sanitise the selected default tutor.
     *
     * Core supports one administrator tutor per site.
     *
     * @param mixed $user_id Submitted WordPress user ID.
     *
     * @return int
     */
    public static function sanitize_tutor_user_id(
        $user_id
    ) {
        $user_id =
            absint( $user_id );

        if ( ! $user_id ) {
            return 0;
        }

        $user =
            get_user_by(
                'id',
                $user_id
            );

        if ( ! $user instanceof WP_User ) {
            return 0;
        }

        if (
            ! in_array(
                'administrator',
                (array) $user->roles,
                true
            )
        ) {
            return 0;
        }

        return $user_id;
    }



	/**
	 * Render the currency selector.
	 *
	 * @return void
	 */
	public static function render_currency_field() {
		$current_currency =
			TutorHelper_Currency::get_currency();

		$currencies =
			TutorHelper_Currency::
				get_supported_currencies();

		?>
		<select
			id="<?php echo esc_attr(
				TutorHelper_Currency::OPTION_CURRENCY
			); ?>"
			name="<?php echo esc_attr(
				TutorHelper_Currency::OPTION_CURRENCY
			); ?>"
		>
			<?php
			foreach (
				$currencies
				as $currency_code => $details
			) :
				$currency_name = isset(
					$details['name']
				)
					? $details['name']
					: $currency_code;

				$currency_symbol = isset(
					$details['symbol']
				)
					? $details['symbol']
					: '';
				?>
				<option
					value="<?php echo esc_attr(
						$currency_code
					); ?>"
					<?php selected(
						$current_currency,
						$currency_code
					); ?>
				>
					<?php
					echo esc_html(
						$currency_code
						. ' — '
						. $currency_name
						. (
							$currency_symbol
								? ' (' . $currency_symbol . ')'
								: ''
						)
					);
					?>
				</option>
			<?php endforeach; ?>
		</select>

		<p class="tutorhelper-settings-field__description">
			<?php
			printf(
				/* translators: %s is a formatted example price. */
				esc_html__(
					'Example price: %s',
					'tutorhelper-bookings'
				),
				esc_html(
					TutorHelper_Currency::
						format_minor_units(
							5000,
							$current_currency,
							true
						)
				)
			);
			?>
		</p>
        <p class="tutorhelper-settings-field__description">
            <?php
            echo esc_html__(
                'Existing bookings retain the currency stored when they were created. Changing this setting only affects new prices and bookings.',
                'tutorhelper-bookings'
            );
            ?>
        </p>
		<?php
	}


    /**
     * Return TutorHelper Settings tabs.
     *
     * Allows TutorHelper extensions to add their own
     * settings sections without modifying Core.
     *
     * @return array
     */
    private static function get_tabs() {

        $tabs = array(
            'pages' => array(
                'label' =>
                    __(
                        'Pages',
                        'tutorhelper-bookings'
                    ),

                'icon' =>
                    'dashicons-admin-page',
            ),

            'booking' => array(
                'label' =>
                    __(
                        'Booking',
                        'tutorhelper-bookings'
                    ),

                'icon' =>
                    'dashicons-calendar-alt',
            ),

            'currency' => array(
                'label' =>
                    __(
                        'Currency',
                        'tutorhelper-bookings'
                    ),

                'icon' =>
                    'dashicons-money-alt',
            ),

            'email' => array(
                'label' =>
                    __(
                        'Email',
                        'tutorhelper-bookings'
                    ),

                'icon' =>
                    'dashicons-email-alt',
            ),
        );

        /**
         * Filter the available TutorHelper Settings tabs.
         *
         * @param array $tabs Settings tabs.
         */

    

        return apply_filters(
            'tutorhelper_settings_tabs',
            $tabs
        );
    }

    /**
     * Return the selected Settings tab.
     *
     * @return string
     */
    private static function get_selected_tab() {
        $tabs =
            self::get_tabs();

        $selected_tab =
            isset( $_GET['tab'] ) // 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['tab'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
                    )
                )
                : self::DEFAULT_TAB;

        return isset(
            $tabs[ $selected_tab ]
        )
            ? $selected_tab
            : self::DEFAULT_TAB;
    }

    /**
     * Return the URL for one Settings tab.
     *
     * @param string $tab Tab key.
     *
     * @return string
     */
    private static function get_tab_url(
        $tab
    ) {
        return add_query_arg(
            array(
                'page' =>
                    self::PAGE_SLUG,

                'tab' =>
                    sanitize_key(
                        $tab
                    ),
            ),
            admin_url(
                'admin.php'
            )
        );
    }

    /**
     * Render Settings navigation tabs.
     *
     * @param string $selected_tab Selected tab.
     *
     * @return void
     */
    private static function render_tabs(
        $selected_tab
    ) {
        $tabs =
            self::get_tabs();

        ?>
        <nav
            class="tutorhelper-hub-tabs tutorhelper-settings-tabs"
            aria-label="<?php echo esc_attr__(
                'TutorHelper settings sections',
                'tutorhelper-bookings'
            ); ?>"
        >
            <?php
            foreach (
                $tabs
                as $tab_key => $tab
            ) :
                $classes = array(
                    'tutorhelper-hub-tabs__tab',
                    'is-available',
                );

                if (
                    $tab_key
                    === $selected_tab
                ) {
                    $classes[] =
                        'is-active';
                }
                ?>
                <a
                    class="<?php echo esc_attr(
                        implode(
                            ' ',
                            $classes
                        )
                    ); ?>"
                    href="<?php echo esc_url(
                        self::get_tab_url(
                            $tab_key
                        )
                    ); ?>"
                    <?php
                    echo $tab_key
                        === $selected_tab
                            ? 'aria-current="page"'
                            : '';
                    ?>
                >
                    <span
                        class="dashicons <?php echo esc_attr(
                            $tab['icon']
                        ); ?>"
                        aria-hidden="true"
                    ></span>

                    <span>
                        <?php
                        echo esc_html(
                            $tab['label']
                        );
                        ?>
                    </span>
                </a>
            <?php endforeach; ?>
        </nav>
        <?php
    }


	/**
     * Render the Settings page.
     *
     * @return void
     */
    public static function render_page() {
        if (
            ! current_user_can(
                TutorHelper_Admin::CAPABILITY
            )
        ) {
            wp_die(
                esc_html__(
                    'You do not have permission to manage TutorHelper settings.',
                    'tutorhelper-bookings'
                ),
                esc_html__(
                    'Permission denied',
                    'tutorhelper-bookings'
                ),
                array(
                    'response' => 403,
                )
            );
        }

        $selected_tab =
            self::get_selected_tab();

        ?>
        <div
            class="
                wrap
                tutorhelper-booking-hub
                tutorhelper-settings-page
            "
        >
            <header
                class="tutorhelper-booking-hub__heading"
            >
                <div>
                    <h1>
                        <?php
                        echo esc_html__(
                            'TutorHelper Settings',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </h1>

                    <p>
                        <?php
                        echo esc_html__(
                            'Configure the shared settings used throughout TutorHelper Bookings.',
                            'tutorhelper-bookings'
                        );
                        ?>
                    </p>
                </div>
            </header>

            <?php
            self::render_tabs(
                $selected_tab
            );
            ?>

            <div
                class="tutorhelper-hub-workspace"
            >
                <?php
                switch ( $selected_tab ) {

                case 'email':
                    self::render_email_tab();
                    break;

                case 'pages':
                    settings_errors();

                    self::render_pages_tab();
                    break;

                case 'booking':
                settings_errors();

                self::render_booking_tab();
                break;

                case 'currency':
                    settings_errors();

                    self::render_currency_tab();
                    break;

                default:
                    /**
                     * Allow TutorHelper extensions to render
                     * their own Settings tab content.
                     *
                     * @param string $selected_tab Selected tab key.
                     */
                    do_action(
                        'tutorhelper_settings_render_tab',
                        $selected_tab
                    );
                    break;
            }
                ?>
            </div>
        </div>
        <?php
    }


    /**
     * Render one TutorHelper page selector.
     *
     * @param string $option_name Option name.
     * @param string $label       Field label.
     * @param string $description Field description.
     *
     * @return void
     */
    private static function render_page_selector(
        $option_name,
        $label,
        $description
    ) {
        $current_page_id =
            absint(
                get_option(
                    $option_name,
                    0
                )
            );

        ?>
        <div
            class="
                tutorhelper-input-field
                is-full-width
            "
        >
            <label
                for="<?php echo esc_attr(
                    $option_name
                ); ?>"
            >
                <?php
                echo esc_html(
                    $label
                );
                ?>
            </label>

            <?php
            wp_dropdown_pages(
                array(
                    'name' =>
                        esc_attr(
                            $option_name
                        ),

                    'id' =>
                        esc_attr(
                            $option_name
                        ),

                    'selected' =>
                        absint(
                            $current_page_id
                        ),

                    'show_option_none' =>
                        esc_html__(
                            '— Select a page —',
                            'tutorhelper-bookings'
                        ),

                    'option_none_value' =>
                        '0',

                    'post_status' =>
                        array(
                            'publish',
                            'private',
                            'draft',
                        ),
                )
            );
            ?>

            <p
                class="tutorhelper-settings-field__description"
            >
                <?php
                echo esc_html(
                    $description
                );
                ?>
            </p>
        </div>
        <?php
    }


    /**
     * Render TutorHelper page settings.
     *
     * @return void
     */
    private static function render_pages_tab() {
        ?>
        <form
            method="post"
            action="options.php"
            class="tutorhelper-settings-form"
        >
            <?php
            settings_fields(
                self::PAGES_SETTINGS_GROUP
            );
            ?>

            <section
                class="tutorhelper-main-section"
            >
                <header
                    class="
                        tutorhelper-main-section__header
                        is-compact
                    "
                >
                    <div
                        class="
                            tutorhelper-main-section__header-content
                        "
                    >
                        <h2>
                            <?php
                            esc_html_e(
                                'TutorHelper pages',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </h2>

                        <p>
                            <?php
                            esc_html_e(
                                'Choose the WordPress pages used for student booking, lesson management and login links.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>
                </header>

                <div
                    class="
                        tutorhelper-main-section__body
                        tutorhelper-settings-section__body
                    "
                >
                    <div
                        class="tutorhelper-input-fields"
                    >
                        <?php
                        self::render_page_selector(
                            self::OPTION_STUDENT_BOOKING_PAGE,
                            __(
                                'Student booking page',
                                'tutorhelper-bookings'
                            ),
                            __(
                                'Select the page containing the [tutorhelper_student_booking] shortcode.',
                                'tutorhelper-bookings'
                            )
                        );

                        self::render_page_selector(
                            self::OPTION_STUDENT_DASHBOARD_PAGE,
                            __(
                                'Student dashboard page',
                                'tutorhelper-bookings'
                            ),
                            __(
                                'Select the page containing the [tutorhelper_student_dashboard] shortcode.',
                                'tutorhelper-bookings'
                            )
                        );

                        self::render_page_selector(
                            self::OPTION_LOGIN_PAGE,
                            __(
                                'Login page',
                                'tutorhelper-bookings'
                            ),
                            __(
                                'Select the page students should use to log in. Leave blank to use the standard WordPress login page.',
                                'tutorhelper-bookings'
                            )
                        );
                        ?>
                    </div>

                    <div
                        class="tutorhelper-settings-form__actions"
                    >
                        <?php
                        submit_button(
                            __(
                                'Save page settings',
                                'tutorhelper-bookings'
                            ),
                            'primary tutorhelper-action-button',
                            'submit',
                            false
                        );
                        ?>
                    </div>
                </div>
            </section>
        </form>
        <?php
    }


    /**
     * Render the Booking settings tab.
     *
     * @return void
     */
    private static function render_booking_tab() {

        $current_tutor_id =
            absint(
                get_option(
                    TutorHelper_Booking_Tutor_Resolver::
                        OPTION_KEY,
                    0
                )
            );

        $administrators =
            get_users(
                array(
                    'role' =>
                        'administrator',

                    'orderby' =>
                        'display_name',

                    'order' =>
                        'ASC',
                )
            );

        ?>
        <form
            method="post"
            action="options.php"
            class="tutorhelper-settings-form"
        >
            <?php
            settings_fields(
                self::BOOKING_SETTINGS_GROUP
            );
            ?>

            <section
                class="tutorhelper-main-section"
            >
                <header
                    class="
                        tutorhelper-main-section__header
                        is-compact
                    "
                >
                    <div
                        class="
                            tutorhelper-main-section__header-content
                        "
                    >
                        <h2>
                            <?php
                            esc_html_e(
                                'Booking',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </h2>

                        <p>
                            <?php
                            esc_html_e(
                                'Configure how students are matched with lesson availability.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>
                </header>

                <div
                    class="
                        tutorhelper-main-section__body
                        tutorhelper-settings-section__body
                    "
                >
                    <div
                        class="tutorhelper-input-fields"
                    >
                        <div
                            class="
                                tutorhelper-input-field
                                is-full-width
                            "
                        >
                            <label
                                for="<?php
                                    echo esc_attr(
                                        TutorHelper_Booking_Tutor_Resolver::
                                            OPTION_KEY
                                    );
                                ?>"
                            >
                                <?php
                                esc_html_e(
                                    'Default Tutor',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <select
                                id="<?php
                                    echo esc_attr(
                                        TutorHelper_Booking_Tutor_Resolver::
                                            OPTION_KEY
                                    );
                                ?>"
                                name="<?php
                                    echo esc_attr(
                                        TutorHelper_Booking_Tutor_Resolver::
                                            OPTION_KEY
                                    );
                                ?>"
                            >
                                <option value="0">
                                    <?php
                                    esc_html_e(
                                        '— Select a tutor —',
                                        'tutorhelper-bookings'
                                    );
                                    ?>
                                </option>

                                <?php
                                foreach (
                                    $administrators
                                        as $administrator
                                ) :
                                    ?>
                                    <option
                                        value="<?php
                                            echo esc_attr(
                                                $administrator->ID
                                            );
                                        ?>"
                                        <?php
                                        selected(
                                            $current_tutor_id,
                                            $administrator->ID
                                        );
                                        ?>
                                    >
                                        <?php
                                        echo esc_html(
                                            $administrator
                                                ->display_name
                                        );
                                        ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>

                            <p
                                class="
                                    tutorhelper-settings-field__description
                                "
                            >
                                <?php
                                esc_html_e(
                                    'Students booking lessons on this site will see availability belonging to this tutor. TutorHelper Core supports one booking tutor per site.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </p>
                        </div>
                    </div>

                    <div
                        class="
                            tutorhelper-settings-form__actions
                        "
                    >
                        <?php
                        submit_button(
                            __(
                                'Save booking settings',
                                'tutorhelper-bookings'
                            ),
                            'primary tutorhelper-action-button',
                            'submit',
                            false
                        );
                        ?>
                    </div>
                </div>
            </section>
        </form>
        <?php
    }




    /**
     * Render the Currency settings tab.
     *
     * @return void
     */
    private static function render_currency_tab() {
        ?>
        <form
            method="post"
            action="options.php"
            class="tutorhelper-settings-form"
        >
            <?php
            settings_fields(
                self::SETTINGS_GROUP
            );
            ?>

            <section class="tutorhelper-main-section">
                <header
                    class="
                        tutorhelper-main-section__header
                        is-compact
                    "
                >
                    <div
                        class="
                            tutorhelper-main-section__header-content
                        "
                    >
                        <h2>
                            <?php
                            echo esc_html__(
                                'Currency',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </h2>

                        <p>
                            <?php
                            echo esc_html__(
                                'Choose the currency used for Booking Type prices and new bookings.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>
                </header>

                <div
                    class="
                        tutorhelper-main-section__body
                        tutorhelper-settings-section__body
                    "
                >
                    <div class="tutorhelper-input-fields">
                        <div
                            class="
                                tutorhelper-input-field
                                is-full-width
                            "
                        >
                            <label
                                for="<?php echo esc_attr(
                                    TutorHelper_Currency::
                                        OPTION_CURRENCY
                                ); ?>"
                            >
                                <?php
                                echo esc_html__(
                                    'Working currency',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <?php
                            self::render_currency_field();
                            ?>
                        </div>
                    </div>

                    <div
                        class="tutorhelper-settings-form__actions"
                    >
                        <?php
                        submit_button(
                            __(
                                'Save settings',
                                'tutorhelper-bookings'
                            ),
                            'primary tutorhelper-action-button',
                            'submit',
                            false
                        );
                        ?>
                    </div>
                </div>
            </section>
        </form>
        <?php
    }


    /**
     * Render shared Email settings.
     *
     * @return void
     */
    private static function render_email_tab() {
        $settings =
            TutorHelper_Email_Settings::get_all();

        self::render_email_notice();

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

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

            <section class="tutorhelper-main-section">
                <header
                    class="
                        tutorhelper-main-section__header
                        is-compact
                    "
                >
                    <div
                        class="
                            tutorhelper-main-section__header-content
                        "
                    >
                        <h2>
                            <?php
                            echo esc_html__(
                                'Email sender details',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </h2>

                        <p>
                            <?php
                            echo esc_html__(
                                'Configure the contact and privacy details shown in automatic TutorHelper emails.',
                                'tutorhelper-bookings'
                            );
                            ?>
                        </p>
                    </div>
                </header>

                <div
                    class="
                        tutorhelper-main-section__body
                        tutorhelper-settings-section__body
                    "
                >
                    <div class="tutorhelper-input-fields">
                        <div
                            class="
                                tutorhelper-input-field
                                is-full-width
                            "
                        >
                            <label
                                for="tutorhelper-email-sender-name"
                            >
                                <?php
                                echo esc_html__(
                                    'Sender name',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="text"
                                id="tutorhelper-email-sender-name"
                                name="sender_name"
                                value="<?php echo esc_attr(
                                    $settings[
                                        'sender_name'
                                    ]
                                ); ?>"
                                required
                            />

                            <p
                                class="tutorhelper-settings-field__description"
                            >
                                <?php
                                echo esc_html__(
                                    'Shown in the footer to identify the tutor or business sending the email.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </p>
                        </div>

                        <div
                            class="
                                tutorhelper-input-field
                                is-full-width
                            "
                        >
                            <label
                                for="tutorhelper-email-contact-email"
                            >
                                <?php
                                echo esc_html__(
                                    'Contact email',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="email"
                                id="tutorhelper-email-contact-email"
                                name="contact_email"
                                value="<?php echo esc_attr(
                                    $settings[
                                        'contact_email'
                                    ]
                                ); ?>"
                                required
                            />

                            <p
                                class="tutorhelper-settings-field__description"
                            >
                                <?php
                                echo esc_html__(
                                    'Displayed as the contact address in automatic email footers.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </p>
                        </div>

                        <div
                            class="
                                tutorhelper-input-field
                                is-full-width
                            "
                        >
                            <label
                                for="tutorhelper-email-privacy-policy"
                            >
                                <?php
                                echo esc_html__(
                                    'Privacy policy',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </label>

                            <input
                                type="url"
                                id="tutorhelper-email-privacy-policy"
                                name="privacy_policy_url"
                                value="<?php echo esc_attr(
                                    $settings[
                                        'privacy_policy_url'
                                    ]
                                ); ?>"
                            />

                            <p
                                class="tutorhelper-settings-field__description"
                            >
                                <?php
                                echo esc_html__(
                                    'TutorHelper uses the published WordPress Privacy Policy page by default. You can provide a different URL here.',
                                    'tutorhelper-bookings'
                                );
                                ?>
                            </p>
                        </div>
                    </div>

                    <div
                        class="tutorhelper-settings-form__actions"
                    >
                        <?php
                        submit_button(
                            __(
                                'Save email settings',
                                'tutorhelper-bookings'
                            ),
                            'primary tutorhelper-action-button',
                            'submit',
                            false
                        );
                        ?>
                    </div>
                </div>
            </section>
        </form>
        <?php
    }


    /**
     * Save shared TutorHelper Email settings.
     *
     * @return void
     */
    public static function handle_save_email_settings() {
        if (
            ! current_user_can(
                TutorHelper_Admin::CAPABILITY
            )
        ) {
            wp_die(
                esc_html__(
                    'You do not have permission to manage TutorHelper settings.',
                    'tutorhelper-bookings'
                ),
                esc_html__(
                    'Permission denied',
                    'tutorhelper-bookings'
                ),
                array(
                    'response' => 403,
                )
            );
        }

        check_admin_referer(
            self::SAVE_EMAIL_ACTION
        );

        $result =
            TutorHelper_Email_Settings::save(
                $_POST
            );

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

        self::redirect_email_settings(
            'saved'
        );
    }

    /**
     * Redirect back to the Email settings tab.
     *
     * @param string $status     Result status.
     * @param string $error_code Optional error code.
     *
     * @return void
     */
    private static function redirect_email_settings(
        $status,
        $error_code = ''
    ) {
        $args = array(
            'page' =>
                self::PAGE_SLUG,

            'tab' =>
                'email',

            'tutorhelper_email_settings_status' =>
                sanitize_key(
                    $status
                ),
        );

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

        wp_safe_redirect(
            add_query_arg(
                $args,
                admin_url(
                    'admin.php'
                )
            )
        );

        exit;
    }


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

        if ( 'saved' === $status ) {
            ?>
            <div
                class="notice notice-success inline"
            >
                <p>
                    <?php
                    echo esc_html__(
                        'Email settings saved.',
                        'tutorhelper-bookings'
                    );
                    ?>
                </p>
            </div>
            <?php

            return;
        }

        if ( 'error' === $status ) {
            ?>
            <div
                class="notice notice-error inline"
            >
                <p>
                    <?php
                    echo esc_html__(
                        'The email settings could not be saved. Check the sender name and contact email and try again.',
                        'tutorhelper-bookings'
                    );
                    ?>
                </p>
            </div>
            <?php
        }
    }



    /**
     * Return the configured student booking URL.
     *
     * @return string
     */
    public static function get_student_booking_url() {
        return self::get_page_url(
            self::OPTION_STUDENT_BOOKING_PAGE
        );
    }

    /**
     * Return the configured student dashboard URL.
     *
     * @return string
     */
    public static function get_student_dashboard_url() {
        return self::get_page_url(
            self::OPTION_STUDENT_DASHBOARD_PAGE
        );
    }

    /**
     * Return the configured login URL.
     *
     * @return string
     */
    public static function get_login_url() {
        $url =
            self::get_page_url(
                self::OPTION_LOGIN_PAGE
            );

        return $url
            ? $url
            : wp_login_url();
    }

    /**
     * Return the permalink for one configured page option.
     *
     * @param string $option_name Page option.
     *
     * @return string
     */
    private static function get_page_url(
        $option_name
    ) {
        $page_id =
            absint(
                get_option(
                    $option_name,
                    0
                )
            );

        if ( ! $page_id ) {
            return '';
        }

        $url =
            get_permalink(
                $page_id
            );

        return $url
            ? esc_url_raw(
                $url
            )
            : '';
    }




    /**
     * Log the creation or update of a TutorHelper setting.
     *
     * This callback is used for both added_option and updated_option.
     *
     * @param string $option_name Option name.
     * @param mixed  $old_value   New value for added_option, or previous value
     *                            for updated_option.
     * @param mixed  $new_value   New value for updated_option.
     *
     * @return void
     */
    public static function log_changed_option(
        $option_name,
        $old_value,
        $new_value = null
    ) {
        if (
            ! in_array(
                $option_name,
                self::LOGGABLE_OPTIONS,
                true
            )
        ) {
            return;
        }

        $is_update = null !== $new_value;

        if ( $is_update ) {
            $previous_value = $old_value;
            $saved_value    = $new_value;
        } else {
            $previous_value = null;
            $saved_value    = $old_value;
        }

        $changed_setting = sanitize_key(
            $option_name
        );

        $clean_new_value = strtoupper(
            sanitize_text_field(
                (string) $saved_value
            )
        );

        $current_user = wp_get_current_user();
        $current_username = $current_user->user_login;


        $context = array(
            'setting'    => $changed_setting,
            'new_value'  => $clean_new_value,
            'changed_by' => $current_username,
        );

        if ( $is_update ) {
            $clean_old_value = strtoupper(
                sanitize_text_field(
                    (string) $previous_value
                )
            );

            /*
            * Avoid logging when WordPress receives the same value again.
            */
            if ( $clean_old_value === $clean_new_value ) {
                return;
            }

            $context['old_value'] =
                $clean_old_value;

            TutorHelper_Logger::success(
                'TutorHelper setting updated.',
                $context
            );

            return;
        }

        TutorHelper_Logger::success(
            'TutorHelper setting created.',
            $context
        );
    }



}
