<?php
// admin/neue-reservierung.php
// Direkten Zugriff verhindern
if (!defined('ABSPATH')) {
    exit;
}

// Testphase-Hinweis anzeigen
simpbook_display_trial_notice_on_admin_pages();

// CSS und JS werden bereits in admin_skripte_laden() geladen - NICHT hier, da zu spät!

// Wochentage und Zeiten aus der Datenbank laden
$simpbook_wochentag_zeiten = get_option('simpbook_wochentag_zeiten', []);
$simpbook_intervall = intval(get_option('simpbook_intervall', 30));
$simpbook_ausgeschlossene_tage = get_option('simpbook_ausgeschlossene_tage', '');
// Spezielle Tage-Konfiguration laden
$simpbook_default_map = simpbook_get_default_settings_map();
$simpbook_spezielle_tage_konfiguration = simpbook_get_option('simpbook_spezielle_tage_konfiguration', $simpbook_default_map['simpbook_spezielle_tage_konfiguration']);
// Alle Dienstleistungen laden (sortiert nach Kategorien)
$simpbook_alle_dienstleistungen = simpbook_get_all_dienstleistungen_sorted_by_kategorie(true); // Nur aktive

// Kategorien für Gruppierung laden
$simpbook_alle_kategorien = simpbook_get_all_kategorien();
$simpbook_kategorien_map = [];
foreach ($simpbook_alle_kategorien as $simpbook_kat) {
    $simpbook_kategorien_map[$simpbook_kat->id] = $simpbook_kat->name;
}

// Buchungsoptionen je Dienstleistung laden (wenn Funktion aktiv)
$simpbook_bo_aktiv_neu = get_option('simpbook_buchungsoptionen_aktiv', '0') === '1';
$simpbook_service_buchungsoptionen_neu = [];
if ($simpbook_bo_aktiv_neu) {
    global $wpdb;
    $simpbook_dl_bo_table_neu = $wpdb->prefix . 'simpbook_dienstleistung_buchungsoptionen';
    $simpbook_bo_table_neu    = $wpdb->prefix . 'simpbook_buchungsoptionen';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $simpbook_bo_opts = $wpdb->get_results(
        "SELECT dbo.dienstleistung_id, dbo.buchungsoption_id, dbo.preis, bo.name, bo.dauer_minuten
         FROM {$simpbook_dl_bo_table_neu} dbo
         JOIN {$simpbook_bo_table_neu} bo ON dbo.buchungsoption_id = bo.id
         ORDER BY dbo.sortierung ASC, bo.name ASC"
    );
    foreach ($simpbook_bo_opts as $simpbook_bo_opt) {
        $simpbook_service_buchungsoptionen_neu[(int)$simpbook_bo_opt->dienstleistung_id][] = [
            'buchungsoption_id' => (int)$simpbook_bo_opt->buchungsoption_id,
            'name'              => $simpbook_bo_opt->name,
            'preis'             => $simpbook_bo_opt->preis,
            'dauer_minuten'     => (int)$simpbook_bo_opt->dauer_minuten,
        ];
    }
}

// Standardwerte falls keine Zeiten gesetzt sind
$simpbook_standard_beginn = '11:00';
$simpbook_standard_ende = '22:00';

// Wochentage übersetzbar definieren
$simpbook_wochentage = [
    'montag' => __('Monday', 'simple-appointment-booking'),
    'dienstag' => __('Tuesday', 'simple-appointment-booking'),
    'mittwoch' => __('Wednesday', 'simple-appointment-booking'),
    'donnerstag' => __('Thursday', 'simple-appointment-booking'),
    'freitag' => __('Friday', 'simple-appointment-booking'),
    'samstag' => __('Saturday', 'simple-appointment-booking'),
    'sonntag' => __('Sunday', 'simple-appointment-booking')
];

// Inaktive Wochentage finden
$simpbook_deaktivierte_wochentage = [];
foreach ($simpbook_wochentag_zeiten as $simpbook_tag_key => $simpbook_tag_settings) {
    if ($simpbook_tag_settings['aktiv'] !== '1') {
        $simpbook_deaktivierte_wochentage[] = $simpbook_tag_key;
    }
}

// Ausgeschlossene Tage in Array umwandeln
$simpbook_ausgeschlossene_tage_array = array();
$simpbook_ausgeschlossene_tage_formatiert = array();
if (!empty($simpbook_ausgeschlossene_tage)) {
    $simpbook_ausgeschlossene_tage_array = explode("\n", str_replace("\r", "", $simpbook_ausgeschlossene_tage));
    $simpbook_ausgeschlossene_tage_array = array_map('trim', $simpbook_ausgeschlossene_tage_array);
    $simpbook_ausgeschlossene_tage_array = array_filter($simpbook_ausgeschlossene_tage_array);

    // Daten formatieren für die Anzeige
    foreach ($simpbook_ausgeschlossene_tage_array as $simpbook_datum_raw) {
        $simpbook_datum_obj = DateTime::createFromFormat('Y-m-d', $simpbook_datum_raw);
        if ($simpbook_datum_obj !== false) {
            $simpbook_ausgeschlossene_tage_formatiert[] = date_i18n(get_option('date_format'), $simpbook_datum_obj->getTimestamp());
        } else {
            // Fallback: Wenn Format nicht passt, Original verwenden
            $simpbook_ausgeschlossene_tage_formatiert[] = $simpbook_datum_raw;
        }
    }
}

/**
 * Sendet eine Bestätigungsmail an den Gast
 *
 * @param array $daten Reservierungsdaten
 * @return bool True bei erfolgreicher E-Mail-Zustellung, ansonsten False
 */
function simpbook_sende_reservierungsbestaetigung($daten) {
    $name = $daten['name'];
    $email = $daten['simpbook_email'];
    $datum_obj = new DateTime($daten['simpbook_datum']);
    $datum = $datum_obj->format('d.m.Y');
    $uhrzeit = $daten['uhrzeit'];
    // E-Mail-Inhalt erstellen (wird nicht mehr verwendet, da E-Mail-Templates verwendet werden)
    $gast_betreff = 'Ihre Buchung wurde bestätigt';
    $gast_nachricht = "Sehr geehrte(r) $name,\n\n";
    $gast_nachricht .= "vielen Dank für Ihre Buchung.\n";
    $gast_nachricht .= "Wir freuen uns Sie am folgenden Tag bei uns begrüssen zu dürfen:\n\n";
    $gast_nachricht .= "Datum: $datum\n";
    $gast_nachricht .= "Uhrzeit: $uhrzeit\n";

    // Absender-Einstellungen
    $firmen_name = get_option('simpbook_firmen_name', get_bloginfo('name'));
    $headers = array(
        'Content-Type: text/plain; charset=UTF-8',
        'From: ' . $firmen_name . ' <' . get_option('admin_email') . '>'
    );

    // E-Mail senden
    return wp_mail($email, $gast_betreff, $gast_nachricht, $headers);
}

// Formular abgeschickt
if (isset($_POST['simpbook_reservierung_neu_submit'])) {
    // Nonce überprüfen
    check_admin_referer('simpbook_reservierung_neu');

    // Daten validieren und sanitizen
    $simpbook_name_val = isset($_POST['simpbook_name']) ? sanitize_text_field(wp_unslash($_POST['simpbook_name'])) : '';
    $simpbook_email_val = isset($_POST['simpbook_email']) ? sanitize_email(wp_unslash($_POST['simpbook_email'])) : '';
    $simpbook_telefon_val = isset($_POST['simpbook_telefon']) ? sanitize_text_field(wp_unslash($_POST['simpbook_telefon'])) : '';
    $simpbook_uhrzeit_val_raw = isset($_POST['simpbook_uhrzeit']) ? sanitize_text_field(wp_unslash($_POST['simpbook_uhrzeit'])) : '';
    // Konvertiere Zeit von 12h-Format (falls vorhanden) zu 24h-Format für DB
    $simpbook_uhrzeit_val = simpbook_parse_time_12h($simpbook_uhrzeit_val_raw);
    $simpbook_dienstleistung_id_val = isset($_POST['simpbook_dienstleistung_id']) ? intval($_POST['simpbook_dienstleistung_id']) : 0;
    $simpbook_mitarbeiter_id_val = isset($_POST['simpbook_mitarbeiter_id']) ? intval($_POST['simpbook_mitarbeiter_id']) : 0; // Optional
    $simpbook_buchungsoption_id_val = isset($_POST['simpbook_buchungsoption_id']) ? intval($_POST['simpbook_buchungsoption_id']) : 0;
    $simpbook_nachricht_val = isset($_POST['simpbook_nachricht']) ? sanitize_textarea_field(wp_unslash($_POST['simpbook_nachricht'])) : '';
    $simpbook_status_val = isset($_POST['simpbook_status']) && in_array(sanitize_text_field(wp_unslash($_POST['simpbook_status'])), ['AUSSTEHEND', 'BESTÄTIGT', 'ABGELEHNT'], true)
                   ? sanitize_text_field(wp_unslash($_POST['simpbook_status']))
                   : 'AUSSTEHEND';
    $simpbook_email_senden_val = isset($_POST['simpbook_send_confirmation_email']) && sanitize_text_field(wp_unslash($_POST['simpbook_send_confirmation_email'])) === '1';

    // Validierung
    if ($simpbook_dienstleistung_id_val <= 0) {
        echo '<div class="notice notice-error"><p>' . esc_html__('Please select a service first.', 'simple-appointment-booking') . '</p></div>';
        $simpbook_dienstleistung_id_val = 0;
    }

    // Datum aus dem Datepicker-Format (dd.mm.yyyy) in YYYY-MM-DD für die Datenbank umwandeln
    $simpbook_datum_eingabe_raw = isset($_POST['simpbook_datum']) ? sanitize_text_field(wp_unslash($_POST['simpbook_datum'])) : '';
    $simpbook_datum_mysql_format_val = '';

    if (!empty($simpbook_datum_eingabe_raw)) {
        // Der Datepicker ist auf 'dd.mm.yy' (europäisch) oder 'mm/dd/yy' (US) konfiguriert
        // Versuche verschiedene Formate
        $simpbook_current_lang = simpbook_get_current_language();
        $simpbook_dt_obj = DateTime::createFromFormat('d.m.Y', $simpbook_datum_eingabe_raw); // dd.mm.yyyy
        if ($simpbook_dt_obj === false) {
            $simpbook_dt_obj = DateTime::createFromFormat('d.m.y', $simpbook_datum_eingabe_raw); // dd.mm.yy
        }
        // US-Format: mm/dd/yyyy oder mm/dd/yy
        if ($simpbook_dt_obj === false && $simpbook_current_lang === 'en_US_AMPM') {
            $simpbook_dt_obj = DateTime::createFromFormat('m/d/Y', $simpbook_datum_eingabe_raw); // mm/dd/yyyy
        }
        if ($simpbook_dt_obj === false && $simpbook_current_lang === 'en_US_AMPM') {
            $simpbook_dt_obj = DateTime::createFromFormat('m/d/y', $simpbook_datum_eingabe_raw); // mm/dd/yy
        }
        if ($simpbook_dt_obj === false) {
            // Fallback: Alte Formate mit Bindestrichen
            $simpbook_dt_obj = DateTime::createFromFormat('d-m-y', $simpbook_datum_eingabe_raw);
        }
        if ($simpbook_dt_obj === false) {
            $simpbook_dt_obj = DateTime::createFromFormat('d-m-Y', $simpbook_datum_eingabe_raw);
        }
        if ($simpbook_dt_obj !== false) {
            $simpbook_datum_mysql_format_val = $simpbook_dt_obj->format('Y-m-d');
        } else {
            echo '<div class="notice notice-error"><p>' . sprintf(
                // translators: %s: Invalid date string that was received
                esc_html__('Invalid date format received: %s. Please check your input.', 'simple-appointment-booking'),
                esc_html($simpbook_datum_eingabe_raw)
            ) . '</p></div>';
            $simpbook_datum_mysql_format_val = current_time('Y-m-d'); // Fallback
        }
    } else {
        // Wenn kein Datum übergeben wurde, Fallback auf aktuelles Datum
        $simpbook_datum_mysql_format_val = current_time('Y-m-d');
        echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html__('No date specified, current date was used.', 'simple-appointment-booking') . '</p></div>';
    }

    // Stornierungs-Token generieren
    $simpbook_stornierungs_token = simpbook_generiere_stornierungs_token();

    $simpbook_daten = [
        'name' => $simpbook_name_val,
        'email' => $simpbook_email_val,
        'telefon' => $simpbook_telefon_val,
        'datum' => $simpbook_datum_mysql_format_val,
        'uhrzeit' => $simpbook_uhrzeit_val,
        'dienstleistung_id' => $simpbook_dienstleistung_id_val,
        'mitarbeiter_id' => $simpbook_mitarbeiter_id_val > 0 ? $simpbook_mitarbeiter_id_val : null,
        'buchungsoption_id' => $simpbook_buchungsoption_id_val > 0 ? $simpbook_buchungsoption_id_val : null,
        'nachricht' => $simpbook_nachricht_val,
        'status' => $simpbook_status_val,
        'storniert' => 0,
        'stornierungs_token' => $simpbook_stornierungs_token,
        'erinnerung_gesendet' => 0
    ];

    // Custom fields aus dem Formular-Builder sammeln
    $simpbook_nr_fc = SimpBook_DB_Reservierungen::simpbook_get_form_fields_config();
    $simpbook_nr_cf_data = array();
    if (!empty($simpbook_nr_fc['fields'])) {
        foreach ($simpbook_nr_fc['fields'] as $simpbook_nr_cf) {
            if (empty($simpbook_nr_cf['removable'])) { continue; }
            $simpbook_nr_cf_key = isset($simpbook_nr_cf['key']) ? sanitize_key($simpbook_nr_cf['key']) : '';
            if (empty($simpbook_nr_cf_key)) { continue; }
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked above
            $simpbook_nr_cf_data[$simpbook_nr_cf_key] = isset($_POST[$simpbook_nr_cf_key]) ? sanitize_text_field(wp_unslash($_POST[$simpbook_nr_cf_key])) : '';
        }
    }
    if (!empty($simpbook_nr_cf_data)) {
        $simpbook_daten['custom_fields'] = wp_json_encode($simpbook_nr_cf_data);
    }

    // In die Datenbank einfügen
    global $wpdb;
    $simpbook_erfolg = false;
    if (!empty($simpbook_daten['datum'])) {
        // Build format array dynamically
        $simpbook_nr_format = array('%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%d');
        if (isset($simpbook_daten['custom_fields'])) {
            $simpbook_nr_format[] = '%s';
        }
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Plugin-specific table
        $simpbook_erfolg = $wpdb->insert(
            $wpdb->prefix . 'buchungen',
            $simpbook_daten,
            $simpbook_nr_format
        );
    }

    // Rückmeldung an den Benutzer
    if ($simpbook_erfolg) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Reservation successfully created.', 'simple-appointment-booking') . '</p></div>';

        if ($simpbook_daten['status'] === 'BESTÄTIGT' && $simpbook_email_senden_val) {
            // Verwende die Hauptfunktion aus simple-appointment-booking.php
            $simpbook_reservierung_id = $wpdb->insert_id;
            if ($simpbook_reservierung_id) {
                // Suche nach der Plugin-Instanz über globale Variable
                global $simpbook_db_reservierungen_instance;
                if (!isset($simpbook_db_reservierungen_instance)) {
                    $simpbook_db_reservierungen_instance = new simpbook_DB_Reservierungen();
                }
                // Verwende die Funktion für Statusänderung (sie sendet automatisch E-Mail bei BESTÄTIGT)
                $simpbook_email_gesendet = $simpbook_db_reservierungen_instance->simpbook_benachrichtige_gast_ueber_statusaenderung($simpbook_reservierung_id, 'BESTÄTIGT');
            } else {
                $simpbook_email_gesendet = false;
            }

            if ($simpbook_email_gesendet) {
                echo '<div class="notice notice-success is-dismissible"><p>' . sprintf(
                    // translators: %s: Email address
                    esc_html__('Confirmation email has been sent to %s.', 'simple-appointment-booking'),
                    esc_html($simpbook_daten['email'])
                ) . '</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>' . esc_html__('Error sending confirmation email.', 'simple-appointment-booking') . '</p></div>';
            }
        } elseif ($simpbook_daten['status'] === 'BESTÄTIGT' && !$simpbook_email_senden_val) {
             echo '<div class="notice notice-info is-dismissible"><p>' . esc_html__('Reservation saved as "Confirmed" but no email sent (option not selected).', 'simple-appointment-booking') . '</p></div>';
        }

        // Formular zurücksetzen
        unset($_POST);
    } else {
        if (empty($simpbook_daten['datum'])) {
             echo '<div class="notice notice-error"><p>' . esc_html__('Error creating reservation: Date could not be processed.', 'simple-appointment-booking') . '</p></div>';
        } else {
             echo '<div class="notice notice-error"><p>' . sprintf(
                 // translators: %s: Database error message
                 esc_html__('Error creating reservation: %s', 'simple-appointment-booking'),
                 esc_html($wpdb->last_error)
             ) . '</p></div>';
        }
    }
}
?>

<div class="wrap simpbook-admin-wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e('Create New Booking', 'simple-appointment-booking'); ?></h1>
    <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen'))); ?>" class="page-title-action"><?php esc_html_e('Back to List', 'simple-appointment-booking'); ?></a>

    <hr class="wp-header-end">

    <form method="post" action="<?php echo esc_attr(simpbook_get_form_action()); ?>">
        <?php wp_nonce_field('simpbook_reservierung_neu'); ?>

        <table class="form-table simpbook-neue-reservierung-form-table">
            <tr>
                <th scope="row"><label for="simpbook_name"><?php esc_html_e('Name *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <input name="simpbook_name" id="simpbook_name" type="text"
                           value="<?php echo esc_attr(isset($_POST['simpbook_name']) ? sanitize_text_field(wp_unslash($_POST['simpbook_name'])) : ''); ?>"
                           class="regular-text" required>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_email"><?php esc_html_e('Email *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <input name="simpbook_email" id="simpbook_email" type="email"
                           value="<?php echo esc_attr(isset($_POST['simpbook_email']) ? sanitize_email(wp_unslash($_POST['simpbook_email'])) : ''); ?>"
                           class="regular-text" required>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_telefon"><?php esc_html_e('Phone *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <input name="simpbook_telefon" id="simpbook_telefon" type="text"
                           value="<?php echo esc_attr(isset($_POST['simpbook_telefon']) ? sanitize_text_field(wp_unslash($_POST['simpbook_telefon'])) : ''); ?>"
                           class="regular-text" required>
                </td>
            </tr>
            <?php
            // Custom fields aus dem Formular-Builder anzeigen
            $simpbook_admin_nr_form_config = SimpBook_DB_Reservierungen::simpbook_get_form_fields_config();
            if (!empty($simpbook_admin_nr_form_config['fields'])) :
                $simpbook_admin_nr_allowed_types = array('text', 'textarea', 'tel', 'email', 'date', 'number', 'select', 'checkbox', 'url');
                foreach ($simpbook_admin_nr_form_config['fields'] as $simpbook_admin_nr_field) :
                    if (empty($simpbook_admin_nr_field['removable'])) { continue; } // Systemfelder überspringen
                    $simpbook_nr_key   = isset($simpbook_admin_nr_field['key']) ? sanitize_key($simpbook_admin_nr_field['key']) : '';
                    $simpbook_nr_type  = isset($simpbook_admin_nr_field['type']) && in_array($simpbook_admin_nr_field['type'], $simpbook_admin_nr_allowed_types, true) ? $simpbook_admin_nr_field['type'] : 'text';
                    $simpbook_nr_label = isset($simpbook_admin_nr_field['placeholder']) && $simpbook_admin_nr_field['placeholder'] !== '' ? $simpbook_admin_nr_field['placeholder'] : $simpbook_nr_key;
                    $simpbook_nr_req   = !empty($simpbook_admin_nr_field['required']);
                    if (empty($simpbook_nr_key)) { continue; }
                    // POST-Wert für erneute Anzeige nach Validierungsfehler
                    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked in handle form submit
                    $simpbook_nr_post_val = isset($_POST[$simpbook_nr_key]) ? sanitize_text_field(wp_unslash($_POST[$simpbook_nr_key])) : '';
                    ?>
                    <tr>
                        <th scope="row">
                            <label for="cf-<?php echo esc_attr($simpbook_nr_key); ?>">
                                <?php echo esc_html($simpbook_nr_label); ?><?php if ($simpbook_nr_req) { echo ' *'; } ?>
                            </label>
                        </th>
                        <td>
                            <?php if ($simpbook_nr_type === 'date') : ?>
                                <input type="text" name="<?php echo esc_attr($simpbook_nr_key); ?>" id="cf-<?php echo esc_attr($simpbook_nr_key); ?>"
                                       value="<?php echo esc_attr($simpbook_nr_post_val); ?>" class="regular-text simpbook-cf-datepicker" autocomplete="off" readonly<?php echo $simpbook_nr_req ? ' required' : ''; ?>>
                            <?php elseif ($simpbook_nr_type === 'textarea') : ?>
                                <textarea name="<?php echo esc_attr($simpbook_nr_key); ?>" id="cf-<?php echo esc_attr($simpbook_nr_key); ?>" rows="4" class="large-text"<?php echo $simpbook_nr_req ? ' required' : ''; ?>><?php echo esc_textarea($simpbook_nr_post_val); ?></textarea>
                            <?php elseif ($simpbook_nr_type === 'select' && !empty($simpbook_admin_nr_field['options'])) : ?>
                                <select name="<?php echo esc_attr($simpbook_nr_key); ?>" id="cf-<?php echo esc_attr($simpbook_nr_key); ?>"<?php echo $simpbook_nr_req ? ' required' : ''; ?>>
                                    <option value=""><?php echo esc_html($simpbook_nr_label); ?></option>
                                    <?php foreach (array_filter(array_map('trim', explode(',', $simpbook_admin_nr_field['options']))) as $simpbook_nr_opt) : ?>
                                        <option value="<?php echo esc_attr($simpbook_nr_opt); ?>"<?php selected($simpbook_nr_post_val, $simpbook_nr_opt); ?>><?php echo esc_html($simpbook_nr_opt); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            <?php elseif ($simpbook_nr_type === 'checkbox') : ?>
                                <label>
                                    <input type="checkbox" name="<?php echo esc_attr($simpbook_nr_key); ?>" id="cf-<?php echo esc_attr($simpbook_nr_key); ?>" value="1"<?php checked($simpbook_nr_post_val, '1'); ?><?php echo $simpbook_nr_req ? ' required' : ''; ?>>
                                    <?php echo esc_html($simpbook_nr_label); ?>
                                </label>
                            <?php else : ?>
                                <input type="<?php echo esc_attr($simpbook_nr_type); ?>" name="<?php echo esc_attr($simpbook_nr_key); ?>" id="cf-<?php echo esc_attr($simpbook_nr_key); ?>"
                                       value="<?php echo esc_attr($simpbook_nr_post_val); ?>" class="regular-text"<?php echo $simpbook_nr_req ? ' required' : ''; ?>>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php
                endforeach;
            endif;
            ?>
            <tr>
                <th scope="row"><label for="simpbook_dienstleistung_id"><?php esc_html_e('Service *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_dienstleistung_id" id="simpbook_dienstleistung_id" required>
                        <option value="">-- <?php esc_html_e('Select Service', 'simple-appointment-booking'); ?> --</option>
                        <?php
                        $simpbook_selected_dienstleistung = isset($_POST['simpbook_dienstleistung_id']) ? intval($_POST['simpbook_dienstleistung_id']) : 0;
                        foreach ($simpbook_alle_dienstleistungen as $simpbook_dl) {
                            // Kategorie-Name aus dem JOIN verwenden
                            $simpbook_kategorie_name = $simpbook_dl->kategorie_name ?? '';
                            
                            // Option-Text zusammensetzen
                            // Minuten nur anzeigen wenn dieser Service keine Buchungsoptionen hat
                            $simpbook_dl_hat_optionen = !empty($simpbook_service_buchungsoptionen_neu[(int)$simpbook_dl->id]);
                            if ($simpbook_dl_hat_optionen) {
                                $simpbook_option_text = $simpbook_dl->name;
                            } else {
                                $simpbook_option_text = $simpbook_dl->name . ' (' . $simpbook_dl->dauer_minuten . ' Min.)';
                            }
                            if (!empty($simpbook_kategorie_name)) {
                                $simpbook_option_text .= ' - ' . $simpbook_kategorie_name;
                            } else {
                                $simpbook_option_text .= ' - ' . __('No Category', 'simple-appointment-booking');
                            }
                            
                            $simpbook_dl_buchungsoptionen_json = wp_json_encode($simpbook_service_buchungsoptionen_neu[(int)$simpbook_dl->id] ?? []);
                            echo '<option value="' . esc_attr($simpbook_dl->id) . '"'
                                . ' data-ohne-mitarbeiter="' . esc_attr($simpbook_dl->ohne_mitarbeiter) . '"'
                                . ' data-buchungsoptionen="' . esc_attr($simpbook_dl_buchungsoptionen_json) . '"'
                                . selected($simpbook_selected_dienstleistung, $simpbook_dl->id, false) . '>'
                                . esc_html($simpbook_option_text) . '</option>';
                        }
                        ?>
                    </select>
                    <p class="description"><?php esc_html_e('Please select a service first.', 'simple-appointment-booking'); ?></p>
                </td>
            </tr>
            <?php if ($simpbook_bo_aktiv_neu) : ?>
            <tr id="simpbook_buchungsoption_row" style="display:none;">
                <th scope="row"><label for="simpbook_buchungsoption_id"><?php esc_html_e('Booking Option', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_buchungsoption_id" id="simpbook_buchungsoption_id">
                        <option value="">-- <?php esc_html_e('Choose Booking Option', 'simple-appointment-booking'); ?> --</option>
                    </select>
                </td>
            </tr>
            <?php endif; ?>
            <tr>
                <th scope="row"><label for="simpbook_datum"><?php esc_html_e('Date *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <?php
                    // Determine initial date value based on language
                    $simpbook_initial_date_value = current_time('d.m.Y');
                    if (simpbook_get_current_language() === 'en_US_AMPM') {
                        $simpbook_initial_date_value = current_time('m/d/Y');
                    }
                    ?>
                    <input name="simpbook_datum" id="simpbook_datum" type="text" class="datepicker"
                           value="<?php echo esc_attr(isset($_POST['simpbook_datum']) ? sanitize_text_field(wp_unslash($_POST['simpbook_datum'])) : $simpbook_initial_date_value); ?>"
                           required autocomplete="off">
                    <p class="description" id="available-days-info" style="display:none;"></p>
                </td>
            </tr>
            <tr id="simpbook_mitarbeiter_row">
                <th scope="row"><label for="simpbook_mitarbeiter_id"><?php esc_html_e('Staff', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_mitarbeiter_id" id="simpbook_mitarbeiter_id">
                        <option value="0">-- <?php esc_html_e('No Specific Staff Member', 'simple-appointment-booking'); ?> --</option>
                        <option value="" disabled>-- <?php esc_html_e('Please select date and service', 'simple-appointment-booking'); ?> --</option>
                    </select>
                    <p class="description"><?php esc_html_e('Optional: Select a specific staff member. Leave the field empty to automatically assign the first available staff member.', 'simple-appointment-booking'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_uhrzeit"><?php esc_html_e('Time *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_uhrzeit" id="simpbook_uhrzeit" required>
                        <option value="">-- <?php esc_html_e('Select time', 'simple-appointment-booking'); ?> --</option>
                    </select>
                    <p class="description"><?php esc_html_e('Please select date and service first.', 'simple-appointment-booking'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_nachricht"><?php esc_html_e('Message', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <textarea name="simpbook_nachricht" id="simpbook_nachricht" rows="5" cols="50"><?php
                        echo esc_textarea(isset($_POST['simpbook_nachricht']) ? sanitize_textarea_field(wp_unslash($_POST['simpbook_nachricht'])) : '');
                    ?></textarea>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_status"><?php esc_html_e('Status', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_status" id="simpbook_status">
                        <?php $simpbook_status_value = isset($_POST['simpbook_status']) ? sanitize_text_field(wp_unslash($_POST['simpbook_status'])) : ''; ?>
                        <option value="AUSSTEHEND" <?php selected($simpbook_status_value, 'AUSSTEHEND'); ?>><?php esc_html_e('Pending', 'simple-appointment-booking'); ?></option>
                        <option value="BESTÄTIGT" <?php selected($simpbook_status_value, 'BESTÄTIGT'); ?>><?php esc_html_e('Confirmed', 'simple-appointment-booking'); ?></option>
                        <option value="ABGELEHNT" <?php selected($simpbook_status_value, 'ABGELEHNT'); ?>><?php esc_html_e('Rejected', 'simple-appointment-booking'); ?></option>
                    </select>
                </td>
            </tr>
            <tr id="send_email_row"> <th scope="row"><label for="simpbook_send_confirmation_email"><?php esc_html_e('Send confirmation email to guest?', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <input type="checkbox" name="simpbook_send_confirmation_email" id="simpbook_send_confirmation_email" value="1" <?php checked(true); ?>>
                    <span class="description"><?php esc_html_e('Only relevant if status is "Confirmed".', 'simple-appointment-booking'); ?></span>
                </td>
            </tr>
        </table>

        <input type="submit" name="simpbook_reservierung_neu_submit" class="button button-primary" value="<?php esc_attr_e('Create Reservation', 'simple-appointment-booking'); ?>">
    </form>
</div>







