<?php

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

if ( ! class_exists( 'SBUY_Settings' ) ) {
    /**
     * Settings class
     *
     * @since 1.0.0
     */
    class SBUY_Settings {

        private string $admin_url;
        private mixed $options_finance;
        private string $option_group_finance;
        private string $option_page_finance;
        private mixed $options_pages;
        private string $option_group_pages;
        private string $option_page_pages;
        private mixed $options_google;
        private string $option_group_google;
        private string $option_page_google;
        private mixed $options_time;
        private string $option_group_time;
        private string $option_page_time;
        private mixed $options_checkout;
        private string $option_group_checkout;
        private string $option_page_checkout;
        private mixed $options_privacy;
        private string $option_group_privacy;
        private string $option_page_privacy;
        private mixed $options_debug;
        private string $option_group_debug;
        private string $option_page_debug;
        private mixed $options_branding;
        private string $option_group_branding;
        private string $option_page_branding;
        private mixed $options_support;
        private string $option_group_support;
        private string $option_page_support;
        private mixed $options_email;
        private string $option_group_email;
        private string $option_page_email;

        public function __construct() {

            $this->admin_url             = 'admin.php?page=simply-buy';
            $this->option_group_finance  = 'sbuy_settings_finance';
            $this->option_page_finance   = 'settings-finance';
            $this->option_group_pages    = 'sbuy_settings_pages';
            $this->option_page_pages     = 'settings-pages';
            $this->option_group_google   = 'sbuy_settings_google';
            $this->option_page_google    = 'settings-google';
            $this->option_group_time     = 'sbuy_settings_time';
            $this->option_page_time      = 'settings-time';
            $this->option_group_checkout = 'sbuy_settings_checkout';
            $this->option_page_checkout  = 'settings-checkout';
            $this->option_group_privacy  = 'sbuy_settings_privacy';
            $this->option_page_privacy   = 'settings-privacy';
            $this->option_group_debug    = 'sbuy_settings_debug';
            $this->option_page_debug     = 'settings-debug';
            $this->option_group_branding = 'sbuy_settings_branding';
            $this->option_page_branding  = 'settings-branding';
            $this->option_group_support  = 'sbuy_settings_support';
            $this->option_page_support   = 'settings-support';
            $this->option_group_email    = 'sbuy_settings_email';
            $this->option_page_email     = 'settings-email';

            $this->options_finance  = get_option( $this->option_group_finance );
            $this->options_pages    = get_option( $this->option_group_pages );
            $this->options_google   = get_option( $this->option_group_google );
            $this->options_time     = get_option( $this->option_group_time );
            $this->options_checkout = get_option( $this->option_group_checkout );
            $this->options_privacy  = get_option( $this->option_group_privacy );
            $this->options_debug    = get_option( $this->option_group_debug );
            $this->options_branding = get_option( $this->option_group_branding );
            $this->options_support  = get_option( $this->option_group_support );
            $this->options_email    = get_option( $this->option_group_email );

            add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
            add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue' ) );

            add_action( 'admin_init', array( $this, 'handle_branding_choice' ), 0 );
            add_action( 'admin_init', array( $this, 'options_init' ) );
        }

        /**
         * Prevent rapid enable/disable toggling of branding.
         *
         * Adjust the cooldown as desired (e.g. WEEK_IN_SECONDS).
         */
        private const SBUY_BRANDING_TOGGLE_COOLDOWN = DAY_IN_SECONDS;

        /**
         * Pro pricing URL is translatable so locale-specific landing pages can be used.
         */
        private function sbuy_get_pro_pricing_url(): string {
            return __( 'https://profitclicker.com/pricing/', 'simply-buy' );
        }

        private function sbuy_get_branding_toggle_blocked_until(): int {
            return (int) get_option( 'sbuy_branding_toggle_blocked_until', 0 );
        }

        private function sbuy_can_toggle_branding(): bool {
            return time() >= $this->sbuy_get_branding_toggle_blocked_until();
        }

        /**
         * Set branding flag with rate-limit protection.
         */
        private function sbuy_set_branding( bool $enable ): void {
            $current         = (array) get_option( $this->option_group_branding, array() );
            $current_enabled = ! empty( $current['show_branding'] );

            if ( $current_enabled === $enable ) {
                return;
            }

            if ( ! $enable && ! $this->sbuy_can_toggle_branding() ) {
                $until = $this->sbuy_get_branding_toggle_blocked_until();
                $human = wp_date( 'Y-m-d H:i', $until );

                add_settings_error( $this->option_group_branding, 'sbuy_branding_toggle_rate_limited', sprintf( /* translators: %s: date/time */ __( 'You can disable branding again after %s.', 'simply-buy' ), esc_html( $human ) ), 'error' );

                return;
            }

            update_option( $this->option_group_branding, array( 'show_branding' => $enable ? 1 : 0 ) );

            if ( ! $enable ) {
                update_option( 'sbuy_branding_toggle_blocked_until', time() + self::SBUY_BRANDING_TOGGLE_COOLDOWN );
            }
        }

        public function handle_branding_choice(): void {
            $page = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';

            if ( $page !== 'simply-buy' ) {
                return;
            }

            if ( isset( $_POST['sbuy_branding_enable'] ) && check_admin_referer( 'sbuy_branding_choice', 'sbuy_branding_nonce' ) ) {
                $this->sbuy_set_branding( true );
            }

            if ( isset( $_POST['sbuy_branding_dismiss'] ) && check_admin_referer( 'sbuy_branding_dismiss', 'sbuy_branding_dismiss_nonce' ) ) {
                update_option( 'sbuy_branding_notice_dismissed', time() );
            }
        }

        public function add_plugin_page(): void {
            // This page will be under "WooCommerce"
            add_menu_page( esc_html__( 'SimplyBuy Settings', 'simply-buy' ), esc_html__( 'SimplyBuy', 'simply-buy' ), 'manage_options', 'simply-buy', array(
                    $this,
                    'create_admin_page'
            ), 'dashicons-performance', 90 );

            add_submenu_page( 'simply-buy', esc_html__( 'Bookings', 'simply-buy' ), esc_html__( 'Bookings', 'simply-buy' ), 'manage_options', 'simply-buy-bookings', array(
                    $this,
                    'bookings_page'
            ), );
        }

        public function admin_enqueue( $hook ): void {

            if ( 'toplevel_page_simply-buy' != $hook ) {
                return;
            }

            wp_register_style( 'sbuy_admin', SBUY_CORE_PLUGIN_URL . 'admin/assets/style/sb-admin.min.css', false, SBUY_PLUGIN_VERSION );
            wp_enqueue_style( 'sbuy_admin' );

            wp_enqueue_style( 'plugin-install' );

            wp_enqueue_script( 'plugin-install' );
            wp_enqueue_script( 'updates' );

            add_thickbox();
        }

        public function create_admin_page(): void {

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
            $active_page = sanitize_text_field( ( $_GET['tab'] ?? 'finance' ) ); // set default tab
            // Hide the support notice once branding is enabled (legacy unlock), even without Pro add-on.
            $branding_enabled          = (bool) sbuy_get_options( 'show_branding', $this->option_group_branding );
            $dismissed_at              = (int) get_option( 'sbuy_branding_notice_dismissed', 0 );
            $is_dismissed              = ( $dismissed_at > 0 ) && ( time() < ( $dismissed_at + 30 * DAY_IN_SECONDS ) );
            $show_support_brand_notice = ( ! sbuy_has_pro_plugin_access() && ! $branding_enabled && ! $is_dismissed && 'finance' === $active_page );
            ?>

            <div class="wrap">
                <h1><?php esc_html_e( 'Simply Buy Settings', 'simply-buy' ); ?></h1>
                <?php
                if ( $show_support_brand_notice ) {
                    ?>
                    <div class="notice notice-info" style="padding:12px; display: flex; flex-wrap: wrap; justify-content: space-between;">
                        <div>
                            <p><strong><?php esc_html_e( 'Support SimplyBuy', 'simply-buy' ); ?></strong></p>
                            <p><?php esc_html_e( 'By enabling the SimplyBuy branding, you help keep the plugin free for everyone – and enjoy all the pro features yourself.', 'simply-buy' ); ?></p>
                            <div style="margin-top:8px; display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
                                <form method="post" style="margin:0;">
                                    <?php wp_nonce_field( 'sbuy_branding_choice', 'sbuy_branding_nonce' ); ?>
                                    <input type="submit" name="sbuy_branding_enable" class="button button-primary"
                                           value="<?php esc_attr_e( 'Enable branding — Pro features for free', 'simply-buy' ); ?>">
                                </form>
                                <form method="post" style="margin:0;">
                                    <?php wp_nonce_field( 'sbuy_branding_dismiss', 'sbuy_branding_dismiss_nonce' ); ?>
                                    <button type="submit" name="sbuy_branding_dismiss" class="button-link" style="color:#646970; text-decoration:none;">
                                        <?php esc_html_e( 'No thanks', 'simply-buy' ); ?>
                                    </button>
                                </form>
                            </div>
                        </div>
                        <img src="<?php echo esc_url( SBUY_CORE_PLUGIN_URL . 'assets/branding.png' ); ?>" alt="Simply Buy"
                             style="width: 500px; max-width: 100%;">
                    </div>
                    <?php
                }
                settings_errors(); ?>
                <h2 class="nav-tab-wrapper">
                    <a href="<?php echo esc_url( admin_url( $this->admin_url ) ); ?>"
                       class="nav-tab<?php echo( 'finance' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Finance', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'pages' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'pages' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Pages', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'google' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'google' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Calendar', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'time' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'time' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Time', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'checkout' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'checkout' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Checkout', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'privacy' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'privacy' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Terms and Conditions', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'email' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'email' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Email', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'support' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'support' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Support', 'simply-buy' ); ?></a>
                    <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'debug' ), admin_url( $this->admin_url ) ) ); ?>"
                       class="nav-tab<?php echo( 'debug' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Debug', 'simply-buy' ); ?></a>
                    <?php if ( ! sbuy_has_pro_plugin_access() ) { ?>
                        <a href="<?php echo esc_url( add_query_arg( array( 'tab' => 'branding' ), admin_url( $this->admin_url ) ) ); ?>"
                           class="nav-tab<?php echo( 'branding' == $active_page ? ' nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Branding', 'simply-buy' ); ?></a>
                    <?php } ?>
                </h2>

                <form method="post" action="options.php">
                    <?php
                    switch ( $active_page ) {
                        case 'pages':
                            settings_fields( $this->option_group_pages );
                            do_settings_sections( $this->option_page_pages );
                            break;
                        case 'google':
                            settings_fields( $this->option_group_google );
                            do_settings_sections( $this->option_page_google );
                            break;
                        case 'time':
                            settings_fields( $this->option_group_time );
                            do_settings_sections( $this->option_page_time );
                            break;
                        case 'checkout':
                            settings_fields( $this->option_group_checkout );
                            do_settings_sections( $this->option_page_checkout );
                            break;
                        case 'privacy':
                            settings_fields( $this->option_group_privacy );
                            do_settings_sections( $this->option_page_privacy );
                            break;
                        case 'email':
                            settings_fields( $this->option_group_email );
                            do_settings_sections( $this->option_page_email );
                            break;
                        case 'support':
                            settings_fields( $this->option_group_support );
                            do_settings_sections( $this->option_page_support );
                            break;
                        case 'debug':
                            settings_fields( $this->option_group_debug );
                            do_settings_sections( $this->option_page_debug );
                            break;
                        case 'branding':
                            if ( ! sbuy_has_pro_plugin_access() ) {
                                settings_fields( $this->option_group_branding );
                                do_settings_sections( $this->option_page_branding );
                            }
                            break;
                        default:
                            settings_fields( $this->option_group_finance );
                            do_settings_sections( $this->option_page_finance );
                            break;
                    }

                    // Branding tab uses its own Yes/No buttons (auto-submit), so no generic Save button there.
                    if ( ! in_array( $active_page, [ 'debug', 'support', 'branding' ], true ) ) {
                        submit_button();
                    }
                    ?>
                </form>

            </div>
            <?php
        }

        /**
         * Booking submenu page
         *
         * @since 1.0.0
         */
        public function bookings_page(): void {

            global $wp_locale;
            $today = wp_date( 'Y-m-d' );
            $years = range( gmdate( 'Y' ), gmdate( 'Y' ) + 3 );
            ?>
            <div class="wrap">
                <h1><?php esc_html_e( 'Simply Buy Bookings', 'simply-buy' ); ?></h1>

                <?php if ( sbuy_has_pro_access() ) { ?>
                    <button id="booking-open-popup"
                            class="button button-primary"><?php echo esc_html__( 'Generate Order Link', 'simply-buy' ); ?></button>
                <?php } ?>

                <?php
                $sbuy_bulk_days = array(
                    0 => __( 'All Sundays', 'simply-buy' ),
                    1 => __( 'All Mondays', 'simply-buy' ),
                    2 => __( 'All Tuesdays', 'simply-buy' ),
                    3 => __( 'All Wednesdays', 'simply-buy' ),
                    4 => __( 'All Thursdays', 'simply-buy' ),
                    5 => __( 'All Fridays', 'simply-buy' ),
                    6 => __( 'All Saturdays', 'simply-buy' ),
                );
                $sbuy_bulk_pro = sbuy_has_pro_access();
                ?>
                <div class="sbuy-bulk-actions" style="margin-top:18px; margin-bottom:20px; display:flex; align-items:center; gap:8px; flex-wrap:wrap;<?php echo $sbuy_bulk_pro ? '' : ' opacity:0.5; pointer-events:none;'; ?>">
                    <label><strong><?php esc_html_e( 'Block days:', 'simply-buy' ); ?></strong></label>
                    <select id="sbuy-bulk-day-select" <?php disabled( ! $sbuy_bulk_pro ); ?>>
                        <option value=""><?php esc_html_e( 'Select weekday...', 'simply-buy' ); ?></option>
                        <?php foreach ( $sbuy_bulk_days as $day_num => $label ) : ?>
                            <option value="<?php echo esc_attr( $day_num ); ?>"><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="sbuy-bulk-block-btn" class="button button-primary" <?php disabled( ! $sbuy_bulk_pro ); ?>>
                        <?php esc_html_e( 'Block', 'simply-buy' ); ?>
                    </button>
                    <button type="button" id="sbuy-bulk-unblock-all" class="button button-secondary" style="margin-left:16px;" <?php disabled( ! $sbuy_bulk_pro ); ?>>
                        <?php esc_html_e( 'Remove bulk blocks', 'simply-buy' ); ?>
                    </button>
                </div>
                <?php if ( ! $sbuy_bulk_pro ) : ?>
                    <p style="font-size:12px; color:#888; margin-top:-12px;">⭐
                        <?php esc_html_e( 'Pro feature — ', 'simply-buy' ); ?>
                        <a href="<?php echo esc_url( __( 'https://profitclicker.com/pricing/', 'simply-buy' ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upgrade to Pro', 'simply-buy' ); ?></a>
                    </p>
                <?php endif; ?>

                <div id="year-tabs">
                    <div id="year-select-area" class="formfield formfield__half">
                        <label for="year-select" class="screen-reader-text"><?php echo esc_html__( 'Select year', 'simply-buy' ); ?>
                            <span>*</span></label>
                        <select name="year-select" id="year-select">
                            <?php
                            foreach ( $years as $year ) {
                                ?>
                                <option value="<?php echo esc_attr( $year ); ?>" <?php echo gmdate( 'Y' ) == $year ? 'selected' : ''; ?>><?php echo esc_html( $year ); ?></option>
                                <?php
                            }
                            ?>
                        </select>
                    </div>
                    <ul>
                        <?php
                        foreach ( $years as $year ) {
                            ?>
                            <li><a href="#<?php echo esc_attr( $year ); ?>"><?php echo esc_html( $year ); ?></a></li>
                            <?php
                        }
                        ?>
                    </ul>
                    <?php
                    foreach ( $years as $year ) {
                        ?>
                        <div id="<?php echo esc_attr( $year ); ?>" style="overflow-x: auto;">
                            <table class="sp-date-table">
                                <tr class="header">
                                    <td class="cell cell__heading"><?php echo esc_html( $year ); ?></td>
                                    <?php
                                    for ( $i = 1; $i <= 31; $i ++ ) {
                                        echo '<td class="cell">' . esc_html( $i ) . '</td>';
                                    }
                                    ?>
                                </tr>
                                <?php
                                $months = range( 1, 12 );
                                foreach ( $months as $month ) {
                                    if ( $month === 7 ) {
                                        echo '<tr class="header">';
                                        echo '<td class="cell cell__heading"></td>';
                                        for ( $i = 1; $i <= 31; $i ++ ) {
                                            echo '<td class="cell">' . esc_html( $i ) . '</td>';
                                        }
                                        echo '</tr>';
                                    }

                                    $month_attr = DateTime::createFromFormat( '!m', $month )->format( 'F' );
                                    $month_name = $wp_locale->get_month( $month );
                                    ?>
                                    <tr class="<?php echo esc_attr( strtolower( $month_attr ) ); ?>">
                                        <td class="cell cell__heading"><?php echo esc_attr( $month_name ); ?></td>
                                        <?php
                                        $days_of_this_month = cal_days_in_month( CAL_GREGORIAN, $month, $year );
                                        for ( $i = 1; $i <= $days_of_this_month; $i ++ ) {
                                            $date                          = wp_date( 'Y-m-d', strtotime( $year . '-' . $month . '-' . $i ) );
                                            $formatted_date                = strtotime( $date );
                                            $sbuy_has_available_slot_class = sbuy_has_available_slot( $formatted_date ) <= 0 ? 'full-house' : '';
                                            echo '<td class="cell ' . esc_attr( $sbuy_has_available_slot_class ) . '">';
                                            $disable_class = $date < $today ? 'disabled' : '';
                                            foreach ( range( 1, 6 ) as $index => $time ) {
                                                $popup       = ( $index < 3 ) ? esc_html__( 'Morning', 'simply-buy' ) : ( $index >= 3 || $index < 6 ? esc_html__( 'Afternoon', 'simply-buy' ) : '' );
                                                $slot        = ( $index < 3 ) ? 'morning' : ( $index >= 3 || $index < 6 ? 'afternoon' : '' );
                                                $database_id = sbuy_get_id( $formatted_date, $slot, $index );
                                                $is_booked   = sbuy_check_booked( $formatted_date, $index ) ? 'checked' : '';
                                                echo '<input type="checkbox" name="date" data-date="' . esc_attr( $date ) . '" data-slot="' . esc_attr( $slot ) . '" data-index="' . esc_attr( $database_id ) . '" title="' . esc_attr( $popup ) . '" ' . esc_attr( $disable_class ) . ' ' . esc_attr( $is_booked ) . ' />';

                                            }
                                            echo '</td>';
                                        }
                                        ?>
                                    </tr>
                                    <?php
                                }
                                ?>

                                <tr class="footer">
                                    <td class="cell cell__heading"><?php echo esc_html( $year ); ?></td>
                                    <?php
                                    for ( $i = 1; $i <= 31; $i ++ ) {
                                        echo '<td class="cell">' . esc_html( $i ) . '</td>';
                                    }
                                    ?>
                                </tr>
                            </table>
                        </div>
                        <?php
                    } ?>
                </div>
            </div>
            <?php
        }

        /**
         * Initialize Options on Settings Page
         */
        public function options_init(): void {

            $this->options_finance();

            register_setting( $this->option_group_finance, // Option group
                    $this->option_group_finance, // Option name
                    array( $this, 'sanitize' ) // Sanitize
            );

            $this->options_pages();

            register_setting( $this->option_group_pages, // Option group
                    $this->option_group_pages, // Option name
                    array( $this, 'sanitize' ) // Sanitize
            );

            $this->options_google();

            register_setting( $this->option_group_google, // Option group
                    $this->option_group_google, // Option name
                    array( $this, 'sanitize' ) // Sanitize
            );

            $this->options_time();

            register_setting( $this->option_group_time, // Option group
                    $this->option_group_time, // Option name
                    array( $this, 'sanitize' ) // Sanitize
            );

            $this->options_checkout();

            register_setting( $this->option_group_checkout, $this->option_group_checkout, array( $this, 'sanitize' ) );

            $this->options_privacy();
            register_setting( $this->option_group_privacy, $this->option_group_privacy, array( $this, 'sanitize' ) );

            $this->options_debug();
            register_setting( $this->option_group_debug, $this->option_group_debug, array( $this, 'sanitize' ) );

            $this->options_branding();
            register_setting( $this->option_group_branding, $this->option_group_branding, array( $this, 'sanitize' ) );

            $this->options_support();
            register_setting( $this->option_group_support, $this->option_group_support, array( $this, 'sanitize' ) );

            $this->options_email();
            register_setting( $this->option_group_email, $this->option_group_email, array( $this, 'sanitize' ) );
        }

        /**
         * Branding Settings Section and Fields
         */
        public function options_branding(): void {
            $section = 'branding_settings';
            add_settings_section( $section, esc_html__( 'Branding Settings', 'simply-buy' ), '', $this->option_page_branding );

            $id = 'show_branding';
            add_settings_field( $id, esc_html__( 'Backlink / Branding', 'simply-buy' ), array(
                    $this,
                    'branding_consent_cb'
            ), $this->option_page_branding, $section, array(
                    'option_group' => $this->option_group_branding,
                    'id'           => $id,
                    'value'        => $this->options_branding[ $id ] ?? '',
            ) );
        }

        /**
         * Branding consent UI — preview box + Pro features + toggle buttons.
         */
        public function branding_consent_cb( array $args ): void {
            $option_group     = $args['option_group'] ?? '';
            $id               = $args['id'] ?? '';
            $branding_enabled = ! empty( $args['value'] );
            $pro_pricing_url  = $this->sbuy_get_pro_pricing_url();

            // Keep the outer options.php form saving the current value when neither button is pressed.
            printf( '<input type="hidden" name="%1$s[%2$s]" value="%3$s" />',
                esc_attr( $option_group ),
                esc_attr( $id ),
                esc_attr( $branding_enabled ? '1' : '0' )
            );
            wp_nonce_field( 'sbuy_branding_choice', 'sbuy_branding_nonce' );

            // Preview box showing where the link would appear
            echo '<div style="border: 1px solid #ddd; border-radius: 8px; padding: 20px; max-width: 500px; margin-bottom: 24px; background: #fafafa;">';
            echo '<p style="color:#999; font-size:13px;">' . esc_html__( 'Search for object...', 'simply-buy' ) . '</p>';
            echo '<div style="border:1px solid #eee; border-radius:4px; padding:10px; background:#fff;">';
            echo '<p style="color:#aaa; font-size:12px;">' . esc_html__( 'E.g. file folder, shoe rack, floor lamp, etc.', 'simply-buy' ) . '</p>';
            echo '<p style="text-align:right; margin:0;"><a style="font-size:11px; color:#666;">' . esc_html__( 'SimplyBuy – tools for junk removal', 'simply-buy' ) . '</a></p>';
            echo '</div>';
            echo '<p style="font-size:11px; color:#999; margin-top:8px;">';
            echo esc_html__( 'The link appears here — small and discreet, only inside the widget.', 'simply-buy' );
            echo '</p>';
            echo '</div>';

            // Value proposition box
            echo '<div style="background:#f0f7ff; border-left:4px solid #2271b1; padding:16px; max-width:500px; margin-bottom:24px; border-radius:4px;">';
            echo '<h3 style="margin-top:0;">🎁 ' . esc_html__( 'All Pro features — unlock for free', 'simply-buy' ) . '</h3>';
            echo '<ul style="margin:0 0 8px 16px;">';
            echo '<li>' . esc_html__( 'Minimum Pickup Price', 'simply-buy' ) . '</li>';
            echo '<li>' . esc_html__( 'Direct Link URL', 'simply-buy' ) . '</li>';
            echo '<li>' . esc_html__( 'Bulk block days', 'simply-buy' ) . '</li>';
            echo '<li>' . esc_html__( 'Bulk price adjustment', 'simply-buy' ) . '</li>';
            echo '<li>' . esc_html__( 'Automated customer review request', 'simply-buy' ) . '</li>';
            echo '</ul>';
            echo '<p style="margin:0; font-size:13px; color:#555;">';
            echo esc_html__( 'In return, a small discreet link appears in the widget. No popup. No banner. Just one line.', 'simply-buy' );
            echo '</p>';
            echo '</div>';

            // Buttons — submit through the outer options.php form via named submit buttons
            if ( $branding_enabled ) {
                echo '<p><strong>' . esc_html__( 'Status: Active — Pro features unlocked ✓', 'simply-buy' ) . '</strong></p>';
                if ( $this->sbuy_can_toggle_branding() ) {
                    echo '<button type="submit" name="sbuy_branding_disable" class="button button-secondary">' . esc_html__( 'Disable branding', 'simply-buy' ) . '</button>';
                } else {
                    $until = wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $this->sbuy_get_branding_toggle_blocked_until() );
                    echo '<button type="button" class="button button-secondary" disabled style="opacity:0.5; cursor:not-allowed;">' . esc_html__( 'Disable branding', 'simply-buy' ) . '</button>';
                    echo '<p style="color:#888; font-size:13px; margin-top:6px;">' . esc_html( sprintf( /* translators: %s: date/time */ __( 'Available from %s', 'simply-buy' ), $until ) ) . '</p>';
                }
            } else {
                echo '<button type="submit" name="sbuy_branding_enable" class="button button-primary button-large" style="margin-right:12px;">';
                echo '✓ ' . esc_html__( 'Yes, I\'m in — unlock Pro features', 'simply-buy' );
                echo '</button>';
                echo '<button type="submit" name="sbuy_branding_decline" class="button button-secondary" style="color:#999;">';
                echo esc_html__( 'No thanks', 'simply-buy' );
                echo '</button>';
            }

            // Pro upsell box below
            echo '<div style="margin-top:24px; padding:14px; border:1px solid #f0b849; border-radius:8px; background:linear-gradient(135deg, #fff9ef 0%, #fff3de 100%); max-width:500px;">';
            echo '<p style="margin:0 0 10px; font-weight:600;">' . esc_html__( 'Prefer a clean Pro setup with zero branding?', 'simply-buy' ) . '</p>';
            echo '<div style="display: flex; align-items: center;">';
            echo '<a href="' . esc_url( $pro_pricing_url ) . '" class="button" target="_blank" rel="noopener noreferrer" style="background:#ff7a00; border-color:#ff7a00; color:#fff; font-weight:600;">' . esc_html__( 'See Pro Pricing', 'simply-buy' ) . '</a>';
            echo '<span style="margin-left:8px; color:#8a5a00;">' . esc_html__( 'Instant access to all premium features.', 'simply-buy' ) . '</span>';
            echo '</div>';
            echo '</div>';
        }

        /**
         * Page Debug, Section Settings
         */
        public function options_email(): void {
            $section = 'email_settings';

            add_settings_section( $section, esc_html__( 'Email Settings', 'simply-buy' ), '', $this->option_page_email );

            // Email From
            $id = 'email_from';
            add_settings_field( $id, esc_html__( 'Email From', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), $this->option_page_email, $section, array(
                    'option_group' => $this->option_group_email,
                    'id'           => $id,
                    'value'        => $this->options_email[ $id ] ?? '',
                    'placeholder'  => esc_html__( 'SimplyBuy', 'simply-buy' ),
                    'description'  => esc_html__( 'Enter the name that will be visible to the client in the Email From field.', 'simply-buy' ),
                    'width'        => '400px',
            ) );


            // Email Subject
            $id = 'email_subject';
            add_settings_field( $id, esc_html__( 'Email Subject', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), $this->option_page_email, $section, array(
                    'option_group' => $this->option_group_email,
                    'id'           => $id,
                    'value'        => $this->options_email[ $id ] ?? '',
                    'placeholder'  => esc_html__( 'New booking', 'simply-buy' ),
                    'description'  => esc_html__( 'Enter the subject of the email that the client will see in Email', 'simply-buy' ),
                    'width'        => '400px',
            ) );

            // Notification Email
            $id = 'notification_email';
            add_settings_field( $id, esc_html__( 'Notification Email', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), $this->option_page_email, $section, array(
                    'option_group' => $this->option_group_email,
                    'id'           => $id,
                    'value'        => $this->options_email[ $id ] ?? '',
                    'placeholder'  => get_option( 'admin_email' ),
                    'description'  => esc_html__( 'Booking notifications are sent to this email address. Leave empty to use the WordPress admin email.', 'simply-buy' ),
                    'width'        => '400px',
            ) );

            // Reply-To Email
            $id = 'reply_to_email';
            add_settings_field( $id, esc_html__( 'Reply-To Email', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), $this->option_page_email, $section, array(
                    'option_group' => $this->option_group_email,
                    'id'           => $id,
                    'value'        => $this->options_email[ $id ] ?? '',
                    'placeholder'  => 'info@yourcompany.com',
                    'description'  => esc_html__( 'Customers can reply to this address. Leave empty for no-reply.', 'simply-buy' ),
                    'width'        => '400px',
            ) );
        }

        /**
         * Page Debug, Section Settings
         */
        public function options_debug(): void {
            $section = 'debug_settings';

            add_settings_section( $section, esc_html__( 'Debug Settings', 'simply-buy' ), '', $this->option_page_debug );

            $id = 'debug_log_output';
            add_settings_field( $id, esc_html__( 'Event Log (last 7 days)', 'simply-buy' ), array(
                    $this,
                    'debug_log_output_cb'
            ), $this->option_page_debug, $section );
        }

        /**
         * Page Support, Section Settings
         */
        public function options_support(): void {
            $section = 'support_settings';

            add_settings_section( $section, esc_html__( 'Support & Help', 'simply-buy' ), '', $this->option_page_support );

            $id = 'support_info';
            add_settings_field( $id, esc_html__( 'Contact Support', 'simply-buy' ), array(
                    $this,
                    'support_info_cb'
            ), $this->option_page_support, $section );
        }

        public function support_info_cb(): void {
            list( $lang ) = explode( '_', get_locale() );

            if ( $lang === 'de' ) {
                $support_link = 'https://profitclicker.com/hilfe/';
            } else {
                $support_link = 'https://profitclicker.com/help/';
            }

            echo '<p>' . esc_html__( 'Need help with SimplyBuy?', 'simply-buy' ) . '</p>';
            echo '<p><a href="' . esc_url( $support_link ) . '" target="_blank" class="button button-primary">' . esc_html__( 'Support Page', 'simply-buy' ) . '</a> ';
        }

        /**
         * Outputs the event log from sbuy_logs table for last 7 days.
         */
        public function debug_log_output_cb(): void {
            global $wpdb;
            $table_name = esc_sql( $wpdb->prefix . 'sbuy_logs' );
            $date_limit = gmdate( 'Y-m-d H:i:s', strtotime( '-7 days' ) );

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $logs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE event_time >= %s ORDER BY event_time DESC LIMIT 100", $date_limit ) );

            if ( empty( $logs ) ) {
                echo '<p>' . esc_html__( 'No log data available for the last 7 days.', 'simply-buy' ) . '</p>';

                return;
            }

            $json_logs = json_encode( $logs, true );

            ob_start();
            ?>
            <input type="button" id="debug-copy" class="button button-primary" onclick="copyText()" style="margin-bottom: 10px"
                   value="<?php echo esc_html__( 'Copy logs', 'simply-buy' ); ?>">

            <textarea id="debug-log-output" style="display:none"><?php echo esc_textarea( $json_logs ); ?></textarea>

            <table class="widefat striped">
                <thead>
                <tr>
                    <td><strong><?php esc_html_e( 'Date/Time', 'simply-buy' ); ?></strong></td>
                    <td><strong><?php esc_html_e( 'Type', 'simply-buy' ); ?></strong></td>
                    <td><strong><?php esc_html_e( 'Message', 'simply-buy' ); ?></strong></td>
                </tr>
                </thead>
                <tbody>
                <?php foreach ( $logs as $log ) : ?>
                    <tr>
                        <td><?php echo esc_html( $log->event_time ); ?></td>
                        <td><?php echo esc_html( ucfirst( $log->event_type ) ); ?></td>
                        <td><?php echo esc_html( $log->message ); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <?php
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo ob_get_clean();
        }

        /**
         * Page Checkout, Section Settings
         */
        public function options_checkout(): void {
            $section = 'checkout_settings';

            add_settings_section( $section, esc_html__( 'Checkout Settings', 'simply-buy' ), '', $this->option_page_checkout );

            // Enable/Disable custom checkbox feature
            $id = 'enable_custom_checkbox';
            add_settings_field( $id, esc_html__( 'Enable custom checkbox', 'simply-buy' ), array(
                    $this,
                    'option_input_checkbox_cb'
            ), $this->option_page_checkout, $section, array(
                    'option_group' => $this->option_group_checkout,
                    'id'           => $id,
                    'value'        => $this->options_checkout[ $id ] ?? '',
                    'description'  => esc_html__( 'Turn on to show the custom checkbox and its tooltip on checkout.', 'simply-buy' ),
            ) );

            // Checkbox label field
            $id = 'custom_checkbox_label_text';
            add_settings_field( $id, esc_html__( 'Custom checkbox label', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), $this->option_page_checkout, $section, array(
                    'option_group' => $this->option_group_checkout,
                    'id'           => $id,
                    'value'        => $this->options_checkout[ $id ] ?? '',
                    'placeholder'  => esc_html__( 'Enter checkbox label', 'simply-buy' ),
                    'description'  => esc_html__( 'This is the label shown next to the checkbox (e.g. "Planting a tree")', 'simply-buy' ),
                    'width'        => '400px',
            ) );

            // Tooltip HTML field
            $id = 'custom_checkbox_tooltip_html';
            add_settings_field( $id, esc_html__( 'Custom Tooltip HTML', 'simply-buy' ), array(
                    $this,
                    'option_input_wp_editor_cb'
            ), $this->option_page_checkout, $section, array(
                    'option_group' => $this->option_group_checkout,
                    'id'           => $id,
                    'value'        => $this->options_checkout[ $id ] ?? '',
                    'description'  => esc_html__( 'HTML content below the checkbox (can include icons, links, etc.)', 'simply-buy' ),
            ) );

            // Next Day Booking Message HTML field
            $id = 'next_day_booking_message_html';
            add_settings_field( $id, esc_html__( 'Tooltip after Date', 'simply-buy' ), array(
                    $this,
                    'option_input_wp_editor_cb'
            ), $this->option_page_checkout, $section, array(
                    'option_group' => $this->option_group_checkout,
                    'id'           => $id,
                    'value'        => $this->options_checkout[ $id ] ?? '',
                    'description'  => esc_html__( 'HTML message shown below the date/time selector.', 'simply-buy' ),
            ) );
        }

        /**
         * Page Privacy, Section Settings
         */
        public function options_privacy(): void {
            $section = 'privacy_settings';

            add_settings_section( $section, esc_html__( 'Terms and Conditions Settings', 'simply-buy' ), '', $this->option_page_privacy );

            // Enable/disable privacy notice
            $id = 'enable_privacy_notice';
            add_settings_field( $id, esc_html__( 'Enable Notice', 'simply-buy' ), array(
                    $this,
                    'option_input_checkbox_cb'
            ), $this->option_page_privacy, $section, array(
                    'option_group' => $this->option_group_privacy,
                    'id'           => $id,
                    'value'        => $this->options_privacy[ $id ] ?? '',
                    'description'  => esc_html__( 'Show or hide the terms and conditions notice on checkout.', 'simply-buy' ),
            ) );

            // Privacy notice HTML
            $id = 'privacy_notice_html';
            add_settings_field( $id, esc_html__( 'Notice HTML', 'simply-buy' ), array(
                    $this,
                    'option_input_wp_editor_cb'
            ), $this->option_page_privacy, $section, array(
                    'option_group' => $this->option_group_privacy,
                    'id'           => $id,
                    'value'        => $this->options_privacy[ $id ] ?? '',
                    'description'  => esc_html__( 'HTML content of the terms and conditions notice displayed at checkout.', 'simply-buy' ),
            ) );

            // Privacy checkbox HTML
            $id = 'privacy_checkbox_html';
            add_settings_field( $id, esc_html__( 'Checkbox HTML', 'simply-buy' ), array(
                    $this,
                    'option_input_wp_editor_cb'
            ), $this->option_page_privacy, $section, array(
                    'option_group' => $this->option_group_privacy,
                    'id'           => $id,
                    'value'        => $this->options_privacy[ $id ] ?? '',
                    'description'  => esc_html__( 'Checkbox HTML content of the terms and conditions displayed at checkout.', 'simply-buy' ),
            ) );
        }

        /**
         * Page Finance, Section Settings
         */
        public function options_finance(): void {
            $section = 'finance_settings';

            add_settings_section( $section, // ID
                    esc_html__( 'Finance Settings', 'simply-buy' ), '', // Callback
                    $this->option_page_finance // Page
            );

            // Currency selection
            $id         = 'currency_code';
            $currencies = array(
                    'EUR' => 'EUR (€)',
                    'USD' => 'USD ($)',
                    'GBP' => 'GBP (£)',
                    'AUD' => 'AUD ($)',
                    'CAD' => 'CAD ($)',
                    'CHF' => 'CHF (CHF)',
                    'CZK' => 'CZK (Kč)',
                    'PLN' => 'PLN (zł)',
                    'HUF' => 'HUF (Ft)',
                    'UAH' => 'UAH (₴)',
                    'JPY' => 'JPY (¥)',
                    'CNY' => 'CNY (¥)',
                    'SEK' => 'SEK (kr)',
                    'NOK' => 'NOK (kr)',
                    'DKK' => 'DKK (kr)',
                    'RON' => 'RON (lei)',
                    'RUB' => 'RUB (₽)'
            );
            add_settings_field( $id, esc_html__( 'Currency', 'simply-buy' ), array(
                    $this,
                    'option_select_cb'
            ), $this->option_page_finance, $section, array(
                    'option_group' => $this->option_group_finance,
                    'id'           => $id,
                    'value'        => $this->options_finance[ $id ] ?? 'EUR',
                    'choices'      => $currencies,
                    'placeholder'  => esc_html__( 'Select currency', 'simply-buy' ),
                    'description'  => esc_html__( 'Choose the currency to be used across finance settings.', 'simply-buy' ),
                    'width'        => '200px',
            ) );

            // Determine symbol from selected currency code (fallback to EUR)
            $selected_currency_code = $this->options_finance['currency_code'] ?? 'EUR';
            $currency_symbol        = $this->get_currency_symbol( $selected_currency_code );

            $id = 'minimum_pickup';
            if ( sbuy_has_pro_access() ) {
                add_settings_field( $id, esc_html__( 'Minimum pick-up price', 'simply-buy' ), array(
                        $this,
                        'option_input_text_cb'
                ), // general call back for input text
                        $this->option_page_finance, $section, array(
                                'option_group' => $this->option_group_finance,
                                'id'           => $id,
                                'value'        => $this->options_finance[ $id ] ?? '',
                                'suffix'       => SBUY_CORE_CURRENCY_SYMBOL,
                                'description'  => esc_html__( 'Please set the minimum pick-up price including VAT and use only digits. No decimal separator, no currency. You can use this shortcode [simply-buy-fee-show].', 'simply-buy' ),
                                'placeholder'  => '',
                                'width'        => '100px',
                        ) );
            } else {
                add_settings_field( $id, esc_html__( 'Minimum pick-up price', 'simply-buy' ), array(
                        $this,
                        'minimum_pickup_locked_cb'
                ), $this->option_page_finance, $section, array() );
            }

            $id = 'surcharge_floor';
            add_settings_field( $id, esc_html__( 'Surcharge no elevator and from 4th floor', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), // general call back for input text
                    $this->option_page_finance, $section, array(
                            'option_group' => $this->option_group_finance,
                            'id'           => $id,
                            'value'        => $this->options_finance[ $id ] ?? '',
                            'suffix'       => '%',
                            'description'  => esc_html__( 'Please enter the surcharge in % without decimal places. For no surcharge, leave the field blank.', 'simply-buy' ),
                            'placeholder'  => '',
                            'width'        => '50px',
                    ) );

            $id = 'surcharge_15_50_meter';
            add_settings_field( $id, esc_html__( 'Surcharge 15 to 50 meter', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), // general call back for input text
                    $this->option_page_finance, $section, array(
                            'option_group' => $this->option_group_finance,
                            'id'           => $id,
                            'value'        => $this->options_finance[ $id ] ?? '',
                            'suffix'       => '%',
                            'description'  => esc_html__( 'Please enter the surcharge in % without decimal places. For no surcharge, leave the field blank.', 'simply-buy' ),
                            'placeholder'  => '',
                            'width'        => '50px',
                    ) );

            $id = 'surcharge_50_plus_meter';
            add_settings_field( $id, esc_html__( 'Surcharge 50 meter and more', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), // general call back for input text
                    $this->option_page_finance, $section, array(
                            'option_group' => $this->option_group_finance,
                            'id'           => $id,
                            'value'        => $this->options_finance[ $id ] ?? '',
                            'suffix'       => '%',
                            'description'  => esc_html__( 'Please enter the surcharge in % without decimal places. For no surcharge, leave the field blank.', 'simply-buy' ),
                            'placeholder'  => '',
                            'width'        => '50px',
                    ) );
        }

        /**
         * Map ISO currency code to symbol (basic set)
         */
        private function get_currency_symbol( string $code ): string {
            $map  = array(
                    'EUR' => '€',
                    'USD' => '$',
                    'GBP' => '£',
                    'AUD' => '$',
                    'CAD' => '$',
                    'CHF' => 'CHF',
                    'CZK' => 'Kč',
                    'PLN' => 'zł',
                    'HUF' => 'Ft',
                    'UAH' => '₴',
                    'JPY' => '¥',
                    'CNY' => '¥',
                    'SEK' => 'kr',
                    'NOK' => 'kr',
                    'DKK' => 'kr',
                    'RON' => 'lei',
                    'RUB' => '₽',
            );
            $code = strtoupper( $code );

            return $map[ $code ] ?? '€';
        }


        /**
         * Page Pages, Section Settings
         */
        public function options_pages(): void {
            $section = 'pages_settings';

            add_settings_section( $section, // ID
                    esc_html__( 'Pages Settings', 'simply-buy' ),
                    array( $this, 'pages_settings_notice_cb' ), // Callback
                    $this->option_page_pages // Page
            );

            $id = 'simply_buy_cart_page';
            add_settings_field( $id, esc_html__( 'Cart page', 'simply-buy' ), array(
                    $this,
                    'pages_dropdown_cb'
            ), $this->option_page_pages, $section, array(
                    'option_group' => $this->option_group_pages,
                    'id'           => $id,
                    'value'        => $this->options_pages[ $id ] ?? '',
                    'placeholder'  => esc_html__( 'Select a page', 'simply-buy' ),
                    'description'  => wp_kses_post( 'Please select the page where the shortcodes <code>[simply-buy-cart]</code> and <code>[simply-buy-shopping-cart]</code> is included.', 'simply-buy' ),
            ) );

            $id = 'simply_buy_checkout_page';
            add_settings_field( $id, esc_html__( 'Checkout page', 'simply-buy' ), array(
                    $this,
                    'pages_dropdown_cb'
            ), $this->option_page_pages, $section, array(
                    'option_group' => $this->option_group_pages,
                    'id'           => $id,
                    'value'        => $this->options_pages[ $id ] ?? '',
                    'placeholder'  => esc_html__( 'Select a page', 'simply-buy' ),
                    'description'  => wp_kses_post( 'Please select the page where the shortcode <code>[simply-buy-checkout]</code> is included.', 'simply-buy' ),
            ) );

            $id = 'simply_buy_thankyou_page';
            add_settings_field( $id, esc_html__( 'Thank you page', 'simply-buy' ), array(
                    $this,
                    'pages_dropdown_cb'
            ), $this->option_page_pages, $section, array(
                    'option_group' => $this->option_group_pages,
                    'id'           => $id,
                    'value'        => $this->options_pages[ $id ] ?? '',
                    'placeholder'  => esc_html__( 'Select a page', 'simply-buy' ),
                    'description'  => wp_kses_post( 'Please select the page that will be displayed after completing the booking process.', 'simply-buy' ),
            ) );
        }

        /**
         * Info notice above the Pages dropdowns
         */
        /**
         * Field callback for the minimum pick-up price when Pro access is missing.
         */
        public function minimum_pickup_locked_cb(): void {
            echo '<input type="text" disabled style="opacity:0.5; width:100px;" placeholder="—">';
            echo '<p class="description">⭐ ' . esc_html__( 'Pro feature — ', 'simply-buy' );
            echo '<a href="' . esc_url( __( 'https://profitclicker.com/pricing/', 'simply-buy' ) ) . '" target="_blank" rel="noopener noreferrer">';
            echo esc_html__( 'Upgrade to Pro', 'simply-buy' ) . '</a></p>';
        }

        public function pages_settings_notice_cb(): void {
            echo '<div class="notice notice-info inline"><p>' .
                esc_html__( 'SimplyBuy has automatically created 3 pages for you: Cart, Checkout and Thank You. They are already selected below. You can find and edit them under Pages in your WordPress menu.', 'simply-buy' ) .
                '</p></div>';
            echo '<p class="description" style="margin-top:8px;">💡 ' .
                esc_html__( 'Tip: You can also add the shortcode [simply-buy-shopping-cart] to your sidebar — for a better layout. This setting is preserved during plugin updates.', 'simply-buy' ) .
                '</p>';
        }

        /**
         * Page Calendar, Section Settings
         */
        public function options_google(): void {
            $section = 'google_settings';

            add_settings_section( $section, // ID
                    esc_html__( 'Google Calendar Settings', 'simply-buy' ),
                    array( $this, 'google_settings_notice_cb' ), // Callback
                    $this->option_page_google // Page
            );

            $id = 'google_service_account_json';
            add_settings_field( $id, esc_html__( 'Google service account key JSON', 'simply-buy' ), array(
                    $this,
                    'option_input_textarea_cb'
            ), // general call back for textarea.
                    $this->option_page_google, $section, array(
                            'option_group' => $this->option_group_google,
                            'id'           => $id,
                            'value'        => $this->options_google[ $id ] ?? '',
                            'description'  => esc_html__( 'Get the JSON file from Google cloud->APIs & Services->Credentials->Service Accounts->keys.', 'simply-buy' ),
                            'rows'         => '8',
                            'cols'         => '80',
                    ) );

            $id = 'calendar_id';
            add_settings_field( $id, esc_html__( 'Google calendar ID', 'simply-buy' ), array(
                    $this,
                    'option_input_text_cb'
            ), // general call back for input text.
                    $this->option_page_google, $section, array(
                            'option_group' => $this->option_group_google,
                            'id'           => $id,
                            'value'        => $this->options_google[ $id ] ?? '',
                            'description'  => esc_html__( 'Calendar ID in Settings and sharing > Integrated calendar > Calendar ID', 'simply-buy' ),
                            'placeholder'  => '',
                            'width'        => '400px',
                    ) );

            add_settings_field(
                'sbuy_test_calendar_connection',
                esc_html__( 'Connection test', 'simply-buy' ),
                array( $this, 'test_calendar_connection_cb' ),
                $this->option_page_google,
                $section
            );
        }

        /**
         * Render the "Test connection" button + inline JS that talks to the
         * sbuy_test_calendar_connection AJAX handler and prints the result
         * next to the button.
         */
        public function test_calendar_connection_cb(): void {
            $nonce = wp_create_nonce( 'simplybuy-nonce' );
            ?>
            <button type="button" id="sbuy-test-calendar-btn" class="button">
                <?php echo esc_html__( 'Test connection', 'simply-buy' ); ?>
            </button>
            <span id="sbuy-test-calendar-result" style="margin-left:12px;font-weight:600;"></span>
            <p class="description" style="margin-top:8px;">
                <?php echo esc_html__( 'Performs a read-only connection check — no calendar events are created.', 'simply-buy' ); ?>
            </p>
            <script>
                (function () {
                    var btn = document.getElementById('sbuy-test-calendar-btn');
                    var out = document.getElementById('sbuy-test-calendar-result');
                    if (!btn || !out) { return; }
                    var i18n = {
                        saving:     <?php echo wp_json_encode( esc_html__( 'Saving…', 'simply-buy' ) ); ?>,
                        checking:   <?php echo wp_json_encode( esc_html__( 'Checking…', 'simply-buy' ) ); ?>,
                        saveFailed: <?php echo wp_json_encode( esc_html__( 'Save failed — check the form values.', 'simply-buy' ) ); ?>,
                        errorPrefix: <?php echo wp_json_encode( esc_html__( 'Error: ', 'simply-buy' ) ); ?>
                    };
                    btn.addEventListener('click', async function () {
                        btn.disabled = true;

                        // 1. Auto-save the form first so the test always runs
                        //    against the values the admin is currently looking
                        //    at, not the last ones they happened to click
                        //    "Save changes" for. The form posts to options.php
                        //    (WP Settings API) — we replay the exact same POST
                        //    in the background.
                        out.textContent = i18n.saving;
                        out.style.color = '#666';
                        try {
                            var form = btn.closest('form');
                            if (form) {
                                // NB: form.action is shadowed by the hidden
                                // <input name="action"> that the WP Settings
                                // API emits — getAttribute bypasses the DOM
                                // quirk and returns the URL string.
                                var target = form.getAttribute('action') || window.location.href;
                                var saveResp = await fetch(target, {
                                    method:      'POST',
                                    credentials: 'same-origin',
                                    body:        new FormData(form)
                                });
                                if (!saveResp.ok) throw new Error('HTTP ' + saveResp.status);
                            }
                        } catch (e) {
                            out.textContent = i18n.saveFailed + ' (' + e.message + ')';
                            out.style.color = '#d63638';
                            btn.disabled = false;
                            return;
                        }

                        // 2. Run the connection test
                        out.textContent = i18n.checking;
                        out.style.color = '#666';
                        try {
                            var body = new URLSearchParams({
                                action: 'sbuy_test_calendar_connection',
                                nonce:  <?php echo wp_json_encode( $nonce ); ?>
                            });
                            var r   = await fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: body });
                            var res = await r.json();
                            out.textContent = (res && res.data && res.data.message) || 'Unknown response';
                            out.style.color = (res && res.success) ? '#1d7302' : '#d63638';
                        } catch (e) {
                            out.textContent = i18n.errorPrefix + e.message;
                            out.style.color = '#d63638';
                        } finally {
                            btn.disabled = false;
                        }
                    });
                })();
            </script>
            <?php
        }

        /**
         * Help link above the Google Calendar fields
         */
        public function google_settings_notice_cb(): void {
            echo '<p>' .
                sprintf(
                    wp_kses(
                        /* translators: %s: documentation URL */
                        __( 'Need help setting up Google Calendar? <a href="%s" target="_blank">View Documentation</a>', 'simply-buy' ),
                        array( 'a' => array( 'href' => array(), 'target' => array() ) )
                    ),
                    esc_url( __( 'https://profitclicker.com/documentation/', 'simply-buy' ) )
                ) .
                '</p>';
        }

        /**
         * Page Time, Section Settings
         */
        public function options_time(): void {

            $section = 'time_settings';

            add_settings_section( $section, // ID
                    esc_html__( 'Time Settings', 'simply-buy' ), '', // Callback
                    $this->option_page_time // Page
            );

            $id = 'slot_time';
            add_settings_field( $id, esc_html__( 'Slot Time', 'simply-buy' ), array(
                    $this,
                    'weekday_time_table_cb'
            ), $this->option_page_time, $section, array(
                    'option_group' => $this->option_group_time,
                    'id'           => $id,
            ) );

            $id = 'min_booking_days';
            add_settings_field( $id, esc_html__( 'Earliest Booking Offset (Days)', 'simply-buy' ), array(
                    $this,
                    'option_select_cb'
            ), $this->option_page_time, $section, array(
                    'option_group' => $this->option_group_time,
                    'id'           => $id,
                    'value'        => $this->options_time[ $id ] ?? '1',
                    'choices'      => array_combine( range( 1, 14 ), array_map( fn( $d ) => sprintf( /* translators: %d: number of days */ _n( '%d day', '%d days', $d, 'simply-buy' ), $d ), range( 1, 14 ) ) ),
                    'description'  => esc_html__( 'Defines how many days in advance the earliest booking can be made (e.g. 1 = tomorrow, 2 = in two days, etc.).', 'simply-buy' ),
                    'width'        => '120px',
            ) );
        }

        /**
         * Output of table of the weekdays
         *
         * @param $args array
         *
         * @return void
         */
        public function weekday_time_table_cb( array $args ): void {

            ?>
            <table class="form-table sb-form-table">
                <thead>
                <tr>
                    <th scope="col"><?php esc_html_e( 'Weekday', 'simply-buy' ); ?></th>
                    <th scope="col" class="center"><?php esc_html_e( 'Morning', 'simply-buy' ); ?></th>
                    <th scope="col" class="center"><?php esc_html_e( 'Afternoon', 'simply-buy' ); ?></th>
                </tr>
                </thead>
                <tbody>
                <?php
                // create a list of weekdays, starting with the global start of the week
                for ( $day_index = get_option( 'start_of_week' ); $day_index <= 6; $day_index ++ ) {
                    self::weekday_row_for_time_settings( $day_index, $args );
                }

                // If the week does not start with day 0, which is Sunday, we have to add the days below the list
                if ( 0 < get_option( 'start_of_week' ) ) {
                    for ( $day_index = 0; $day_index < get_option( 'start_of_week' ); $day_index ++ ) {
                        self::weekday_row_for_time_settings( $day_index, $args );
                    }
                }
                ?>
                </tbody>
            </table>
            <?php
        }

        /**
         * Output of the row for a weekday
         *
         * @param $day_index int
         * @param $args array
         *
         * @return void
         */
        private function weekday_row_for_time_settings( int $day_index, array $args ): void {

            /**
             * @global WP_Locale $wp_locale WordPress date and time locale object.
             */ global $wp_locale;
            ?>

            <tr>
                <th scope="row" class="titledesc"><?php echo esc_html( $wp_locale->get_weekday( $day_index ) ); ?></th>
                <td>
                    <?php
                    self::option_input_type_time( $day_index, $args, 'morning_from' );
                    echo '&nbsp;' . esc_html_x( 'to', 'time range separator: from → to', 'simply-buy' ) . '&nbsp;';
                    self::option_input_type_time( $day_index, $args, 'morning_to' );
                    ?>
                </td>
                <td>
                    <?php
                    self::option_input_type_time( $day_index, $args, 'afternoon_from' );
                    echo '&nbsp;' . esc_html_x( 'to', 'time range separator: from → to', 'simply-buy' ) . '&nbsp;';
                    self::option_input_type_time( $day_index, $args, 'afternoon_to' );
                    ?>
                </td>
            </tr>

            <?php
        }

        /**
         * General Select Field
         *
         * @param array $args
         */
        public function option_select_cb( array $args ): void {
            $option_group = $args['option_group'] ?? '';
            $id           = $args['id'] ?? '';
            $value        = $args['value'] ?? '';
            $choices      = $args['choices'] ?? array();
            $placeholder  = $args['placeholder'] ?? '';
            $description  = $args['description'] ?? '';
            $width        = $args['width'] ?? '';

            printf( '<select id="%1$s" name="%2$s[%1$s]" style="width:%3$s">', esc_attr( $id ), esc_attr( $option_group ), esc_attr( $width ) );
            if ( ! empty( $placeholder ) ) {
                printf( '<option value="">%s</option>', esc_html( $placeholder ) );
            }
            foreach ( $choices as $k => $label ) {
                $selected = selected( (string) $value, (string) $k, false );
                printf( '<option value="%1$s" %3$s>%2$s</option>', esc_attr( $k ), esc_html( $label ), esc_html( $selected ) );
            }
            echo '</select>';

            if ( ! empty( $description ) ) {
                echo '<p class="description">' . esc_html( $description ) . '</p>';
            }
        }

        /**
         * General Input Field Text
         *
         * @param array $args
         */
        public function option_input_text_cb( array $args ): void {

            $option_group = ( isset( $args['option_group'] ) ) ? $args['option_group'] : '';
            $id           = ( isset( $args['id'] ) ) ? $args['id'] : '';
            $value        = ( isset( $args['value'] ) ) ? $args['value'] : '';
            $suffix       = ( isset( $args['suffix'] ) ) ? ' ' . $args['suffix'] : '';
            $placeholder  = ( isset( $args['placeholder'] ) ) ? $args['placeholder'] : '';
            $description  = ( isset( $args['description'] ) ) ? $args['description'] : '';
            $password     = ( isset( $args['password'] ) ) ? $args['password'] : false;
            $width        = ( isset( $args['width'] ) ) ? $args['width'] : '';

            $type = 'text';
            if ( $password ) {
                $type = 'password';
            }

            printf( '<input type="%6$s" id="%1$s" name="%3$s[%1$s]" value="%2$s" placeholder="%4$s" style="width: %5$s"/>%7$s', esc_attr( $id ), esc_attr( $value ), esc_attr( $option_group ), esc_attr( $placeholder ), esc_attr( $width ), esc_attr( $type ), esc_attr( $suffix ) );

            if ( ! empty( $description ) ) {
                echo '<p class="description">' . esc_html( $description ) . '</p>';
            }
        }

        /**
         * Input Field Time for Slot Time
         *
         * @param int $day_index
         * @param array $args
         * @param string $slot
         */
        private function option_input_type_time( int $day_index, array $args, string $slot ): void {

            $option_group = ( isset( $args['option_group'] ) ) ? $args['option_group'] : '';
            $id           = ( isset( $args['id'] ) ) ? $args['id'] : '';
            $value        = $this->options_time[ $id ][ $day_index ][ $slot ] ?? null;

            if ( is_null( $value ) ) {
                // set default slot time
                switch ( $slot ) {
                    case 'morning_from':
                        $value = '08:00';
                        break;
                    case 'morning_to' || 'afternoon_from':
                        $value = '12:00';
                        break;
                    case 'afternoon_to':
                        $value = '16:00';
                        break;
                }
            }

            printf( '<input type="time" class="forminp forminp-number" id="%1$s" name="%3$s[%1$s][%4$s][%5$s]" value="%2$s" />', esc_attr( $id ), esc_attr( $value ), esc_attr( $option_group ), esc_attr( $day_index ), esc_attr( $slot ) );
        }

        /**
         * General Field Textarea
         *
         * @param array $args
         */
        public function option_input_textarea_cb( array $args ): void {

            $option_group = ( isset( $args['option_group'] ) ) ? $args['option_group'] : '';
            $id           = ( isset( $args['id'] ) ) ? $args['id'] : '';
            $value        = ( isset( $args['value'] ) ) ? $args['value'] : '';
            $rows         = $args['rows'] ?? '';
            $cols         = $args['cols'] ?? '';
            $suffix       = ( isset( $args['suffix'] ) ) ? ' ' . $args['suffix'] : '';
            $description  = ( isset( $args['description'] ) ) ? $args['description'] : '';

            printf( '<textarea id="%1$s" name="%3$s[%1$s]" rows="%4$s" cols="%5$s">%2$s</textarea>%6$s', esc_attr( $id ), esc_attr( $value ), esc_attr( $option_group ), esc_attr( $rows ), esc_attr( $cols ), esc_attr( $suffix ) );

            if ( ! empty( $description ) ) {
                echo '<p class="description">' . esc_html( $description ) . '</p>';
            }
        }

        /**
         * WYSIWYG Editor Field
         *
         * @param array $args
         */
        public function option_input_wp_editor_cb( array $args ): void {

            $option_group = $args['option_group'] ?? '';
            $id           = $args['id'] ?? '';
            $value        = $args['value'] ?? '';
            $description  = $args['description'] ?? '';

            wp_editor( $value, $id, array(
                    'textarea_name' => $option_group . '[' . $id . ']',
                    'media_buttons' => false,
                    'textarea_rows' => 8,
                    'teeny'         => true,
            ) );

            if ( ! empty( $description ) ) {
                echo '<p class="description">' . esc_html( $description ) . '</p>';
            }
        }

        /**
         * General Input Field Checkbox
         *
         * @param array $args
         */
        public function option_input_checkbox_cb( array $args ): void {

            $option_group = ( isset( $args['option_group'] ) ) ? $args['option_group'] : '';
            $id           = ( isset( $args['id'] ) ) ? $args['id'] : '';
            $checked      = ( ! empty( $args['value'] ) ) ? 'checked' : '';
            $description  = ( ! empty( $args['description'] ) ) ? $args['description'] : '';

            // Always send a value even when unchecked
            printf( '<input type="hidden" name="%2$s[%1$s]" value="0" />', esc_attr( $id ), esc_attr( $option_group ) );

            // Actual checkbox control
            printf( '<input type="checkbox" id="%1$s" name="%3$s[%1$s]" value="1" %2$s />', esc_attr( $id ), esc_attr( $checked ), esc_attr( $option_group ) );

            if ( ! empty( $description ) ) {
                echo '<p class="description">' . esc_html( $description ) . '</p>';
            }
        }

        /**
         * Pages dropdown
         *
         * @since 1.0.0
         */
        public function pages_dropdown_cb( array $args ): void {

            $option_group = ( isset( $args['option_group'] ) ) ? $args['option_group'] : '';
            $id           = ( isset( $args['id'] ) ) ? $args['id'] : '';
            $value        = ( isset( $args['value'] ) ) ? $args['value'] : '';
            $placeholder  = ( isset( $args['placeholder'] ) ) ? $args['placeholder'] : '';
            $description  = ( isset( $args['description'] ) ) ? $args['description'] : '';

            printf( '<select name="%2$s[%1$s]" id="%1$s">', esc_attr( $id ), esc_attr( $option_group ) );

            $allowed_select_tag = sbuy_get_allowed_tag_in_dropdown();
            echo wp_kses( self::get_pages_option_list( $value, $placeholder ), $allowed_select_tag );

            echo '</select>';

            if ( ! empty( $description ) ) {
                echo '<p class="description">' . esc_html( $description ) . '</p>';
            }
        }

        /**
         * Returns an option list with pages
         *
         * @param $pre_selected
         * @param $placeholder
         *
         * @return string
         *
         * @since 1.0.0
         */
        private function get_pages_option_list( $pre_selected, $placeholder ): string {

            // create options list
            $option = '<option value="">' . $placeholder . '</option>';
            $pages  = get_pages();
            if ( ! empty( $pages ) ) {
                foreach ( $pages as $page ) {
                    $selected = ( isset( $pre_selected ) && $pre_selected == $page->ID ) ? 'selected' : '';

                    $option .= '<option value="' . $page->ID . '" ' . $selected . '>';
                    $option .= $page->post_title;
                    $option .= '</option>';
                }
            }

            return $option;
        }

        /**
         * Sanitizes a string from user input
         * Checks for invalid UTF-8, Converts single < characters to entities, Strips all tags, Removes line breaks, tabs, and extra whitespace, Strips octets
         *
         * @param array|null $input
         *
         * @return array
         */
        public function sanitize( ?array $input ): array {

            $new_input = array();

            if ( empty( $input ) ) {
                return $new_input;
            }

            foreach ( $input as $key => $value ) {

                if ( 'notification_email' === $key ) {
                    $value = trim( (string) $value );
                    if ( $value !== '' && ! is_email( $value ) ) {
                        add_settings_error( $this->option_group_email, 'invalid_notification_email', __( 'Please enter a valid notification email address.', 'simply-buy' ) );
                        $new_input[ $key ] = '';
                        continue;
                    }
                    $new_input[ $key ] = sanitize_email( $value );
                    continue;
                }

                if ( 'show_branding' === $key ) {
                    // Named submit buttons from the branding tab override the hidden input value.
                    if ( isset( $_POST['sbuy_branding_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sbuy_branding_nonce'] ) ), 'sbuy_branding_choice' ) ) {
                        if ( isset( $_POST['sbuy_branding_enable'] ) ) {
                            $value = '1';
                        } elseif ( isset( $_POST['sbuy_branding_disable'] ) ) {
                            $value = '0';
                        }
                        // sbuy_branding_decline leaves value untouched (keeps current state)
                    }

                    $enable          = ! empty( $value ) && (string) $value !== '0';
                    $current         = (array) get_option( $this->option_group_branding, array() );
                    $current_enabled = ! empty( $current['show_branding'] );

                    if ( $current_enabled && ! $enable ) {
                        if ( ! $this->sbuy_can_toggle_branding() ) {
                            $new_input[ $key ] = $current_enabled ? 1 : 0;

                            $until = $this->sbuy_get_branding_toggle_blocked_until();
                            $human = wp_date( 'Y-m-d H:i', $until );

                            add_settings_error( $this->option_group_branding, 'sbuy_branding_toggle_rate_limited', sprintf( /* translators: %s: date/time */ __( 'You can disable branding again after %s.', 'simply-buy' ), esc_html( $human ) ), 'error' );

                            continue;
                        }

                        update_option( 'sbuy_branding_toggle_blocked_until', time() + self::SBUY_BRANDING_TOGGLE_COOLDOWN );
                    }

                    $new_input[ $key ] = $enable ? 1 : 0;
                    continue;
                }

                if ( 'ftp-directory' == $key ) {

                    // add leading slash
                    $new_input[ $key ] = '/' . ( ltrim( sanitize_text_field( $value ), '/\\' ) );

                } else {
                    if ( in_array( $key, [
                            'custom_checkbox_tooltip_html',
                            'privacy_notice_html',
                            'privacy_checkbox_html',
                            'next_day_booking_message_html'
                    ], true ) ) {
                        $new_input[ $key ] = wp_kses_post( $value );
                    } else {
                        $new_input[ $key ] = self::sanitize_text_or_array_field( $value );
                    }
                }
            }

            return $new_input;
        }

        /**
         * Recursive sanitation for text or array
         *
         * @param $array_or_string (array|string)
         *
         * @since  1.0.0
         */
        private function sanitize_text_or_array_field( $array_or_string ) {

            if ( is_string( $array_or_string ) ) {

                $array_or_string = sanitize_text_field( $array_or_string );

            } elseif ( is_array( $array_or_string ) ) {
                foreach ( $array_or_string as $key => &$value ) {
                    if ( is_array( $value ) ) {
                        $value = self::sanitize_text_or_array_field( $value );
                    } else {
                        $value = sanitize_text_field( $value );
                    }
                }
            }

            return $array_or_string;
        }
    }

}
