<?php
/**
 * Einstellungen & Admin-Logik für PocketBooking Calendar
 *
 * @package SimpleBookingCalendar
 * @since 1.1.3
 */

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

// === AJAX-HANDLER ===

/**
 * AJAX-Handler zum Speichern der Sprachüberschreibung
 */
function simpbook_ajax_save_language_override() {
    // Nonce überprüfen
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'simpbook_language_override_nonce')) {
        wp_send_json_error('Invalid nonce');
        return;
    }

    // Berechtigungen prüfen
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'auto';
    $supported = simpbook_get_supported_languages();
    
    if ($language === 'auto' || in_array($language, $supported, true)) {
        simpbook_update_option('simpbook_language_override', $language);
        // Reload textdomain to apply new language immediately
        if (class_exists('simpbook_DB_Reservierungen')) {
            simpbook_DB_Reservierungen::reload_plugin_textdomain();
        }
        wp_send_json_success();
    } else {
        wp_send_json_error('Invalid language');
    }
}
add_action('wp_ajax_simpbook_save_language_override', 'simpbook_ajax_save_language_override');

// === EINSTELLUNGS-FUNKTIONEN ===

/**
 * Gibt die Standardeinstellungen des Plugins zurück.
 */
function simpbook_get_default_settings_map() {
    $wochentage_keys_for_settings = ['montag', 'dienstag', 'mittwoch', 'donnerstag', 'freitag', 'samstag', 'sonntag'];
    $wochentage_defaults = [];
    $standard_beginn = '11:00'; $standard_ende = '22:00';
    foreach ($wochentage_keys_for_settings as $tag_key) {
        $wochentage_defaults[$tag_key] = ['aktiv' => '1', 'beginn' => $standard_beginn, 'ende' => $standard_ende];
    }
    return [
        'simpbook_email_benachrichtigungen' => '1',
        'simpbook_benachrichtigungs_email' => get_option('admin_email'),
        'simpbook_firmen_name' => get_bloginfo('name'),
        'simpbook_email_bestaetigt_betreff' => __('Your booking for {service_name} has been confirmed', 'simple-appointment-booking'),
        'simpbook_email_bestaetigt_nachricht' => sprintf("%s {name},\n\n%s {service_name} %s {date} %s {time} %s.\n%s: {employee_name}\n\n%s:\n{cancellation_link}\n\n%s\n\n%s\n{company_name}",__('Dear','simple-appointment-booking'),__('Your booking for','simple-appointment-booking'),__('am','simple-appointment-booking'),__('at','simple-appointment-booking'),__('has been confirmed','simple-appointment-booking'),__('Staff','simple-appointment-booking'),__('You can cancel your booking at any time using the following link','simple-appointment-booking'),__('We look forward to your visit!','simple-appointment-booking'),__('Best regards','simple-appointment-booking')),
        'simpbook_email_abgelehnt_betreff' => __('Information zu Ihrer Buchungsanfrage', 'simple-appointment-booking'),
        'simpbook_email_abgelehnt_nachricht' => sprintf("%s {name},\n\n%s {service_name} %s {date} %s {time} %s.\n\n%s\n\n%s\n{company_name}",__('Dear','simple-appointment-booking'),__('we regret to inform you that your booking request for','simple-appointment-booking'),__('am','simple-appointment-booking'),__('at','simple-appointment-booking'),__('unfortunately cannot be confirmed','simple-appointment-booking'),__('Please contact us for alternative dates or if you have questions.','simple-appointment-booking'),__('Best regards','simple-appointment-booking')),
        'simpbook_email_bestaetigungs_betreff' => __('Your request for {service_name} has been received', 'simple-appointment-booking'),
        'simpbook_email_bestaetigungs_nachricht' => sprintf("%s {name},\n\n%s {company_name}. %s:\n\n%s: {service_name}\n%s: {date}\n%s: {time}\n%s: {employee_name}\n\n%s: {message}\n\n%s\n\n%s\n{company_name}",__('Dear','simple-appointment-booking'),__('thank you for your inquiry at','simple-appointment-booking'),__('Wir haben folgende Buchungsanfrage erhalten','simple-appointment-booking'),__('Service','simple-appointment-booking'),__('Date','simple-appointment-booking'),__('Time','simple-appointment-booking'),__('Staff','simple-appointment-booking'),__('Your message','simple-appointment-booking'),__('We will check availability and get back to you as soon as possible.','simple-appointment-booking'),__('Best regards','simple-appointment-booking')),
        'simpbook_email_erinnerung_betreff' => __('Reminder: Your booking for {service_name}', 'simple-appointment-booking'),
        'simpbook_email_erinnerung_nachricht' => sprintf("%s {name},\n\n%s {company_name}:\n\n%s: {service_name}\n%s: {date}\n%s: {time}\n%s: {employee_name}\n\n%s:\n{cancellation_link}\n\n%s\n\n%s\n{company_name}",__('Dear','simple-appointment-booking'),__('we would like to remind you that you have an appointment at','simple-appointment-booking'),__('Service','simple-appointment-booking'),__('Date','simple-appointment-booking'),__('Time','simple-appointment-booking'),__('Staff','simple-appointment-booking'),__('If you cannot keep the appointment, you can cancel it here','simple-appointment-booking'),__('We look forward to your visit!','simple-appointment-booking'),__('Best regards','simple-appointment-booking')),
        'simpbook_email_storniert_betreff' => __('Ihre Buchung wurde storniert', 'simple-appointment-booking'),
        'simpbook_email_storniert_nachricht' => sprintf("%s {name},\n\n%s {service_name} %s {date} %s {time} %s.\n\n%s\n\n%s\n{company_name}",__('Dear','simple-appointment-booking'),__('Your booking for','simple-appointment-booking'),__('am','simple-appointment-booking'),__('at','simple-appointment-booking'),__('Uhr wurde erfolgreich storniert','simple-appointment-booking'),__('If you have any questions or would like to make a new booking, please contact us.','simple-appointment-booking'),__('Best regards','simple-appointment-booking')),
        'simpbook_container_background' => '#8bbce4', 'simpbook_text_color' => '#000000', 'simpbook_button_color' => '#2271b1', 'simpbook_tile_background' => '#ffffff', 'simpbook_tile_text_color' => '#333333',
        'simpbook_border_radius' => 8,
        'simpbook_tile_border_radius' => 12,
        'simpbook_button_text_color' => '#ffffff',
        'simpbook_button_border_radius' => 8,
        // Formular-Überschriften haben keine Standardwerte hier, da sie sprachspezifisch über simpbook_get_form_header_defaults() geladen werden
        'simpbook_max_personen' => 20, 'simpbook_verweildauer' => 90, // Werden nicht mehr verwendet, bleiben für Kompatibilität
        'simpbook_wochentag_zeiten' => $wochentage_defaults, 'simpbook_intervall' => 30,
        // 'simpbook_ausgeschlossene_tage' => '', // Alte Option, wird durch neue ersetzt
        'simpbook_spezielle_tage_konfiguration' => [], // NEUE OPTION für spezielle Tage
        'simpbook_urlaub_konfiguration' => [], // Urlaub & Saison Zeiträume
        'simpbook_mindestvorlauf_stunden' => 2, // Mindestvorlaufzeit in Stunden
        'simpbook_maximale_vorlauf_tage' => 30, // Maximale Vorlaufzeit in Tagen
        'simpbook_erinnerung_aktiv' => 1, // Erinnerungs-E-Mails aktivieren
        'simpbook_erinnerung_vor_stunden' => 24, // Erinnerung X Stunden vor Termin
        'simpbook_dauer_anzeigen' => '1', // Dienstleistungsdauer im Frontend anzeigen
    ];
}

/**
 * Setzt Plugin-Einstellungen auf Standardwerte zurück.
 */
function simpbook_reset_plugin_settings_to_defaults() {
    $default_settings = simpbook_get_default_settings_map();
    foreach ($default_settings as $option_name => $default_value) {
        simpbook_update_option($option_name, $default_value);
    }
    simpbook_update_option('simpbook_trial_settings_reset_done', true);
}

/**
 * Verarbeitet das Einstellungsformular, bevor Header gesendet werden.
 */
function simpbook_einstellungen_formular_verarbeiten() {
    // Nur auf der Einstellungsseite ausführen
    if (!isset($_GET['page']) || $_GET['page'] !== 'simpbook-reservierungen-einstellungen') {
        return;
    }

    // Nur wenn das Formular abgeschickt wurde
    if (!isset($_POST['simpbook_einstellungen_submit'])) {
        return;
    }

    // Nonce überprüfen
    check_admin_referer('simpbook_einstellungen');

    // Einmalige Migration: Lösche alte globale Formular-Überschriften-Optionen (ohne Sprachsuffix)
    // Diese wurden vor der Implementierung der sprachspezifischen Speicherung verwendet
    if (!get_option('simpbook_form_headers_migrated', false)) {
        delete_option('simpbook_form_header_date');
        delete_option('simpbook_form_header_service');
        delete_option('simpbook_form_header_employee');
        delete_option('simpbook_form_header_time');
        delete_option('simpbook_form_header_contact');
        update_option('simpbook_form_headers_migrated', true);
    }

    // Wochentage definieren
    $wochentage = [
        'montag' => 'Monday',
        'dienstag' => 'Tuesday',
        'mittwoch' => 'Wednesday',
        'donnerstag' => 'Thursday',
        'freitag' => 'Friday',
        'samstag' => 'Saturday',
        'sonntag' => 'Sunday'
    ];

    // Sprachoption speichern (Override)
    if (isset($_POST['simpbook_language_override'])) {
        $language_override = sanitize_text_field(wp_unslash($_POST['simpbook_language_override']));
        // Erlauben: 'auto' oder unterstützte Sprachen
        $supported = simpbook_get_supported_languages();
        if (!empty($language_override) && ($language_override === 'auto' || in_array($language_override, $supported, true))) {
            simpbook_update_option('simpbook_language_override', $language_override);
            // Reload textdomain to apply new language immediately
            simpbook_DB_Reservierungen::reload_plugin_textdomain();
        }
    }

    // Alle anderen Einstellungen speichern (vereinfacht - nur die wichtigsten)
    // E-Mail-Benachrichtigungen
    $benachrichtigungen = isset($_POST['simpbook_email_benachrichtigungen']) ? '1' : '0';
    update_option('simpbook_email_benachrichtigungen', $benachrichtigungen);

    // E-Mail für Benachrichtigungen
    if (isset($_POST['simpbook_benachrichtigungs_email']) && !empty($_POST['simpbook_benachrichtigungs_email'])) {
        $email = sanitize_email(wp_unslash($_POST['simpbook_benachrichtigungs_email']));
        update_option('simpbook_benachrichtigungs_email', $email);
    }

    // Buchungseinstellungen
    if (isset($_POST['simpbook_mindestvorlauf_stunden'])) {
        $mindestvorlauf = intval($_POST['simpbook_mindestvorlauf_stunden']);
        $mindestvorlauf = max(0, min(168, $mindestvorlauf)); // 0-168 Stunden
        update_option('simpbook_mindestvorlauf_stunden', $mindestvorlauf);
    }
    if (isset($_POST['simpbook_maximale_vorlauf_tage'])) {
        $maximale_vorlauf = intval($_POST['simpbook_maximale_vorlauf_tage']);
        $maximale_vorlauf = max(0, min(365, $maximale_vorlauf)); // 0-365 Tage
        update_option('simpbook_maximale_vorlauf_tage', $maximale_vorlauf);
    }
    // Auto-Bestätigung
    if (isset($_POST['simpbook_auto_bestaetigung'])) {
        update_option('simpbook_auto_bestaetigung', '1');
    } else {
        update_option('simpbook_auto_bestaetigung', '0');
    }
    if (isset($_POST['simpbook_erinnerung_aktiv'])) {
        update_option('simpbook_erinnerung_aktiv', 1);
    } else {
        update_option('simpbook_erinnerung_aktiv', 0);
    }
    if (isset($_POST['simpbook_erinnerung_vor_stunden'])) {
        $erinnerung_stunden = intval($_POST['simpbook_erinnerung_vor_stunden']);
        $erinnerung_stunden = max(1, min(168, $erinnerung_stunden)); // 1-168 Stunden
        update_option('simpbook_erinnerung_vor_stunden', $erinnerung_stunden);
    }

    // Firmen-Informationen
    update_option('simpbook_firmen_name', sanitize_text_field(wp_unslash($_POST['simpbook_firmen_name'] ?? get_bloginfo('name'))));

    // Email Header Logo
    update_option('simpbook_email_header_logo', esc_url_raw(wp_unslash($_POST['simpbook_email_header_logo'] ?? '')));

    // E-Mail-Vorlagen (sprachspezifisch speichern)
    $save_language = simpbook_get_current_language();
    simpbook_save_email_template('simpbook_email_bestaetigt_betreff', sanitize_text_field(wp_unslash($_POST['simpbook_email_bestaetigt_betreff'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_bestaetigt_nachricht', sanitize_textarea_field(wp_unslash($_POST['simpbook_email_bestaetigt_nachricht'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_abgelehnt_betreff', sanitize_text_field(wp_unslash($_POST['simpbook_email_abgelehnt_betreff'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_abgelehnt_nachricht', sanitize_textarea_field(wp_unslash($_POST['simpbook_email_abgelehnt_nachricht'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_bestaetigungs_betreff', sanitize_text_field(wp_unslash($_POST['simpbook_email_bestaetigungs_betreff'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_bestaetigungs_nachricht', sanitize_textarea_field(wp_unslash($_POST['simpbook_email_bestaetigungs_nachricht'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_erinnerung_betreff', sanitize_text_field(wp_unslash($_POST['simpbook_email_erinnerung_betreff'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_erinnerung_nachricht', sanitize_textarea_field(wp_unslash($_POST['simpbook_email_erinnerung_nachricht'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_storniert_betreff', sanitize_text_field(wp_unslash($_POST['simpbook_email_storniert_betreff'] ?? '')), $save_language);
    simpbook_save_email_template('simpbook_email_storniert_nachricht', sanitize_textarea_field(wp_unslash($_POST['simpbook_email_storniert_nachricht'] ?? '')), $save_language);

    // Stornierungen-Einstellungen
    $stornierung_aktiviert = isset($_POST['simpbook_stornierung_aktiviert']) ? '1' : '0';
    update_option('simpbook_stornierung_aktiviert', $stornierung_aktiviert);

    if (isset($_POST['simpbook_stornierung_mindeststunden'])) {
        $mindeststunden = intval($_POST['simpbook_stornierung_mindeststunden']);
        $mindeststunden = max(0, $mindeststunden); // Mindestens 0
        update_option('simpbook_stornierung_mindeststunden', $mindeststunden);
    }

    if (isset($_POST['simpbook_stornierung_telefonnummer'])) {
        $telefonnummer = sanitize_text_field(wp_unslash($_POST['simpbook_stornierung_telefonnummer']));
        update_option('simpbook_stornierung_telefonnummer', $telefonnummer);
    }

    // Formular-Design
    if (isset($_POST['simpbook_container_background'])) {
        update_option('simpbook_container_background', sanitize_hex_color(wp_unslash($_POST['simpbook_container_background'])));

        // Border Radius
        if (isset($_POST['simpbook_border_radius'])) {
            $border_radius = intval(wp_unslash($_POST['simpbook_border_radius']));
            $border_radius = max(0, min(50, $border_radius)); // Begrenze auf 0-50px
            update_option('simpbook_border_radius', $border_radius);
        }
    }
    if (isset($_POST['simpbook_text_color'])) {
        update_option('simpbook_text_color', sanitize_hex_color(wp_unslash($_POST['simpbook_text_color'])));
    }
    if (isset($_POST['simpbook_button_color'])) {
        update_option('simpbook_button_color', sanitize_hex_color(wp_unslash($_POST['simpbook_button_color'])));
    }
    if (isset($_POST['simpbook_button_text_color'])) {
        update_option('simpbook_button_text_color', sanitize_hex_color(wp_unslash($_POST['simpbook_button_text_color'])));
    }
    if (isset($_POST['simpbook_button_border_radius'])) {
        $btn_border_radius = intval(wp_unslash($_POST['simpbook_button_border_radius']));
        $btn_border_radius = max(0, min(50, $btn_border_radius));
        update_option('simpbook_button_border_radius', $btn_border_radius);
    }
    if (isset($_POST['simpbook_tile_background'])) {
        update_option('simpbook_tile_background', sanitize_hex_color(wp_unslash($_POST['simpbook_tile_background'])));
    }
    if (isset($_POST['simpbook_tile_text_color'])) {
        update_option('simpbook_tile_text_color', sanitize_hex_color(wp_unslash($_POST['simpbook_tile_text_color'])));
    }
    if (isset($_POST['simpbook_tile_border_radius'])) {
        $tile_border_radius = intval(wp_unslash($_POST['simpbook_tile_border_radius']));
        $tile_border_radius = max(0, min(50, $tile_border_radius)); // Begrenze auf 0-50px
        update_option('simpbook_tile_border_radius', $tile_border_radius);
    }
    
    // Formular-Überschriften (sprachspezifisch speichern)
    simpbook_save_form_header('date', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_date'] ?? '')), $save_language);
    simpbook_save_form_header('service', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_service'] ?? '')), $save_language);
    simpbook_save_form_header('employee', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_employee'] ?? '')), $save_language);
    simpbook_save_form_header('time', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_time'] ?? '')), $save_language);
    simpbook_save_form_header('contact', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_contact'] ?? '')), $save_language);
    simpbook_save_form_header('ungrouped_services', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_ungrouped_services'] ?? '')), $save_language);
    simpbook_save_form_header('booking_option', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_booking_option'] ?? '')), $save_language);
    simpbook_save_form_header('confirmation', sanitize_text_field(wp_unslash($_POST['simpbook_form_header_confirmation'] ?? '')), $save_language);
    
    // max_personen und verweildauer werden nicht mehr verwendet, aber für Kompatibilität beibehalten
    // Tagesweise Reservierungszeiten
    $zeiten = [];
    foreach ($wochentage as $tag_key => $tag_name) {
        $aktiv = isset($_POST["simpbook_{$tag_key}_aktiv"]) ? '1' : '0';
        $beginn = sanitize_text_field(wp_unslash($_POST["simpbook_{$tag_key}_beginn"] ?? ''));
        $ende = sanitize_text_field(wp_unslash($_POST["simpbook_{$tag_key}_ende"] ?? ''));
        $zeiten[$tag_key] = [
            'aktiv' => $aktiv,
            'beginn' => $beginn,
            'ende' => $ende
        ];
    }
    update_option('simpbook_wochentag_zeiten', $zeiten);

    // Intervall
    if (isset($_POST['simpbook_intervall'])) {
        $intervall = intval($_POST['simpbook_intervall']);
        update_option('simpbook_intervall', $intervall);
    }

    // Spezielle Tage und Öffnungszeiten
    $spezielle_tage_konfiguration = [];
    if (isset($_POST['simpbook_spezielle_tage_daten']) && is_array($_POST['simpbook_spezielle_tage_daten'])) {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Array wird weiter unten validiert und sanitized
        $spezielle_tage_daten = wp_unslash($_POST['simpbook_spezielle_tage_daten']);
        foreach ($spezielle_tage_daten as $datum_str => $einstellungen) {
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $datum_str)) {
                $status = sanitize_text_field($einstellungen['status'] ?? 'geschlossen');
                $beginn = '';
                $ende = '';
                if ($status === 'speziell') {
                    if (isset($einstellungen['beginn']) && preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $einstellungen['beginn'])) {
                        $beginn = sanitize_text_field($einstellungen['beginn']);
                    } else {
                        $status = 'geschlossen';
                    }
                    if (isset($einstellungen['ende']) && preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $einstellungen['ende'])) {
                        $ende = sanitize_text_field($einstellungen['ende']);
                    } else {
                        $status = 'geschlossen';
                    }
                    if ($status === 'speziell' && !empty($beginn) && !empty($ende) && strtotime($ende) <= strtotime($beginn)) {
                        $status = 'geschlossen';
                    }
                }
                $spezielle_tage_konfiguration[$datum_str] = [
                    'status' => $status,
                    'beginn' => $beginn,
                    'ende' => $ende,
                ];
            }
        }
    }
    ksort($spezielle_tage_konfiguration);
    update_option('simpbook_spezielle_tage_konfiguration', $spezielle_tage_konfiguration);

    // Urlaub & Saison Verwaltung speichern
    $urlaub_konfiguration = [];
    if (isset($_POST['simpbook_urlaub_konfiguration']) && is_array($_POST['simpbook_urlaub_konfiguration'])) {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $urlaub_daten = wp_unslash($_POST['simpbook_urlaub_konfiguration']);
        foreach ($urlaub_daten as $zeitraum) {
            $von = sanitize_text_field(isset($zeitraum['von']) ? $zeitraum['von'] : '');
            $bis = sanitize_text_field(isset($zeitraum['bis']) ? $zeitraum['bis'] : '');
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $von) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $bis) && $bis >= $von) {
                $urlaub_konfiguration[] = ['of' => $von, 'bis' => $bis];
            }
        }
    }
    update_option('simpbook_urlaub_konfiguration', $urlaub_konfiguration);

    // Aktualisiere simpbook_ausgeschlossene_tage
    $ausgeschlossene_tage_fuer_alte_option = [];
    foreach ($spezielle_tage_konfiguration as $datum_str => $einstellungen) {
        if (isset($einstellungen['status']) && $einstellungen['status'] === 'geschlossen') {
            $ausgeschlossene_tage_fuer_alte_option[] = $datum_str;
        }
    }
    sort($ausgeschlossene_tage_fuer_alte_option);
    update_option('simpbook_ausgeschlossene_tage', implode("\n", $ausgeschlossene_tage_fuer_alte_option));

    // Aktiven Tab aus POST oder GET übernehmen
    $redirect_tab = isset($_POST['simpbook_active_tab']) ? sanitize_text_field(wp_unslash($_POST['simpbook_active_tab'])) : (isset($_GET['simpbook_tab']) ? sanitize_text_field(wp_unslash($_GET['simpbook_tab'])) : 'general');
    $valid_tabs = array('general', 'opening-hours', 'cancellations', 'emails', 'design', 'formular', 'language', 'app');
    if (!in_array($redirect_tab, $valid_tabs, true)) {
        $redirect_tab = 'general';
    }
    
    // PWA App-Einstellungen speichern
    if (isset($_POST['simpbook_pwa_theme_color'])) {
        update_option('simpbook_pwa_theme_color', sanitize_hex_color(wp_unslash($_POST['simpbook_pwa_theme_color'])));
    }
    if (isset($_POST['simpbook_pwa_icon_192'])) {
        update_option('simpbook_pwa_icon_192', esc_url_raw(wp_unslash($_POST['simpbook_pwa_icon_192'])));
    }
    if (isset($_POST['simpbook_pwa_icon_512'])) {
        update_option('simpbook_pwa_icon_512', esc_url_raw(wp_unslash($_POST['simpbook_pwa_icon_512'])));
    }

    // Redirect-URL erstellen
    $redirect_args = array(
        'page' => 'simpbook-reservierungen-einstellungen',
        'simpbook_tab' => $redirect_tab,
        'simpbook_settings_updated' => 'true'
    );
    
    // PWA-Modus beibehalten
    if (isset($_GET['pwa']) && $_GET['pwa'] === '1') {
        $redirect_args['pwa'] = '1';
    }
    
    $redirect_url = add_query_arg($redirect_args, admin_url('admin.php'));

    // Redirect durchführen (BEVOR Header gesendet werden)
    wp_safe_redirect($redirect_url);
    exit;
}
add_action('admin_init', 'simpbook_einstellungen_formular_verarbeiten', 1);

/**
 * Verarbeitet das Dienstleistungen-Einstellungsformular.
 */
function simpbook_dienstleistungen_einstellungen_speichern() {
    if (!isset($_GET['page']) || $_GET['page'] !== 'simpbook-dienstleistungen-einstellungen') {
        return;
    }
    if (!isset($_POST['simpbook_dienstleistungen_einstellungen_submit'])) {
        return;
    }
    check_admin_referer('simpbook_dienstleistungen_einstellungen');

    if (isset($_POST['simpbook_dauer_anzeigen'])) {
        update_option('simpbook_dauer_anzeigen', '1');
    } else {
        update_option('simpbook_dauer_anzeigen', '0');
    }

    if (isset($_POST['simpbook_buchungsoptionen_aktiv'])) {
        update_option('simpbook_buchungsoptionen_aktiv', '1');
    } else {
        update_option('simpbook_buchungsoptionen_aktiv', '0');
    }

    $redirect_args = [
        'page'              => 'simpbook-dienstleistungen-einstellungen',
        'simpbook_nachricht' => 'gespeichert',
    ];
    if (isset($_GET['pwa']) && $_GET['pwa'] === '1') {
        $redirect_args['pwa'] = '1';
    }
    wp_safe_redirect(add_query_arg($redirect_args, admin_url('admin.php')));
    exit;
}
add_action('admin_init', 'simpbook_dienstleistungen_einstellungen_speichern', 1);

/**
 * Migriert alte Optionen (reservierung_*) zu neuen Optionen (simpbook_*)
 * Diese Funktion wird einmalig ausgeführt, um die Abwärtskompatibilität zu gewährleisten.
 */
function simpbook_migrate_options() {
    $migration_version = get_option('simpbook_migration_version', 0);
    
    if ($migration_version < 1) {
        $options_to_migrate = [
            'reservierung_intervall' => 'simpbook_intervall',
            'reservierung_wochentag_zeiten' => 'simpbook_wochentag_zeiten',
            'reservierung_ausgeschlossene_tage' => 'simpbook_ausgeschlossene_tage',
            'reservierung_email_benachrichtigungen' => 'simpbook_email_benachrichtigungen',
            'reservierung_benachrichtigungs_email' => 'simpbook_benachrichtigungs_email',
            'reservierung_stornierung_aktiviert' => 'simpbook_stornierung_aktiviert',
            'reservierung_stornierung_mindeststunden' => 'simpbook_stornierung_mindeststunden',
            'reservierung_stornierung_telefonnummer' => 'simpbook_stornierung_telefonnummer',
            'reservierung_button_color' => 'simpbook_button_color',
            'reservierung_container_background' => 'simpbook_container_background',
            'reservierung_text_color' => 'simpbook_text_color',
            'reservierung_tile_background' => 'simpbook_tile_background',
            'reservierung_border_radius' => 'simpbook_border_radius',
            'reservierung_firmen_name' => 'simpbook_firmen_name',
            'reservierung_erinnerung_aktiv' => 'simpbook_erinnerung_aktiv',
            'reservierung_erinnerung_vor_stunden' => 'simpbook_erinnerung_vor_stunden',
            'reservierung_mindestvorlauf_stunden' => 'simpbook_mindestvorlauf_stunden',
            'reservierung_maximale_vorlauf_tage' => 'simpbook_maximale_vorlauf_tage',
            'reservierung_spezielle_tage_konfiguration' => 'simpbook_spezielle_tage_konfiguration',
            'reservierung_language_override' => 'simpbook_language_override'
        ];

        foreach ($options_to_migrate as $old_key => $new_key) {
            $old_value = get_option($old_key);
            if ($old_value !== false) {
                // Nur migrieren, wenn die neue Option noch nicht existiert
                if (get_option($new_key) === false) {
                    update_option($new_key, $old_value);
                }
                // Wir löschen die alte Option NICHT sofort, um sicherzugehen
            }
        }

        // Email-Templates migrieren (dynamische Keys)
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Booking system requires direct DB access for real-time data
        $email_options = $wpdb->get_results($wpdb->prepare(
            "SELECT option_name, option_value FROM %i WHERE option_name LIKE %s",
            $wpdb->options,
            'reservierung_email_%'
        ));
        
        foreach ($email_options as $opt) {
            $new_opt_name = str_replace('reservierung_email_', 'simpbook_email_', $opt->option_name);
            if (get_option($new_opt_name) === false) {
                update_option($new_opt_name, maybe_unserialize($opt->option_value));
            }
        }

        update_option('simpbook_migration_version', 1);
    }
    
    // Migration 2: PWA-Spalten zur Mitarbeiter-Tabelle hinzufügen
    if ($migration_version < 2) {
        global $wpdb;
        $mitarbeiter_table = $wpdb->prefix . 'mitarbeiter';
        
        // Prüfe ob Spalten bereits existieren
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $columns = $wpdb->get_col("DESCRIBE {$mitarbeiter_table}", 0);
        
        // Spalte app_zugang_aktiv hinzufügen
        if (!in_array('app_zugang_aktiv', $columns, true)) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $wpdb->query("ALTER TABLE {$mitarbeiter_table} ADD COLUMN app_zugang_aktiv TINYINT(1) DEFAULT 0 NOT NULL AFTER aktiv");
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $wpdb->query("ALTER TABLE {$mitarbeiter_table} ADD KEY app_zugang (app_zugang_aktiv)");
        }
        
        // Spalte wp_user_id hinzufügen
        if (!in_array('wp_user_id', $columns, true)) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $wpdb->query("ALTER TABLE {$mitarbeiter_table} ADD COLUMN wp_user_id BIGINT(20) NULL AFTER app_zugang_aktiv");
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $wpdb->query("ALTER TABLE {$mitarbeiter_table} ADD KEY wp_user (wp_user_id)");
        }
        
        update_option('simpbook_migration_version', 2);
    }
}
add_action('admin_init', 'simpbook_migrate_options');

/**
 * Erstellt die Custom Role "Booking Manager" für App-Zugang
 * Wird bei Plugin-Aktivierung und bei Bedarf ausgeführt
 */
function simpbook_create_booking_manager_role() {
    // Prüfe ob Role bereits existiert
    $role = get_role('booking_manager');
    
    if (!$role) {
        add_role(
            'booking_manager',
            __('Booking Manager', 'simple-appointment-booking'),
            array(
                'read' => true,
                'manage_booking_app' => true,
                'view_bookings' => true,
                'edit_bookings' => true,
                'delete_bookings' => true,
                'view_calendar' => true,
                'view_statistics' => true,
                'manage_services' => true,
                'manage_employees' => true
            )
        );
    }
    
    // Admins die Custom Capabilities geben
    $admin_role = get_role('administrator');
    if ($admin_role) {
        $admin_role->add_cap('manage_booking_app');
        $admin_role->add_cap('view_bookings');
        $admin_role->add_cap('edit_bookings');
        $admin_role->add_cap('delete_bookings');
        $admin_role->add_cap('view_calendar');
        $admin_role->add_cap('view_statistics');
        $admin_role->add_cap('manage_services');
        $admin_role->add_cap('manage_employees');
    }
}
add_action('admin_init', 'simpbook_create_booking_manager_role');

/**
 * Entfernt die Booking Manager Role bei Plugin-Deaktivierung
 */
function simpbook_remove_booking_manager_role() {
    remove_role('booking_manager');
}
