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

// Testphase-Hinweis anzeigen
if (function_exists('simpbook_display_trial_notice_on_admin_pages')) {
    simpbook_display_trial_notice_on_admin_pages();
}

// Heutige Buchungen abrufen
$simpbook_heutige_reservierungen = [];
$simpbook_heutige_anzahl = 0;
$simpbook_dashboard_error = false;

if (!isset($this)) {
    $simpbook_dashboard_error = true;

} elseif (!method_exists($this, 'simpbook_alle_reservierungen_holen') || !method_exists($this, 'simpbook_reservierungen_zaehlen')) {
    $simpbook_dashboard_error = true;

}

if (!$simpbook_dashboard_error) {
    try {
        global $wpdb;
        $simpbook_heute_datum = current_time('Y-m-d');
        $simpbook_heute_filter = $wpdb->prepare("datum = %s", $simpbook_heute_datum);
        $simpbook_heutige_reservierungen = $this->simpbook_alle_reservierungen_holen(PHP_INT_MAX, 0, 'uhrzeit', 'ASC', $simpbook_heute_filter);
        if (!is_array($simpbook_heutige_reservierungen)) {
            $simpbook_heutige_reservierungen = [];
        }
    } catch (Exception $e) {

        $simpbook_heutige_reservierungen = [];
        $simpbook_heutige_anzahl = 0;
    } catch (Error $e) {

        $simpbook_heutige_reservierungen = [];
        $simpbook_heutige_anzahl = 0;
    }
}

// Status-Aufteilung für heute
$simpbook_heute_ausstehend = 0;
$simpbook_heute_bestaetigt = 0;
$simpbook_heute_abgelehnt = 0;
$simpbook_heutige_buchungen_liste = []; // Array für alle heutigen Buchungen

foreach ($simpbook_heutige_reservierungen as $simpbook_res) {
    if ($simpbook_res->status === 'AUSSTEHEND') {
        $simpbook_heute_ausstehend++;
    } elseif ($simpbook_res->status === 'BESTÄTIGT') {
        $simpbook_heute_bestaetigt++;
        // Sammle alle heutigen bestätigten Buchungen
        $simpbook_heutige_buchungen_liste[] = $simpbook_res;
    } elseif ($simpbook_res->status === 'ABGELEHNT' || $simpbook_res->status === 'STORNIERT') {
        $simpbook_heute_abgelehnt++;
    }
}

// Gesamtanzahl heute ohne Abgelehnte/Stornierte
$simpbook_heutige_anzahl = $simpbook_heute_ausstehend + $simpbook_heute_bestaetigt;

// Sortiere heutige Buchungen nach Uhrzeit
usort($simpbook_heutige_buchungen_liste, function($a, $b) {
    return strtotime($a->uhrzeit) - strtotime($b->uhrzeit);
});

// Diese Woche: Montag bis Sonntag der aktuellen Woche
$simpbook_now = current_time('timestamp');
$simpbook_woche_start = strtotime('monday this week', $simpbook_now);
$simpbook_woche_ende = strtotime('sunday this week 23:59:59', $simpbook_now);
$simpbook_woche_start_sql = wp_date('Y-m-d', $simpbook_woche_start);
$simpbook_woche_ende_sql = wp_date('Y-m-d', $simpbook_woche_ende);

$simpbook_woche_reservierungen = [];
$simpbook_woche_anzahl = 0;
if (!$simpbook_dashboard_error) {
    try {
        global $wpdb;
        $simpbook_woche_filter = $wpdb->prepare("datum >= %s AND datum <= %s", $simpbook_woche_start_sql, $simpbook_woche_ende_sql);
        $simpbook_woche_reservierungen = $this->simpbook_alle_reservierungen_holen(PHP_INT_MAX, 0, 'datum', 'ASC', $simpbook_woche_filter);
        if (!is_array($simpbook_woche_reservierungen)) {
            $simpbook_woche_reservierungen = [];
        }
        $simpbook_woche_anzahl = 0; // Wird in der foreach-Schleife berechnet (ohne Abgelehnte/Stornierte)
    } catch (Exception $e) {

        $simpbook_woche_reservierungen = [];
        $simpbook_woche_anzahl = 0;
    } catch (Error $e) {

        $simpbook_woche_reservierungen = [];
        $simpbook_woche_anzahl = 0;
    }
}

// Helper-Funktion zum Parsen von Preisen (DE/US Formate)
function simpbook_parse_price_string($price_string) {
    if (empty($price_string)) {
        return 0.0;
    }
    
    // Entferne alle Nicht-Ziffern außer Punkt, Komma und Minus
    $cleaned = preg_replace('/[^\d.,\-]/', '', $price_string);
    
    if (empty($cleaned)) {
        return 0.0;
    }
    
    // Bestimme das Dezimaltrennzeichen
    $last_comma = strrpos($cleaned, ',');
    $last_dot = strrpos($cleaned, '.');
    
    if ($last_comma !== false && $last_dot !== false) {
        // Beide vorhanden - das letzte ist das Dezimaltrennzeichen
        if ($last_comma > $last_dot) {
            // DE Format: 1.234,56
            $cleaned = str_replace('.', '', $cleaned);
            $cleaned = str_replace(',', '.', $cleaned);
        } else {
            // US Format: 1,234.56
            $cleaned = str_replace(',', '', $cleaned);
        }
    } elseif ($last_comma !== false) {
        // Nur Komma - DE Dezimaltrennzeichen
        $cleaned = str_replace(',', '.', $cleaned);
    }
    // Nur Punkt oder nichts - bereits im richtigen Format
    
    return (float) $cleaned;
}

// Helper: Preis einer Reservierung ermitteln (Buchungsoption hat Vorrang vor Dienstleistungspreis)
function simpbook_get_reservierung_preis($res) {
    global $wpdb;
    if (!empty($res->buchungsoption_id) && $res->buchungsoption_id > 0 && !empty($res->dienstleistung_id)) {
        $dl_bo_table = $wpdb->prefix . 'simpbook_dienstleistung_buchungsoptionen';
        $bo_preis = $wpdb->get_var($wpdb->prepare(
            "SELECT preis FROM {$dl_bo_table} WHERE dienstleistung_id = %d AND buchungsoption_id = %d LIMIT 1",
            $res->dienstleistung_id,
            $res->buchungsoption_id
        ));
        if (!is_null($bo_preis) && $bo_preis !== '') {
            return simpbook_parse_price_string($bo_preis);
        }
    }
    if (!empty($res->dienstleistung_id) && $res->dienstleistung_id > 0) {
        $simpbook_dienstleistung = simpbook_get_dienstleistung($res->dienstleistung_id);
        if ($simpbook_dienstleistung && !empty($simpbook_dienstleistung->preis)) {
            return simpbook_parse_price_string($simpbook_dienstleistung->preis);
        }
    }
    return 0.0;
}

// Berechne geschätzten Umsatz für heutige Buchungen (ohne Abgelehnte/Stornierte)
$simpbook_heute_umsatz = 0.0;
foreach ($simpbook_heutige_reservierungen as $simpbook_res) {
    if (in_array($simpbook_res->status, ['ABGELEHNT', 'STORNIERT'], true)) {
        continue;
    }
    $simpbook_heute_umsatz += simpbook_get_reservierung_preis($simpbook_res);
}

// Woche nach Tagen aufteilen
$simpbook_woche_nach_tagen = [];
$simpbook_woche_status = ['AUSSTEHEND' => 0, 'BESTÄTIGT' => 0, 'ABGELEHNT' => 0, 'STORNIERT' => 0];
$simpbook_woche_umsatz = 0.0;

foreach ($simpbook_woche_reservierungen as $simpbook_res) {
    $simpbook_tag_key = $simpbook_res->datum;
    if (!isset($simpbook_woche_nach_tagen[$simpbook_tag_key])) {
        $simpbook_woche_nach_tagen[$simpbook_tag_key] = 0;
    }

    if (isset($simpbook_woche_status[$simpbook_res->status])) {
        $simpbook_woche_status[$simpbook_res->status]++;
    }

    // Nur aktive Buchungen zählen (ohne Abgelehnte/Stornierte)
    if (!in_array($simpbook_res->status, ['ABGELEHNT', 'STORNIERT'], true)) {
        $simpbook_woche_nach_tagen[$simpbook_tag_key]++;
        $simpbook_woche_anzahl++;
        $simpbook_woche_umsatz += simpbook_get_reservierung_preis($simpbook_res);
    }
}

// Buchungen dieses Jahr berechnen
$simpbook_jahr_start = wp_date('Y') . '-01-01';
$simpbook_jahr_ende = wp_date('Y') . '-12-31';
$simpbook_jahr_reservierungen = [];
$simpbook_jahr_anzahl = 0;
$simpbook_jahr_umsatz = 0.0;

if (!$simpbook_dashboard_error) {
    try {
        global $wpdb;
        $simpbook_jahr_filter = $wpdb->prepare("datum >= %s AND datum <= %s", $simpbook_jahr_start, $simpbook_jahr_ende);
        $simpbook_jahr_reservierungen = $this->simpbook_alle_reservierungen_holen(PHP_INT_MAX, 0, 'datum', 'ASC', $simpbook_jahr_filter);
        if (!is_array($simpbook_jahr_reservierungen)) {
            $simpbook_jahr_reservierungen = [];
        }
        // Umsatz und Anzahl für Jahr berechnen (ohne Abgelehnte/Stornierte)
        foreach ($simpbook_jahr_reservierungen as $simpbook_res) {
            if (in_array($simpbook_res->status, ['ABGELEHNT', 'STORNIERT'], true)) {
                continue;
            }
            $simpbook_jahr_anzahl++;
            $simpbook_jahr_umsatz += simpbook_get_reservierung_preis($simpbook_res);
        }
    } catch (Exception $e) {
        $simpbook_jahr_reservierungen = [];
        $simpbook_jahr_anzahl = 0;
        $simpbook_jahr_umsatz = 0.0;
    } catch (Error $e) {
        $simpbook_jahr_reservierungen = [];
        $simpbook_jahr_anzahl = 0;
        $simpbook_jahr_umsatz = 0.0;
    }
}

// Validierung wichtiger Einstellungen
$simpbook_validierung_warnungen = [];
$simpbook_wochentag_zeiten = get_option('simpbook_wochentag_zeiten', []);
$simpbook_hat_oeffnungszeiten = false;
foreach ($simpbook_wochentag_zeiten as $simpbook_tag_settings) {
    if (isset($simpbook_tag_settings['aktiv']) && $simpbook_tag_settings['aktiv'] === '1') {
        $simpbook_hat_oeffnungszeiten = true;
        break;
    }
}
if (!$simpbook_hat_oeffnungszeiten) {
    $simpbook_validierung_warnungen[] = [
        'type' => 'warning',
        'message' => esc_html__('No business hours configured. Please configure at least one weekday.', 'simple-appointment-booking'),
        'link' => simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen-einstellungen&tab=opening-hours')),
        'link_text' => esc_html__('Configure business hours', 'simple-appointment-booking')
    ];
}

$simpbook_benachrichtigungs_email = get_option('simpbook_benachrichtigungs_email', '');
if (empty($simpbook_benachrichtigungs_email)) {
    $simpbook_admin_email = get_option('admin_email');
    if (empty($simpbook_admin_email)) {
        $simpbook_validierung_warnungen[] = [
            'type' => 'error',
            'message' => esc_html__('No email address configured for notifications.', 'simple-appointment-booking'),
            'link' => simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen-einstellungen&tab=general')),
            'link_text' => esc_html__('Configure email address', 'simple-appointment-booking')
        ];
    }
}

// Prüfe ob Sprache konfiguriert ist (nutze die Funktion, die auch automatische Spracherkennung berücksichtigt)
$simpbook_current_language = simpbook_get_current_language();
// Nur warnen wenn manuelle Überschreibung explizit auf leer gesetzt ist
$simpbook_language_override = simpbook_get_option('simpbook_language_override', 'auto');
if ($simpbook_language_override === '' && !get_locale()) {
    $simpbook_validierung_warnungen[] = [
        'type' => 'warning',
        'message' => esc_html__('No language selected. Please select a language for the plugin.', 'simple-appointment-booking'),
        'link' => simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen-einstellungen&tab=language')),
        'link_text' => esc_html__('Select Language', 'simple-appointment-booking')
    ];
}

// Prüfe ob Shortcode bereits auf einer Seite verwendet wird
$simpbook_shortcode_seite_gefunden = false;
$simpbook_pages_with_shortcode = [];
$simpbook_pages = get_pages();
foreach ($simpbook_pages as $simpbook_page) {
    if (has_shortcode($simpbook_page->post_content, 'simpbook_bookingform')) {
        $simpbook_shortcode_seite_gefunden = true;
        $simpbook_pages_with_shortcode[] = $simpbook_page;
    }
}
$simpbook_posts = get_posts(['numberposts' => -1]);
foreach ($simpbook_posts as $simpbook_post) {
    if (has_shortcode($simpbook_post->post_content, 'simpbook_bookingform')) {
        $simpbook_shortcode_seite_gefunden = true;
        $simpbook_pages_with_shortcode[] = $simpbook_post;
    }
}

// Alle Kategorien für kategorie-spezifische Shortcodes laden
$simpbook_alle_kategorien = simpbook_get_all_kategorien();
?>

<div class="wrap simpbook-admin-wrap simpbook-dashboard-page">
    
    <?php
    // PWA-Modus prüfen - App-Install Overlay anzeigen NUR wenn NICHT installiert
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for mode detection only
    $simpbook_is_pwa_mode = isset($_GET['pwa']) && $_GET['pwa'] === '1' && get_option('simpbook_pwa_enabled', '0') === '1';
    
    // ⭐ Overlay NUR rendern wenn PWA nicht bereits installiert ist (verhindert Aufflackern)
    // JavaScript prüft zusätzlich isStandaloneMode() zur Sicherheit
    if ($simpbook_is_pwa_mode) {
        $simpbook_app_name = get_option('simpbook_pwa_app_name', get_bloginfo('name'));
        ?>
        <!-- PWA Install Overlay (Modal) - wird per JS angezeigt wenn NICHT standalone -->
        <div id="simpbook_pwa_install_overlay" class="simpbook-pwa-install-overlay" style="display: none;">
            <div class="simpbook-pwa-install-modal">
                <div style="text-align: center; padding: 40px 30px;">
                    <div style="font-size: 64px; margin-bottom: 40px;">📱</div>
                    <h2 style="margin: 0 0 15px; color: #333; font-weight: 700;">
                        <?php 
                        /* translators: %s: App-Name */
                        printf(esc_html__('Install %s as app', 'simple-appointment-booking'), esc_html($simpbook_app_name)); 
                        ?>
                    </h2>
                    <p style="margin: 0 0 30px; color: #666; font-size: 16px; line-height: 1.6;">
                        <?php esc_html_e('Install the app on your home screen for faster access and push notifications.', 'simple-appointment-booking'); ?>
                    </p>
                    
                    <!-- Install Button -->
                    <div id="simpbook_pwa_install_button_container">
                        <button type="button" id="simpbook_pwa_install_btn_frontend" class="button button-primary button-hero" style="background: linear-gradient(135deg, #1a4a8a 0%, #0e7490 100%) !important; border: none; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3); font-weight: 600; padding: 16px 40px; font-size: 18px; height: auto; border-radius: 8px;">
                            <span class="dashicons dashicons-download" style="font-size: 24px; vertical-align: middle; margin-right: 8px;"></span>
                            <?php esc_html_e('Install now', 'simple-appointment-booking'); ?>
                        </button>
                    </div>
                    
                    <!-- Loading State (wird per JS angezeigt) -->
                    <div id="simpbook_pwa_install_loading" style="display: none;">
                        <div style="font-size: 48px; margin-bottom: 20px;">📲</div>
                        <p style="margin: 0; color: #667eea; font-size: 18px; font-weight: 600;">
                            <?php esc_html_e('Preparing installation...', 'simple-appointment-booking'); ?>
                        </p>
                        <p style="margin: 10px 0 0; color: #999; font-size: 14px;">
                            <?php esc_html_e('Bitte folgen Sie den Anweisungen Ihres Browsers.', 'simple-appointment-booking'); ?>
                        </p>
                    </div>
                    
                    <!-- Success State (wird per JS angezeigt) -->
                    <div id="simpbook_pwa_install_success" style="display: none;">
                        <div style="font-size: 48px; margin-bottom: 20px;">✅</div>
                        <p style="margin: 0 0 25px; color: #46b450; font-size: 18px; font-weight: 600;">
                            <?php esc_html_e('Erfolgreich installiert!', 'simple-appointment-booking'); ?>
                        </p>
                        <button type="button" id="simpbook_pwa_install_close" class="button button-secondary" style="padding: 12px 30px; font-size: 16px; height: auto; border-radius: 8px;">
                            <?php esc_html_e('Close window', 'simple-appointment-booking'); ?>
                        </button>
                    </div>
                    
                    <p id="simpbook_pwa_install_skip_container" style="margin: 20px 0 0; font-size: 13px; color: #999;">
                        <a href="#" id="simpbook_pwa_install_skip" style="color: #999; text-decoration: underline;">
                            <?php esc_html_e('Skip', 'simple-appointment-booking'); ?>
                        </a>
                    </p>
                </div>
            </div>
        </div>
        <?php
    }
    ?>

    <?php 
    // PWA-Modus: Firmen-Logo/Icon anzeigen
    if (simpbook_is_pwa_mode()) :
        $simpbook_pwa_icon = get_option('simpbook_pwa_icon_512', '');
        $simpbook_firmen_name = get_option('simpbook_firmen_name', get_bloginfo('name'));
        if (!empty($simpbook_pwa_icon)) :
    ?>
    <div class="simpbook-pwa-dashboard-header">
        <img src="<?php echo esc_url($simpbook_pwa_icon); ?>" 
             alt="<?php echo esc_attr($simpbook_firmen_name); ?>" 
             class="simpbook-pwa-dashboard-logo">
        <h2 class="simpbook-pwa-welcome"><?php 
            /* translators: %s: Firmenname */
            printf(esc_html__('Willkommen bei %s', 'simple-appointment-booking'), esc_html($simpbook_firmen_name)); 
        ?></h2>
    </div>
    <?php 
        endif;
    endif; 
    ?>
    <h1 class="wp-heading-inline"><?php esc_html_e('Dashboard', 'simple-appointment-booking'); ?></h1>
    <hr class="wp-header-end">

    <?php
    // Erfolgsmeldung nach Wizard-Abschluss
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for display message only
    if (isset($_GET['simpbook_wizard_completed']) && $_GET['simpbook_wizard_completed'] === '1') :
    ?>
        <div class="notice notice-success is-dismissible">
            <p>
                <strong><?php esc_html_e('Setup Complete!', 'simple-appointment-booking'); ?></strong>
                <?php esc_html_e('Your booking system is now set up. Add the shortcode', 'simple-appointment-booking'); ?> <code>[simpbook_bookingform]</code> <?php esc_html_e('on a page to display the form.', 'simple-appointment-booking'); ?>
            </p>
        </div>
    <?php endif; ?>

    <?php
    // Prüfe ob Wizard-Hinweis dismissed wurde
    $simpbook_wizard_dismissed = get_option('simpbook_wizard_notice_dismissed', false);
    $simpbook_wizard_completed = get_transient('simpbook_setup_wizard_completed');
    if (!$simpbook_wizard_dismissed && !$simpbook_wizard_completed) :
    ?>
        <div class="notice notice-info is-dismissible simpbook-wizard-notice">
            <p>
                <strong><?php esc_html_e('Welcome!', 'simple-appointment-booking'); ?></strong>
                <?php esc_html_e('Run the setup wizard to quickly configure your booking system.', 'simple-appointment-booking'); ?>
                <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-dashboard&simpbook_wizard=1'))); ?>" class="button button-primary" style="margin-left: 10px;">
                    <?php esc_html_e('Start Setup Wizard', 'simple-appointment-booking'); ?>
                </a>
            </p>
        </div>
    <?php endif; ?>

    <?php if (!empty($simpbook_validierung_warnungen)) : ?>
        <div class="simpbook-dashboard-warnings">
            <?php foreach ($simpbook_validierung_warnungen as $simpbook_warnung) : ?>
                <div class="notice notice-<?php echo esc_attr($simpbook_warnung['type']); ?> is-dismissible">
                    <p>
                        <strong><?php echo esc_html($simpbook_warnung['message']); ?></strong>
                        <a href="<?php echo esc_url($simpbook_warnung['link']); ?>" class="button button-small" style="margin-left: 10px;">
                            <?php echo esc_html($simpbook_warnung['link_text']); ?>
                        </a>
                    </p>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <!-- Quick Actions -->
    <div class="simpbook-dashboard-quick-actions">
        <h2><?php esc_html_e('Quick Access', 'simple-appointment-booking'); ?></h2>
        <div class="simpbook-quick-actions-grid">
            <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen-neu'))); ?>" class="simpbook-quick-action">
                <span class="dashicons dashicons-plus-alt"></span>
                <span><?php esc_html_e('New Booking', 'simple-appointment-booking'); ?></span>
            </a>
            <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-kalender'))); ?>" class="simpbook-quick-action">
                <span class="dashicons dashicons-calendar-alt"></span>
                <span><?php esc_html_e('Calendar', 'simple-appointment-booking'); ?></span>
            </a>
            <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen-einstellungen'))); ?>" class="simpbook-quick-action">
                <span class="dashicons dashicons-admin-settings"></span>
                <span><?php esc_html_e('Settings', 'simple-appointment-booking'); ?></span>
            </a>
        </div>
    </div>

    <div class="simpbook-dashboard-grid">
        <!-- Heutige Buchungen -->
        <div class="simpbook-dashboard-card">
            <h2><?php esc_html_e('Today\'s Bookings', 'simple-appointment-booking'); ?></h2>
            <div class="simpbook-dashboard-stats-grid">
                <div class="simpbook-dashboard-stat">
                    <span class="simpbook-stat-number"><?php echo esc_html($simpbook_heutige_anzahl); ?></span>
                    <span class="simpbook-stat-label"><?php esc_html_e('Total', 'simple-appointment-booking'); ?></span>
                </div>
                <div class="simpbook-dashboard-stat simpbook-umsatz-stat">
                    <span class="simpbook-stat-number"><?php echo esc_html(number_format_i18n($simpbook_heute_umsatz, 2)); ?></span>
                    <span class="simpbook-stat-label"><?php esc_html_e('Estimated Revenue', 'simple-appointment-booking'); ?></span>
                </div>
            </div>
            <div class="simpbook-dashboard-status-breakdown">
                <div class="simpbook-status-item status-bestätigt">
                    <span class="simpbook-status-count"><?php echo esc_html($simpbook_heute_bestaetigt); ?></span>
                    <span class="simpbook-status-label"><?php esc_html_e('Confirmed', 'simple-appointment-booking'); ?></span>
                </div>
                <div class="simpbook-status-item status-ausstehend">
                    <span class="simpbook-status-count"><?php echo esc_html($simpbook_heute_ausstehend); ?></span>
                    <span class="simpbook-status-label"><?php esc_html_e('Pending', 'simple-appointment-booking'); ?></span>
                </div>
                <div class="simpbook-status-item status-abgelehnt">
                    <span class="simpbook-status-count"><?php echo esc_html($simpbook_heute_abgelehnt); ?></span>
                    <span class="simpbook-status-label"><?php esc_html_e('Rejected/Cancelled', 'simple-appointment-booking'); ?></span>
                </div>
            </div>
            <?php if (!empty($simpbook_heutige_buchungen_liste)) : ?>
                <div class="simpbook-next-reservation">
                    <h3><?php esc_html_e('Today\'s Bookings', 'simple-appointment-booking'); ?></h3>
                    <div class="simpbook-today-bookings-list">
                        <?php foreach ($simpbook_heutige_buchungen_liste as $simpbook_buchung) : 
                            // Lade Dienstleistung und Mitarbeiter
                            $simpbook_dienstleistung = simpbook_get_dienstleistung($simpbook_buchung->dienstleistung_id);
                            $simpbook_mitarbeiter = $simpbook_buchung->mitarbeiter_id > 0 ? simpbook_get_mitarbeiter($simpbook_buchung->mitarbeiter_id) : null;

                            // Buchungsoption-Name und Preis ermitteln
                            $simpbook_bo_name = '';
                            $simpbook_bo_preis_display = '';
                            if (!empty($simpbook_buchung->buchungsoption_id) && intval($simpbook_buchung->buchungsoption_id) > 0) {
                                $simpbook_bo_table_d = $wpdb->prefix . 'simpbook_buchungsoptionen';
                                $simpbook_bo_row = $wpdb->get_row($wpdb->prepare(
                                    "SELECT name FROM {$simpbook_bo_table_d} WHERE id = %d LIMIT 1",
                                    intval($simpbook_buchung->buchungsoption_id)
                                ));
                                if ($simpbook_bo_row) {
                                    $simpbook_bo_name = $simpbook_bo_row->name;
                                }
                                $simpbook_bo_preis_display = '';
                                if (!empty($simpbook_buchung->buchungsoption_id) && intval($simpbook_buchung->buchungsoption_id) > 0 && !empty($simpbook_buchung->dienstleistung_id)) {
                                    $simpbook_dl_bo_tbl = $wpdb->prefix . 'simpbook_dienstleistung_buchungsoptionen';
                                    $simpbook_bo_raw_preis = $wpdb->get_var($wpdb->prepare(
                                        "SELECT preis FROM {$simpbook_dl_bo_tbl} WHERE dienstleistung_id = %d AND buchungsoption_id = %d LIMIT 1",
                                        intval($simpbook_buchung->dienstleistung_id),
                                        intval($simpbook_buchung->buchungsoption_id)
                                    ));
                                    if (!is_null($simpbook_bo_raw_preis) && $simpbook_bo_raw_preis !== '') {
                                        $simpbook_bo_preis_display = trim($simpbook_bo_raw_preis);
                                    } else {
                                        // Fallback: Dienstleistungs-Preis
                                        $simpbook_bo_preis_display = $simpbook_dienstleistung ? trim($simpbook_dienstleistung->preis ?? '') : '';
                                    }
                                }
                            }
                        ?>
                            <div class="simpbook-booking-item">
                                <div class="simpbook-booking-time">
                                    <strong><?php
                                    if (function_exists('simpbook_format_time')) {
                                        $simpbook_current_language = simpbook_get_current_language();
                                        echo esc_html(simpbook_format_time($simpbook_buchung->uhrzeit, $simpbook_current_language));
                                    } else {
                                        echo esc_html($simpbook_buchung->uhrzeit);
                                    }
                                    ?></strong>
                                </div>
                                <div class="simpbook-booking-details">
                                    <div class="simpbook-booking-name"><?php echo esc_html($simpbook_buchung->name); ?></div>
                                    <div class="simpbook-booking-service">
                                        <?php echo esc_html($simpbook_dienstleistung ? $simpbook_dienstleistung->name : '-'); ?>
                                        <?php if ($simpbook_bo_name !== '') : ?>
                                            <span class="simpbook-booking-option"> | <?php echo esc_html($simpbook_bo_name); ?></span>
                                        <?php endif; ?>
                                        <?php if ($simpbook_bo_preis_display !== '') : ?>
                                            <span class="simpbook-booking-price"> | <?php echo esc_html($simpbook_bo_preis_display); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($simpbook_mitarbeiter) : ?>
                                        <div class="simpbook-booking-employee"><?php echo esc_html($simpbook_mitarbeiter->name); ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
            <div class="simpbook-dashboard-card-footer">
                <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen&simpbook_view=list'))); ?>" class="button">
                    <?php esc_html_e('View All Bookings', 'simple-appointment-booking'); ?>
                </a>
            </div>
        </div>

        <!-- Diese Woche -->
        <div class="simpbook-dashboard-card">
            <h2><?php esc_html_e('This Week', 'simple-appointment-booking'); ?></h2>
            <div class="simpbook-dashboard-stats-grid">
                <div class="simpbook-dashboard-stat">
                    <span class="simpbook-stat-number"><?php echo esc_html($simpbook_woche_anzahl); ?></span>
                    <span class="simpbook-stat-label"><?php esc_html_e('Total', 'simple-appointment-booking'); ?></span>
                </div>
                <div class="simpbook-dashboard-stat simpbook-umsatz-stat">
                    <span class="simpbook-stat-number"><?php echo esc_html(number_format_i18n($simpbook_woche_umsatz, 2)); ?></span>
                    <span class="simpbook-stat-label"><?php esc_html_e('Estimated Revenue', 'simple-appointment-booking'); ?></span>
                </div>
            </div>
            <div class="simpbook-dashboard-status-breakdown">
                <div class="simpbook-status-item status-bestätigt">
                    <span class="simpbook-status-count"><?php echo esc_html($simpbook_woche_status['BESTÄTIGT']); ?></span>
                    <span class="simpbook-status-label"><?php esc_html_e('Confirmed', 'simple-appointment-booking'); ?></span>
                </div>
                <div class="simpbook-status-item status-ausstehend">
                    <span class="simpbook-status-count"><?php echo esc_html($simpbook_woche_status['AUSSTEHEND']); ?></span>
                    <span class="simpbook-status-label"><?php esc_html_e('Pending', 'simple-appointment-booking'); ?></span>
                </div>
                <div class="simpbook-status-item status-abgelehnt">
                    <span class="simpbook-status-count"><?php echo esc_html($simpbook_woche_status['ABGELEHNT'] + $simpbook_woche_status['STORNIERT']); ?></span>
                    <span class="simpbook-status-label"><?php esc_html_e('Rejected/Cancelled', 'simple-appointment-booking'); ?></span>
                </div>
            </div>
            <?php if (!empty($simpbook_woche_nach_tagen)) : ?>
                <div class="simpbook-week-breakdown">
                    <h3><?php esc_html_e('By Days', 'simple-appointment-booking'); ?></h3>
                    <div class="simpbook-week-days">
                        <?php
                        // Wochentage-Übersetzung verwenden
                        if (function_exists('simpbook_get_wochentage')) {
                            $simpbook_wochentage_array = simpbook_get_wochentage();
                        } else {
                            $simpbook_wochentage_array = [
                                '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'),
                            ];
                        }
                        $simpbook_wochentage_namen = [
                            'Monday' => $simpbook_wochentage_array['montag'] ?? __('Monday', 'simple-appointment-booking'),
                            'Tuesday' => $simpbook_wochentage_array['dienstag'] ?? __('Tuesday', 'simple-appointment-booking'),
                            'Wednesday' => $simpbook_wochentage_array['mittwoch'] ?? __('Wednesday', 'simple-appointment-booking'),
                            'Thursday' => $simpbook_wochentage_array['donnerstag'] ?? __('Thursday', 'simple-appointment-booking'),
                            'Friday' => $simpbook_wochentage_array['freitag'] ?? __('Friday', 'simple-appointment-booking'),
                            'Saturday' => $simpbook_wochentage_array['samstag'] ?? __('Saturday', 'simple-appointment-booking'),
                            'Sunday' => $simpbook_wochentage_array['sonntag'] ?? __('Sunday', 'simple-appointment-booking'),
                        ];
                        for ($simpbook_i = 0; $simpbook_i < 7; $simpbook_i++) {
                            $simpbook_tag_timestamp = $simpbook_woche_start + ($simpbook_i * 86400);
                            $simpbook_tag_datum = wp_date('Y-m-d', $simpbook_tag_timestamp);
                            // Verwende gmdate statt wp_date für 'l' um immer englische Wochentagsnamen zu erhalten
                            $simpbook_tag_name = $simpbook_wochentage_namen[gmdate('l', $simpbook_tag_timestamp)];
                            $simpbook_anzahl = isset($simpbook_woche_nach_tagen[$simpbook_tag_datum]) ? $simpbook_woche_nach_tagen[$simpbook_tag_datum] : 0;
                            $simpbook_is_today = ($simpbook_tag_datum === wp_date('Y-m-d'));
                            ?>
                            <div class="simpbook-week-day <?php echo $simpbook_is_today ? 'simpbook-today' : ''; ?>">
                                <span class="simpbook-day-name"><?php echo esc_html($simpbook_tag_name); ?></span>
                                <span class="simpbook-day-date"><?php
                                if (function_exists('simpbook_format_date')) {
                                    $simpbook_current_language = simpbook_get_current_language();
                                    echo esc_html(simpbook_format_date($simpbook_tag_datum, $simpbook_current_language));
                                } else {
                                    echo esc_html(date_i18n(get_option('date_format', 'd.m.Y'), strtotime($simpbook_tag_datum)));
                                }
                                ?></span>
                                <span class="simpbook-day-count"><?php echo esc_html($simpbook_anzahl); ?></span>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            <?php endif; ?>
            <div class="simpbook-dashboard-card-footer">
                <a href="<?php echo esc_url(simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-reservierungen&simpbook_view=list'))); ?>" class="button">
                    <?php esc_html_e('View All Bookings', 'simple-appointment-booking'); ?></a>
            </div>
        </div>
    </div>

    <!-- Buchungen dieses Jahr -->
    <div class="simpbook-dashboard-card" style="margin-bottom: 30px;">
        <h2>
            <span class="dashicons dashicons-calendar-alt" style="color: #667eea; font-size: 24px; margin-right: 8px;"></span>
            <?php esc_html_e('Bookings This Year', 'simple-appointment-booking'); ?> (<?php echo esc_html(wp_date('Y')); ?>)
        </h2>
        <div class="simpbook-dashboard-stats-grid">
            <div class="simpbook-dashboard-stat">
                <span class="simpbook-stat-number"><?php echo esc_html(number_format_i18n($simpbook_jahr_anzahl)); ?></span>
                <span class="simpbook-stat-label"><?php esc_html_e('Total', 'simple-appointment-booking'); ?></span>
            </div>
            <div class="simpbook-dashboard-stat simpbook-umsatz-stat">
                <span class="simpbook-stat-number"><?php echo esc_html(number_format_i18n($simpbook_jahr_umsatz, 2)); ?></span>
                <span class="simpbook-stat-label"><?php esc_html_e('Estimated Revenue', 'simple-appointment-booking'); ?></span>
            </div>
        </div>
    </div>

    <!-- Shortcode-Box -->
    <div class="simpbook-dashboard-shortcode-box">
        <h2><?php esc_html_e('Embed Booking Form', 'simple-appointment-booking'); ?></h2>
        <p><?php esc_html_e('Add the following shortcode to a page or post to display the booking form:', 'simple-appointment-booking'); ?></p>
        <div class="simpbook-shortcode-display">
            <code id="simpbook-shortcode-text">[simpbook_bookingform]</code>
            <button type="button" class="button button-primary" id="simpbook-copy-shortcode">
                <span class="dashicons dashicons-clipboard"></span>
                <?php esc_html_e('Copy', 'simple-appointment-booking'); ?>
            </button>
        </div>
        <?php if ($simpbook_shortcode_seite_gefunden) : ?>
            <p class="simpbook-shortcode-status success">
                <span class="dashicons dashicons-yes-alt"></span>
                <?php esc_html_e('The shortcode is already used on the following pages:', 'simple-appointment-booking'); ?>
                <?php foreach ($simpbook_pages_with_shortcode as $simpbook_item) : ?>
                    <a href="<?php echo esc_url(get_edit_post_link($simpbook_item->ID)); ?>" target="_blank"><?php echo esc_html($simpbook_item->post_title); ?></a><?php echo ($simpbook_item !== end($simpbook_pages_with_shortcode)) ? ', ' : ''; ?>
                <?php endforeach; ?>
            </p>
        <?php else : ?>
            <p class="simpbook-shortcode-status warning">
                <span class="dashicons dashicons-warning"></span>
                <?php esc_html_e('The shortcode is not yet used on any page.', 'simple-appointment-booking'); ?>
                <a href="<?php echo esc_url(admin_url('post-new.php?post_type=page')); ?>" class="button button-small" style="margin-left: 10px;">
                    <?php esc_html_e('Create New Page', 'simple-appointment-booking'); ?>
                </a>
            </p>
        <?php endif; ?>

        <?php if (!empty($simpbook_alle_kategorien)) : ?>
            <hr style="margin: 20px 0; border: none; border-top: 1px solid #e0e0e0;">
            <h3 style="margin: 0 0 8px;font-size:14px;"><?php esc_html_e('Category-Specific Shortcodes', 'simple-appointment-booking'); ?></h3>
            <p style="margin: 0 0 14px; color: #666; font-size: 13px;"><?php esc_html_e('Use these shortcodes to embed a booking form on a page that shows only the services of a specific category - ideal for landing pages or multiple locations.', 'simple-appointment-booking'); ?></p>
            <div class="simpbook-kategorie-shortcode-list">
                <?php foreach ($simpbook_alle_kategorien as $simpbook_kat) : ?>
                    <?php $simpbook_kat_sc = '[simpbook_bookingform kategorie="' . esc_attr($simpbook_kat->id) . '"]'; ?>
                    <div class="simpbook-kat-shortcode-row">
                        <span class="simpbook-kat-badge" style="background:<?php echo esc_attr($simpbook_kat->farbe ?? '#2271b1'); ?>;"><?php echo esc_html($simpbook_kat->name); ?></span>
                        <code class="simpbook-kat-sc-code"><?php echo esc_html($simpbook_kat_sc); ?></code>
                        <button type="button" class="button button-small simpbook-copy-kat-shortcode"
                                data-shortcode="<?php echo esc_attr($simpbook_kat_sc); ?>">
                            <span class="dashicons dashicons-clipboard" style="vertical-align:middle;"></span>
                            <?php esc_html_e('Copy', 'simple-appointment-booking'); ?>
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>
            <style>
                .simpbook-kategorie-shortcode-list { display: flex; flex-direction: column; gap: 8px; }
                .simpbook-kat-shortcode-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
                .simpbook-kat-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; color: #fff; font-size: 12px; font-weight: 600; white-space: nowrap; }
                .simpbook-kat-sc-code { flex: 1; min-width: 0; background: #f5f5f5; padding: 6px 10px; border-radius: 4px; font-size: 13px; word-break: break-all; }
            </style>
        <?php endif; ?>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Setup-Wizard-Hinweis verwerfen
    $('.simpbook-wizard-notice').on('click', '.notice-dismiss', function() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'simpbook_dismiss_wizard_notice',
                nonce: '<?php echo esc_js(wp_create_nonce('simpbook_dismiss_wizard')); ?>'
            }
        });
    });

    // Kategorie-Shortcodes kopieren
    $(document).on('click', '.simpbook-copy-kat-shortcode', function() {
        const $btn = $(this);
        const sc = $btn.data('shortcode');
        navigator.clipboard.writeText(sc).then(function() {
            const orig = $btn.html();
            $btn.html('<span class="dashicons dashicons-yes" style="vertical-align:middle;"></span> <?php echo esc_js(__('Copied!', 'simple-appointment-booking')); ?>');
            setTimeout(function() { $btn.html(orig); }, 2000);
        });
    });
});
</script>






