<?php
/**
 * Lizenz- und Trial-Management für PocketBooking Calendar
 *
 * @package SimpleBookingCalendar
 * @since 1.1.3
 */

// Sicherheitsmaßnahme: Direkten Zugriff verhindern
if (!defined('ABSPATH')) {
    exit;
}

// === LIZENZ- UND TRIAL-FUNKTIONEN ===

/**
 * Ruft die Trial-Dauer vom Lizenzserver ab und speichert sie lokal als Option.
 */
function simpbook_fetch_and_cache_trial_duration() {
    $cached_duration = simpbook_get_option('simpbook_server_configured_trial_duration_seconds');
    $last_check_timestamp = simpbook_get_option('simpbook_trial_duration_last_server_check_timestamp', 0);
    $cache_validity_period = 12 * HOUR_IN_SECONDS;

    if (is_numeric($cached_duration) && (time() - $last_check_timestamp < $cache_validity_period)) {
        return (int) $cached_duration;
    }

    $lizenz_server_url = 'https://mobile-refuel.de/wp-content/plugins/mobile-refuel-lizenzserver/lizenzen/check_license.php';
    $token = 'aP39F3kLc9x!mZ82';

    $args = [
        'action' => 'get_plugin_config',
        'token' => $token,
        'plugin_slug' => SIMPBOOK_PLUGIN_SLUG
    ];

    $response = wp_remote_get(add_query_arg($args, $lizenz_server_url), ['timeout' => 15]);

    if (is_wp_error($response)) {
        return $cached_duration !== false && is_numeric($cached_duration) ? (int) $cached_duration : SIMPBOOK_DEFAULT_FALLBACK_TRIAL_DURATION_SECONDS;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if ($data && isset($data['status']) && $data['status'] === 'success' && isset($data['trial_duration_seconds']) && is_numeric($data['trial_duration_seconds'])) {
        $server_duration = (int) $data['trial_duration_seconds'];
        simpbook_update_option('simpbook_server_configured_trial_duration_seconds', $server_duration);
        simpbook_update_option('simpbook_trial_duration_last_server_check_timestamp', time());
        return $server_duration;
    } else {
        return $cached_duration !== false && is_numeric($cached_duration) ? (int) $cached_duration : SIMPBOOK_DEFAULT_FALLBACK_TRIAL_DURATION_SECONDS;
    }
}

/**
 * Gibt die aktuell gültige Trial-Dauer in Sekunden zurück.
 */
function simpbook_get_active_trial_duration_seconds() {
    $server_configured_duration = simpbook_get_option('simpbook_server_configured_trial_duration_seconds');
    if (is_numeric($server_configured_duration)) {
        return (int) $server_configured_duration;
    }
    return SIMPBOOK_DEFAULT_FALLBACK_TRIAL_DURATION_SECONDS;
}

/**
 * Fügt die Lizenzseite zum Admin-Menü hinzu und registriert Einstellungen.
 */
function simpbook_lizenz_funktionen_hinzufuegen() {
    add_submenu_page(
        'simpbook-dashboard',
        __('License', 'simple-appointment-booking'),
        '🔑 ' . __('License', 'simple-appointment-booking'),
        'manage_options',
        'simpbook-reservierungen-lizenz',
        'simpbook_lizenz_seite_html'
    );

    register_setting('simpbook_lizenz_einstellungen_gruppe', 'simpbook_lizenz_key', ['sanitize_callback' => 'sanitize_text_field']);
    register_setting('simpbook_lizenz_einstellungen_gruppe', 'simpbook_lizenz_status', ['sanitize_callback' => 'sanitize_text_field']);

    // Sprachoptionen registrieren
    register_setting('simpbook_einstellungen_gruppe', 'simpbook_language_override', ['sanitize_callback' => 'sanitize_text_field']);
}
add_action('admin_menu', 'simpbook_lizenz_funktionen_hinzufuegen', 15);

/**
 * Zeigt die HTML-Seite für die Lizenzverwaltung an.
 */
function simpbook_lizenz_seite_html() {
    // Textdomain sicherstellen, dass sie korrekt geladen ist
    simpbook_DB_Reservierungen::reload_plugin_textdomain();

    if (isset($_POST['simpbook_lizenz_aktivieren']) && check_admin_referer('simpbook_lizenz_nonce_action', 'simpbook_lizenz_nonce_field')) {
        $lizenz_key = isset($_POST['simpbook_lizenz_key']) ? sanitize_text_field(wp_unslash($_POST['simpbook_lizenz_key'])) : '';

        if (!empty($lizenz_key)) {
            simpbook_update_option('simpbook_lizenz_key', $lizenz_key);
            simpbook_lizenz_validieren($lizenz_key);
            $lizenz_status = simpbook_get_option('simpbook_lizenz_status');

            if ($lizenz_status === 'gueltig') {
                add_settings_error('simpbook_lizenz_nachrichten', 'lizenz_aktiviert', __('License successfully activated! The trial period has been ended if applicable.', 'simple-appointment-booking'), 'success');
            } elseif ($lizenz_status === 'limit_reached') {
                add_settings_error('simpbook_lizenz_nachrichten', 'lizenz_limit', __('License limit reached! Please purchase a new license or contact support.', 'simple-appointment-booking'), 'error');
            } else {
                add_settings_error('simpbook_lizenz_nachrichten', 'lizenz_ungueltig', __('Invalid license key. Please check your input.', 'simple-appointment-booking'), 'error');
            }
        } else {
            add_settings_error('simpbook_lizenz_nachrichten', 'lizenz_leer', __('Please enter a license key.', 'simple-appointment-booking'), 'error');
        }
        settings_errors('simpbook_lizenz_nachrichten');
    }

    $lizenz_key = simpbook_get_option('simpbook_lizenz_key', '');
    $lizenz_status = simpbook_get_option('simpbook_lizenz_status', '');
    ?>
    <div class="wrap simpbook-license-page">
        <h1><?php esc_html_e('PocketBooking License', 'simple-appointment-booking'); ?></h1>
        <?php
        if (!simpbook_ist_lizenz_aktiv_raw() && simpbook_get_option('simpbook_trial_ever_started')) {
            if (simpbook_is_trial_period_active()) {
                $trial_start_time = simpbook_get_option('simpbook_trial_start_time');
                $active_trial_duration = simpbook_get_active_trial_duration_seconds();
                $time_left_seconds = ($trial_start_time + $active_trial_duration) - time();

                if ($time_left_seconds < 0) $time_left_seconds = 0;

                $days = floor($time_left_seconds / (24 * 60 * 60));
                $seconds_remaining_after_days = $time_left_seconds % (24 * 60 * 60);
                $hours = floor($seconds_remaining_after_days / (60 * 60));
                $seconds_remaining_after_hours = $seconds_remaining_after_days % (60 * 60);
                $minutes = floor($seconds_remaining_after_hours / 60);

                $time_display_parts = [];
                // translators: %d: Number of days
                if ($days > 0) $time_display_parts[] = sprintf(_n('%d Tag', '%d Tage', $days, 'simple-appointment-booking'), $days);
                // translators: %d: Number of hours
                if ($hours > 0) $time_display_parts[] = sprintf(_n('%d Stunde', '%d Stunden', $hours, 'simple-appointment-booking'), $hours);
                // translators: %d: Number of minutes
                if ($minutes > 0 || empty($time_display_parts)) $time_display_parts[] = sprintf(_n('%d Minute', '%d Minuten', $minutes, 'simple-appointment-booking'), $minutes);

                $time_display_string = !empty($time_display_parts) ? implode(', ', $time_display_parts) : esc_html__('less than a minute', 'simple-appointment-booking');

                // translators: %s: Time remaining (e.g., "2 Tage, 3 Stunden")
                echo '<div class="notice notice-info inline simpbook-trial-notice"><p>' . sprintf(esc_html__('Your trial period is active and runs for approximately %s more.', 'simple-appointment-booking'), '<strong>' . esc_html($time_display_string) . '</strong>') . '</p></div>';

            } elseif (simpbook_is_trial_expired_and_no_license()) {
                 echo '<div class="notice notice-error inline simpbook-trial-notice"><p>' . esc_html__('Your trial period has expired. Features are limited and settings have been reset.', 'simple-appointment-booking') . '</p></div>';
            }
        }
        ?>
        <p><?php esc_html_e('Enter your license key to gain access to all plugin features.', 'simple-appointment-booking'); ?></p>

        <div class="simpbook-license-form-container">
            <form method="post" action="">
                <?php wp_nonce_field('simpbook_lizenz_nonce_action', 'simpbook_lizenz_nonce_field'); ?>
                <table class="form-table">
                    <tr valign="top">
                        <th scope="row"><label for="simpbook_lizenz_key_input"><?php esc_html_e('License Key', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input type="text" id="simpbook_lizenz_key_input" name="simpbook_lizenz_key" value="<?php echo esc_attr($lizenz_key); ?>" class="regular-text" />
                            <?php if ($lizenz_status === 'gueltig'): ?>
                                <span class="simpbook-license-status status-valid">✓ <?php esc_html_e('Activated', 'simple-appointment-booking'); ?></span>
                            <?php elseif ($lizenz_status === 'ungueltig' || $lizenz_status === 'limit_reached' || $lizenz_status === 'error'): ?>
                                <span class="simpbook-license-status status-invalid">✗ <?php
                                // translators: %s: License status code
                                printf(esc_html__('License problem (Status: %s)', 'simple-appointment-booking'), esc_html($lizenz_status)); ?></span>
                            <?php elseif (simpbook_is_trial_period_active()): ?>
                                <span class="simpbook-license-status status-trial"><?php esc_html_e('Trial period active', 'simple-appointment-booking'); ?></span>
                            <?php else: ?>
                                <span class="simpbook-license-status status-none"><?php esc_html_e('No active license', 'simple-appointment-booking'); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <input type="submit" name="simpbook_lizenz_aktivieren" class="button-primary" value="<?php esc_attr_e('Activate License', 'simple-appointment-booking'); ?>" />
                    <a href="https://mobile-refuel.de/tischreservierung-plugin-pro/" target="_blank" rel="noopener noreferrer" class="button button-secondary">
                        <?php esc_html_e('Purchase License', 'simple-appointment-booking'); ?>
                    </a>
                </p>
            </form>
        </div>

        <!-- Rabatt-Kachel: 30% Rabatt bei Bewertung -->
        <?php if (!simpbook_ist_lizenz_aktiv_raw()) : ?>
        <div class="simpbook-review-discount-card">
            <div class="simpbook-review-discount-header">
                <span class="simpbook-review-discount-badge"><?php esc_html_e('30% DISCOUNT', 'simple-appointment-booking'); ?></span>
                <h2><?php esc_html_e('Save 30% on all licenses!', 'simple-appointment-booking'); ?></h2>
            </div>
            <div class="simpbook-review-discount-content">
                <p class="simpbook-review-discount-intro">
                    <?php esc_html_e('Help us make the plugin more popular and get an exclusive 30% discount on all license types!', 'simple-appointment-booking'); ?>
                </p>
                <div class="simpbook-review-discount-steps">
                    <h3><?php esc_html_e('How to get your discount code:', 'simple-appointment-booking'); ?></h3>
                    <ol>
                        <li>
                            <strong><?php esc_html_e('Submit a review', 'simple-appointment-booking'); ?></strong>
                            <p><?php esc_html_e('Rate our plugin in the WordPress Plugin Directory and share your experiences with other users.', 'simple-appointment-booking'); ?></p>
                            <a href="https://wordpress.org/plugins/simple-appointment-booking/" target="_blank" rel="noopener noreferrer" class="button button-primary simpbook-review-button">
                                <?php esc_html_e('Rate now', 'simple-appointment-booking'); ?>
                            </a>
                        </li>
                        <li>
                            <strong><?php esc_html_e('Send screenshot', 'simple-appointment-booking'); ?></strong>
                            <p><?php esc_html_e('Send a screenshot of your review to:', 'simple-appointment-booking'); ?> <a href="mailto:plugins@mobile-refuel.de">plugins@mobile-refuel.de</a></p>
                        </li>
                        <li>
                            <strong><?php esc_html_e('Receive discount code', 'simple-appointment-booking'); ?></strong>
                            <p><?php esc_html_e('We will send you your personal 30% discount code for all license types within 24 hours.', 'simple-appointment-booking'); ?></p>
                        </li>
                    </ol>
                </div>
                <div class="simpbook-review-discount-note">
                    <p><strong><?php esc_html_e('Note:', 'simple-appointment-booking'); ?></strong> <?php esc_html_e('This discount code can be applied to all available license types and is valid for one-time use.', 'simple-appointment-booking'); ?></p>
                </div>
            </div>
        </div>
        <?php endif; ?>

    <?php if ($lizenz_status === 'limit_reached'): ?>
        <div class="notice notice-error"><p><strong><?php esc_html_e('License limit reached!', 'simple-appointment-booking'); ?></strong> <?php esc_html_e('Please purchase a new license or contact support.', 'simple-appointment-booking'); ?></p></div>
    <?php elseif ($lizenz_status !== 'gueltig' && !simpbook_is_trial_period_active() && simpbook_get_option('simpbook_trial_ever_started')): ?>
        <div class="notice notice-warning"><p><strong><?php esc_html_e('Note:', 'simple-appointment-booking'); ?></strong> <?php esc_html_e('Without a valid license or active trial period, not all features are available.', 'simple-appointment-booking'); ?></p></div>
    <?php endif; ?>
    </div>
    <?php
}

/**
 * Validiert einen Lizenzschlüssel gegen den Lizenzserver.
 */
function simpbook_lizenz_validieren($lizenz_key) {
    $lizenz_server_url = 'https://mobile-refuel.de/wp-content/plugins/mobile-refuel-lizenzserver/lizenzen/check_license.php';
    $token = 'aP39F3kLc9x!mZ82';
    $domain = home_url();

    $response = wp_remote_get(add_query_arg(
        [
            'key' => urlencode($lizenz_key),
            'token' => $token,
            'domain' => urlencode($domain),
            'plugin_slug' => SIMPBOOK_PLUGIN_SLUG,
            'action' => 'check_license'
        ],
        $lizenz_server_url
    ), ['timeout' => 15]);

    if (is_wp_error($response)) {
        simpbook_update_option('simpbook_lizenz_status', 'error');
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (!$data) {
        simpbook_update_option('simpbook_lizenz_status', 'error');
        return false;
    }

    if (isset($data['status'])) {
        if ($data['status'] === 'valid') {
            simpbook_update_option('simpbook_lizenz_status', 'gueltig');
            simpbook_delete_option('simpbook_trial_start_time');
            simpbook_delete_option('simpbook_server_configured_trial_duration_seconds');
            simpbook_delete_option('simpbook_trial_duration_last_server_check_timestamp');
            return true;
        } elseif (in_array($data['status'], ['invalid', 'limit_reached', 'error'])) {
            simpbook_update_option('simpbook_lizenz_status', $data['status']);
            return false;
        }
    }
    simpbook_update_option('simpbook_lizenz_status', 'error');
    return false;
}

/**
 * Prüft, ob eine Lizenz aktiv ist (nur Status 'gueltig').
 */
function simpbook_ist_lizenz_aktiv_raw() {
    return simpbook_get_option('simpbook_lizenz_status') === 'gueltig';
}

/**
 * Prüft, ob die Testphase aktiv ist.
 */
function simpbook_is_trial_period_active() {
    if (simpbook_ist_lizenz_aktiv_raw()) return false;
    $trial_start_time = simpbook_get_option('simpbook_trial_start_time');
    if (empty($trial_start_time) || !simpbook_get_option('simpbook_trial_ever_started')) return false;
    $actual_trial_duration = simpbook_get_active_trial_duration_seconds();
    return (time() - $trial_start_time) < $actual_trial_duration;
}

/**
 * Prüft, ob die Testphase abgelaufen ist und keine Lizenz aktiv ist.
 */
function simpbook_is_trial_expired_and_no_license() {
    if (simpbook_ist_lizenz_aktiv_raw()) return false;
    $trial_ever_started = simpbook_get_option('simpbook_trial_ever_started');
    if (!$trial_ever_started) return true;
    $trial_start_time = simpbook_get_option('simpbook_trial_start_time');
    if (empty($trial_start_time)) return true;
    $actual_trial_duration = simpbook_get_active_trial_duration_seconds();
    return (time() - $trial_start_time) >= $actual_trial_duration;
}

/**
 * Prüft, ob der Benutzer vollen Zugriff auf Plugin-Funktionen hat.
 */
function simpbook_has_full_access() {
    if (simpbook_ist_lizenz_aktiv_raw()) return true;
    if (simpbook_is_trial_period_active()) return true;
    if (!simpbook_get_option('simpbook_trial_ever_started') && !simpbook_ist_lizenz_aktiv_raw()) return true;
    return false;
}

/**
 * Initialisiert die Trial- und Lizenzprüfung.
 */
function simpbook_trial_and_license_check_init() {
    if (simpbook_ist_lizenz_aktiv_raw()) {
        if (simpbook_get_option('simpbook_trial_start_time')) {
            simpbook_delete_option('simpbook_trial_start_time');
        }
        return;
    }

    if (!simpbook_get_option('simpbook_trial_ever_started')) {
        simpbook_fetch_and_cache_trial_duration();
        simpbook_update_option('simpbook_trial_start_time', time());
        simpbook_update_option('simpbook_trial_ever_started', true);
        simpbook_delete_option('simpbook_trial_settings_reset_done');
        add_action('admin_notices', 'simpbook_trial_started_admin_notice');
        return;
    }

    $last_check_timestamp = simpbook_get_option('simpbook_trial_duration_last_server_check_timestamp', 0);
    if (time() - $last_check_timestamp > 12 * HOUR_IN_SECONDS) {
        if (simpbook_is_trial_period_active() || !simpbook_ist_lizenz_aktiv_raw()) {
            simpbook_fetch_and_cache_trial_duration();
        }
    }

    if (simpbook_is_trial_expired_and_no_license()) {
        if (!simpbook_get_option('simpbook_trial_settings_reset_done', false)) {
            simpbook_reset_plugin_settings_to_defaults();
            add_action('admin_notices', 'simpbook_trial_expired_settings_reset_admin_notice');
        } else {
            add_action('admin_notices', 'simpbook_trial_expired_restricted_admin_notice');
        }
    } elseif (simpbook_is_trial_period_active()) {
        add_action('admin_notices', 'simpbook_trial_active_admin_notice');
    } elseif (!simpbook_ist_lizenz_aktiv_raw() && !simpbook_is_trial_period_active()) {
        add_action('admin_notices', 'simpbook_generic_no_license_admin_notice');
    }
}
add_action('admin_init', 'simpbook_trial_and_license_check_init', 1);

function simpbook_display_admin_notice_wrapper($message_cb_name, $type = 'info') {
    $screen = get_current_screen();
    if ($screen && (strpos($screen->id, 'simpbook-reservierungen') !== false || in_array($screen->id, ['dashboard', 'plugins', 'toplevel_page_simpbook-reservierungen']))) {
        // Admin Notices werden nur auf relevanten Seiten angezeigt
         add_action('admin_notices', function() use ($message_cb_name, $type) {
            ?>
            <div class="notice notice-<?php echo esc_attr($type); ?> is-dismissible">
                <p><?php call_user_func($message_cb_name); ?></p>
            </div>
            <?php
        });
    }
}

function simpbook_trial_started_admin_notice_text() {
    printf(
        // translators: %s: URL to license page
        esc_html__('Thank you for using the PocketBooking Calendar Plugin! Your trial period (based on server settings) has started. Enter your license key on the <a href="%s">License page</a> to use all features permanently.', 'simple-appointment-booking'),
        esc_url(admin_url('admin.php?page=simpbook-reservierungen-lizenz'))
    );
}

function simpbook_trial_active_admin_notice_text() {
    $trial_start_time = simpbook_get_option('simpbook_trial_start_time');
    if (!$trial_start_time) return;

    $active_trial_duration = simpbook_get_active_trial_duration_seconds();
    $time_left_seconds = ($trial_start_time + $active_trial_duration) - time();

    if ($time_left_seconds < 0) $time_left_seconds = 0;

    $days = floor($time_left_seconds / (24 * 60 * 60));
    $hours = floor(($time_left_seconds % (24 * 60 * 60)) / (60 * 60));
    $minutes = floor(($time_left_seconds % (60 * 60)) / 60);

    $time_display_parts = [];
    // translators: %d: Number of days
    if ($days > 0) $time_display_parts[] = sprintf(_n('%d Tag', '%d Tage', $days, 'simple-appointment-booking'), $days);
    // translators: %d: Number of hours
    if ($hours > 0) $time_display_parts[] = sprintf(_n('%d Stunde', '%d Stunden', $hours, 'simple-appointment-booking'), $hours);
    // translators: %d: Number of minutes
    if ($minutes > 0 || empty($time_display_parts)) $time_display_parts[] = sprintf(_n('%d Minute', '%d Minuten', $minutes, 'simple-appointment-booking'), $minutes);

    $time_display_string = !empty($time_display_parts) ? implode(', ', $time_display_parts) : __('less than a minute', 'simple-appointment-booking');

    printf(
        // translators: %1$s: Time remaining (e.g., "2 Tage, 3 Stunden"), %2$s: URL to license page
        esc_html__('Your trial period for the PocketBooking Calendar Plugin has approximately %1$s remaining. Please enter your license key on the <a href="%2$s">License page</a> to continue using the plugin without restrictions.', 'simple-appointment-booking'),
        '<strong>' . esc_html($time_display_string) . '</strong>',
        esc_url(admin_url('admin.php?page=simpbook-reservierungen-lizenz'))
    );
}

function simpbook_trial_expired_settings_reset_admin_notice_text() {
    printf(
        // translators: %s: URL to license page
        esc_html__('Your trial period for the PocketBooking Calendar Plugin has expired. Plugin settings have been reset to defaults. Some features are now restricted. Please enter a valid license key on the <a href="%s">License page</a> to regain full access.', 'simple-appointment-booking'),
        esc_url(admin_url('admin.php?page=simpbook-reservierungen-lizenz'))
    );
}

function simpbook_trial_expired_restricted_admin_notice_text() {
    printf(
        // translators: %s: URL to license page
        esc_html__('Your trial period for the PocketBooking Calendar Plugin has expired and some features are restricted. Please enter a valid license key on the <a href="%s">License page</a> to regain full access.', 'simple-appointment-booking'),
        esc_url(admin_url('admin.php?page=simpbook-reservierungen-lizenz'))
    );
}

function simpbook_generic_no_license_admin_notice_text() {
     printf(
        // translators: %s: URL to license page
        esc_html__('No active license or trial period exists for the PocketBooking Calendar Plugin. Please enter a valid license key on the <a href="%s">License page</a> to use all features.', 'simple-appointment-booking'),
        esc_url(admin_url('admin.php?page=simpbook-reservierungen-lizenz'))
    );
}

/**
 * Zeigt den Testphase-Hinweis auf allen Admin-Seiten des Plugins an.
 * Diese Funktion sollte am Anfang jeder Admin-Seite aufgerufen werden.
 */
function simpbook_display_trial_notice_on_admin_pages() {
    // Nur anzeigen, wenn Testphase aktiv ist und keine gültige Lizenz vorhanden ist
    if (!simpbook_ist_lizenz_aktiv_raw() && simpbook_get_option('simpbook_trial_ever_started')) {
        if (simpbook_is_trial_period_active()) {
            $trial_start_time = simpbook_get_option('simpbook_trial_start_time');
            $active_trial_duration = simpbook_get_active_trial_duration_seconds();
            $time_left_seconds = ($trial_start_time + $active_trial_duration) - time();

            if ($time_left_seconds < 0) $time_left_seconds = 0;

            $days = floor($time_left_seconds / (24 * 60 * 60));
            $seconds_remaining_after_days = $time_left_seconds % (24 * 60 * 60);
            $hours = floor($seconds_remaining_after_days / (60 * 60));
            $seconds_remaining_after_hours = $seconds_remaining_after_days % (60 * 60);
            $minutes = floor($seconds_remaining_after_hours / 60);

            $time_display_parts = [];
            // translators: %d: Number of days
            if ($days > 0) $time_display_parts[] = sprintf(_n('%d Tag', '%d Tage', $days, 'simple-appointment-booking'), $days);
            // translators: %d: Number of hours
            if ($hours > 0) $time_display_parts[] = sprintf(_n('%d Stunde', '%d Stunden', $hours, 'simple-appointment-booking'), $hours);
            // translators: %d: Number of minutes
            if ($minutes > 0 || empty($time_display_parts)) $time_display_parts[] = sprintf(_n('%d Minute', '%d Minuten', $minutes, 'simple-appointment-booking'), $minutes);

            $time_display_string = !empty($time_display_parts) ? implode(', ', $time_display_parts) : esc_html__('less than a minute', 'simple-appointment-booking');

            // translators: %s: Time remaining (e.g., "2 Tage, 3 Stunden")
            echo '<div class="notice notice-info inline simpbook-trial-notice"><p>' . sprintf(esc_html__('Your trial period is active and runs for approximately %s more.', 'simple-appointment-booking'), '<strong>' . esc_html($time_display_string) . '</strong>') . '</p></div>';
        }
    }
}

function simpbook_trial_started_admin_notice() { simpbook_display_admin_notice_wrapper('simpbook_trial_started_admin_notice_text', 'info'); }
function simpbook_trial_active_admin_notice() { simpbook_display_admin_notice_wrapper('simpbook_trial_active_admin_notice_text', 'warning'); }
function simpbook_trial_expired_settings_reset_admin_notice() { simpbook_display_admin_notice_wrapper('simpbook_trial_expired_settings_reset_admin_notice_text', 'error'); }
function simpbook_trial_expired_restricted_admin_notice() { simpbook_display_admin_notice_wrapper('simpbook_trial_expired_restricted_admin_notice_text', 'error'); }
function simpbook_generic_no_license_admin_notice() { simpbook_display_admin_notice_wrapper('simpbook_generic_no_license_admin_notice_text', 'error');}

/**
 * Passt das Admin-Menü basierend auf dem Lizenzstatus an.
 */
function simpbook_admin_menu_anpassen() {
    global $submenu;
    if (!simpbook_has_full_access() && isset($submenu['simpbook-dashboard'])) {
        foreach ($submenu['simpbook-dashboard'] as $key => $item) {
            // Lizenzseite und Buchungsseite IMMER sichtbar halten (auch ohne Zugriff)
            if ($item[2] === 'simpbook-reservierungen-lizenz' || $item[2] === 'simpbook-reservierungen') {
                continue; // Nicht löschen!
            }
            // Alle anderen Seiten ausblenden
            unset($submenu['simpbook-dashboard'][$key]);
        }
    }
}
add_action('admin_menu', 'simpbook_admin_menu_anpassen', 999);

/**
 * Schützt die Einstellungsseite vor unberechtigtem Zugriff.
 */
function simpbook_einstellungen_seite_schuetzen() {
    global $pagenow;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for page identification only
    $current_page = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';

    if ($pagenow === 'admin.php' && $current_page === 'simpbook-reservierungen-einstellungen') {
        if (!simpbook_has_full_access()) {
            $lizenz_status = simpbook_get_option('simpbook_lizenz_status');
            $is_trial_expired = simpbook_is_trial_expired_and_no_license();
            $error_type = 'access_denied';

            if ($lizenz_status === 'limit_reached') $error_type = 'limit_reached';
            elseif ($is_trial_expired) $error_type = 'trial_expired';
            elseif (!simpbook_ist_lizenz_aktiv_raw()) $error_type = 'no_license';

            wp_safe_redirect(admin_url('admin.php?page=simpbook-reservierungen-lizenz&error=' . $error_type . '&return_to=' . urlencode($current_page)));
            exit;
        }
    }
}
add_action('admin_init', 'simpbook_einstellungen_seite_schuetzen', 2);
