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

// Testphase-Hinweis anzeigen
simpbook_display_trial_notice_on_admin_pages();

/**
 * Übersetzt einen Status-String für die Anzeige
 */
function simpbook_translate_status($status) {
    $simpbook_status_map = [
        'AUSSTEHEND' => esc_html__('Pending', 'simple-appointment-booking'),
        'BESTÄTIGT'  => esc_html__('Confirmed', 'simple-appointment-booking'),
        'ABGELEHNT'  => esc_html__('Rejected', 'simple-appointment-booking'),
        'STORNIERT'  => esc_html__('Cancelled', 'simple-appointment-booking'),
    ];

    return $simpbook_status_map[$status] ?? esc_html($status);
}

// Filter-Parameter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_filter = isset($_GET['simpbook_filter']) ? sanitize_text_field(wp_unslash($_GET['simpbook_filter'])) : 'heute';

// Suchparameter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_search = isset($_GET['simpbook_search']) ? sanitize_text_field(wp_unslash($_GET['simpbook_search'])) : '';

// Einträge pro Seite (mit Dropdown-Auswahl)
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_per_page = isset($_GET['simpbook_per_page']) ? intval($_GET['simpbook_per_page']) : 20;
$simpbook_valid_per_page = [20, 40, 60, 100];
if (!in_array($simpbook_per_page, $simpbook_valid_per_page, true)) {
    $simpbook_per_page = 20; // Fallback auf Standard
}

// Aktuelle Parameter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_current_page = isset($_GET['simpbook_seite_nr']) ? max(1, intval($_GET['simpbook_seite_nr'])) : 1;
$simpbook_offset       = ($simpbook_current_page - 1) * $simpbook_per_page;

// Sortierung
$simpbook_valid_orders = ['id', 'name', 'datum', 'uhrzeit', 'status', 'erstellungsdatum'];
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_order        = isset($_GET['simpbook_order']) && in_array(sanitize_text_field(wp_unslash($_GET['simpbook_order'])), $simpbook_valid_orders, true) ? sanitize_text_field(wp_unslash($_GET['simpbook_order'])) : 'datum';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_direction    = isset($_GET['simpbook_direction']) && strtoupper(sanitize_text_field(wp_unslash($_GET['simpbook_direction']))) === 'DESC' ? 'DESC' : 'ASC';

// Filter-Bedingungen für die Datenbankabfrage
global $wpdb;
$simpbook_dl_table_om = $wpdb->prefix . 'dienstleistungen';
$simpbook_filter_condition = '';
switch ($simpbook_filter) {
    case 'heute':
        $simpbook_filter_condition = "(datum = CURDATE())";
        break;
    case 'zukuenftige':
        $simpbook_filter_condition = "((datum > CURDATE()) OR (datum = CURDATE() AND uhrzeit >= CURTIME()))";
        break;
    case 'vergangene':
        $simpbook_filter_condition = "((datum < CURDATE()) OR (datum = CURDATE() AND uhrzeit < CURTIME()))";
        break;
    case 'ausstehend':
        $simpbook_filter_condition = "(status = 'AUSSTEHEND' AND storniert = 0)";
        break;
    case 'ohne-mitarbeiter':
        $simpbook_filter_condition = "((mitarbeiter_id = 0 OR mitarbeiter_id IS NULL OR mitarbeiter_id = '' OR mitarbeiter_id = '0') AND storniert = 0 AND (dienstleistung_id IS NULL OR dienstleistung_id NOT IN (SELECT id FROM `{$simpbook_dl_table_om}` WHERE ohne_mitarbeiter = 1)))";
        break;
    case 'storniert':
        $simpbook_filter_condition = "(storniert = 1 OR status = 'ABGELEHNT')";
        break;
    default:
        $simpbook_filter_condition = '(1=1)'; // Alle anzeigen
}

// Suchbedingung hinzufügen
$simpbook_search_condition = '';
if (!empty($simpbook_search)) {
    global $wpdb;
    $search_like = '%' . $wpdb->esc_like($simpbook_search) . '%';
    $simpbook_search_condition = " AND (name LIKE '" . esc_sql($search_like) . "' OR email LIKE '" . esc_sql($search_like) . "' OR telefon LIKE '" . esc_sql($search_like) . "')";
}

// Kombiniere Filter und Suche
$simpbook_final_condition = $simpbook_filter_condition . $simpbook_search_condition;

// Daten abrufen mit Filter und Suche
$simpbook_reservierungen = $this->simpbook_alle_reservierungen_holen($simpbook_per_page, $simpbook_offset, $simpbook_order, $simpbook_direction, $simpbook_final_condition);
$simpbook_total_items    = $this->simpbook_reservierungen_zaehlen($simpbook_final_condition);
$simpbook_total_pages    = ceil($simpbook_total_items / $simpbook_per_page);

// Alle Mitarbeiter für Dropdown im Modal laden
$simpbook_alle_mitarbeiter = simpbook_get_all_mitarbeiter(false, false);

// Buchungsoptionen-Cache für Modal-Anzeige (einmalig laden)
$simpbook_bo_aktiv_liste = get_option('simpbook_buchungsoptionen_aktiv', '0') === '1';
$simpbook_buchungsoptionen_cache = [];
if ($simpbook_bo_aktiv_liste) {
    global $wpdb;
    $bo_table_cache = $wpdb->prefix . 'simpbook_buchungsoptionen';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $bo_all_rows = $wpdb->get_results("SELECT id, name FROM `{$bo_table_cache}`");
    foreach ($bo_all_rows as $bo_entry) {
        $simpbook_buchungsoptionen_cache[(int)$bo_entry->id] = $bo_entry->name;
    }
}

// Nachrichten
$simpbook_messages = [
    'geloescht'     => esc_html__('Reservation successfully deleted.', 'simple-appointment-booking'),
    'aktualisiert'  => esc_html__('Reservation successfully updated.', 'simple-appointment-booking'),
    'bestaetigt'    => esc_html__('Booking was confirmed.', 'simple-appointment-booking'),
    'abgelehnt'     => esc_html__('Booking was rejected.', 'simple-appointment-booking'),
    'storniert'     => esc_html__('Booking was cancelled.', 'simple-appointment-booking'),
    'ausstehend'    => esc_html__('Nur ausstehende Buchungen werden angezeigt.', 'simple-appointment-booking')
];

// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if (isset($_GET['simpbook_nachricht'])) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $simpbook_nachricht_key = sanitize_text_field(wp_unslash($_GET['simpbook_nachricht']));
    if (isset($simpbook_messages[$simpbook_nachricht_key])) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($simpbook_messages[$simpbook_nachricht_key]) . '</p></div>';
    }
}

// Base URL mit PWA-Parameter falls nötig
$simpbook_base_url = simpbook_is_pwa_mode() 
    ? admin_url('admin.php?page=simpbook-reservierungen&pwa=1')
    : admin_url('admin.php?page=simpbook-reservierungen');
?>

<div class="wrap simpbook-admin-wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e('Bookings Overview', 'simple-appointment-booking'); ?></h1>
    <hr class="wp-header-end">

    <!-- Action Buttons Container -->
    <div class="view-toggle-container">
        <a href="<?php echo esc_url(simpbook_is_pwa_mode() ? simpbook_pwa_url('simpbook-reservierungen-neu') : admin_url('admin.php?page=simpbook-reservierungen-neu')); ?>" class="page-title-action"><?php esc_html_e('Add New', 'simple-appointment-booking'); ?></a>
        
        <div class="reservierungen-search-container">
            <form method="get" id="reservierungen-search-form" style="display: flex; gap: 8px; align-items: center; flex: 1;">
                <input type="hidden" name="page" value="simpbook-reservierungen">
                <input type="hidden" name="simpbook_filter" value="<?php echo esc_attr($simpbook_filter); ?>">
                <input type="hidden" name="simpbook_per_page" value="<?php echo esc_attr($simpbook_per_page); ?>">
                <span class="dashicons dashicons-search"></span>
                <input type="text" 
                       name="simpbook_search"
                       id="reservierungen-search-input" 
                       value="<?php echo esc_attr($simpbook_search); ?>"
                       placeholder="<?php esc_attr_e('Search by name or email...', 'simple-appointment-booking'); ?>"
                       aria-label="<?php esc_attr_e('Search bookings', 'simple-appointment-booking'); ?>"
                       style="flex: 1;">
                <button type="submit" class="button button-primary button-bestaetigen" style="height: 32px; min-width: 80px; display: flex; align-items: center; justify-content: center;">
                    <?php esc_html_e('Suchen', 'simple-appointment-booking'); ?>
                </button>
                <?php if (!empty($simpbook_search)): ?>
                    <a href="<?php echo esc_url(add_query_arg(array('page' => 'simpbook-reservierungen', 'simpbook_filter' => $simpbook_filter, 'simpbook_per_page' => $simpbook_per_page), admin_url('admin.php'))); ?>" 
                       class="button" 
                       style="height: 32px; padding: 0 10px;"
                       title="<?php esc_attr_e('Clear search', 'simple-appointment-booking'); ?>">
                        <span class="dashicons dashicons-no-alt" style="margin-top: 4px;"></span>
                    </a>
                <?php endif; ?>
            </form>
        </div>
        
        <button type="button" id="toggle-reservierungen-view-btn" class="button button-secondary">
            <span class="dashicons dashicons-grid-view" style="margin-right: 5px; vertical-align: middle;"></span>
            <span id="toggle-reservierungen-view-text"><?php esc_html_e('Card View', 'simple-appointment-booking'); ?></span>
        </button>
    </div>

    <div class="reservierungen-filter-container">
        <button class="filter-toggle-button" id="simpbook-filter-toggle" aria-expanded="false">
            <span class="dashicons dashicons-filter"></span>
            <span class="filter-toggle-text"><?php esc_html_e('Filter', 'simple-appointment-booking'); ?></span>
            <span class="dashicons dashicons-arrow-down-alt2 filter-toggle-icon"></span>
        </button>
        <div class="filter-options" id="simpbook-filter-panel">
            <ul class="filter-links">
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'heute', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'heute' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('Today', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen("datum = CURDATE()")); ?>)</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'ausstehend', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'ausstehend' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('Pending', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen("status = 'AUSSTEHEND'")); ?>)</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'zukuenftige', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'zukuenftige' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('Upcoming', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen("(datum > CURDATE()) OR (datum = CURDATE() AND uhrzeit >= CURTIME())")); ?>)</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'ohne-mitarbeiter', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'ohne-mitarbeiter' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('Without Employee', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen("(mitarbeiter_id = 0 OR mitarbeiter_id IS NULL OR mitarbeiter_id = '' OR mitarbeiter_id = '0') AND storniert = 0 AND (dienstleistung_id IS NULL OR dienstleistung_id NOT IN (SELECT id FROM `{$simpbook_dl_table_om}` WHERE ohne_mitarbeiter = 1))")); ?>)</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'vergangene', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'vergangene' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('Past', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen("(datum < CURDATE()) OR (datum = CURDATE() AND uhrzeit < CURTIME())")); ?>)</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'storniert', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'storniert' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('Rejected/Cancelled', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen("storniert = 1 OR status = 'ABGELEHNT'")); ?>)</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(add_query_arg('simpbook_filter', 'alle', remove_query_arg('simpbook_seite_nr', $simpbook_base_url))); ?>"
                       class="filter-button <?php echo $simpbook_filter === 'alle' ? 'current-filter' : ''; ?>">
                        <?php esc_html_e('All', 'simple-appointment-booking'); ?>
                        <span class="count">(<?php echo esc_html($this->simpbook_reservierungen_zaehlen('1=1')); ?>)</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <div class="simpbook-list-container">
        <div class="status-legend">
        <div class="status-legend-title"><?php esc_html_e('Status Colors:', 'simple-appointment-booking'); ?></div>
        <div class="status-legend-items">
            <div class="status-legend-item">
                <span class="status-legend-color status-legend-bestätigt"></span>
                <span class="status-legend-label"><?php esc_html_e('Confirmed', 'simple-appointment-booking'); ?></span>
            </div>
            <div class="status-legend-item">
                <span class="status-legend-color status-legend-abgelehnt"></span>
                <span class="status-legend-label"><?php esc_html_e('Rejected', 'simple-appointment-booking'); ?></span>
            </div>
            <div class="status-legend-item">
                <span class="status-legend-color status-legend-ausstehend"></span>
                <span class="status-legend-label"><?php esc_html_e('Pending', 'simple-appointment-booking'); ?></span>
            </div>
            <div class="status-legend-item">
                <span class="status-legend-color status-legend-storniert"></span>
                <span class="status-legend-label"><?php esc_html_e('Cancelled', 'simple-appointment-booking'); ?></span>
            </div>
        </div>
    </div>

    <?php
    $simpbook_export_nonce = wp_create_nonce('simpbook_export_reservierungen_csv_nonce');
    $simpbook_export_url_params = [
        'action'             => 'export_csv',
        'simpbook_filter'    => $simpbook_filter,
        'simpbook_order'     => $simpbook_order,
        'simpbook_direction' => $simpbook_direction,
        'simpbook_nonce'     => $simpbook_export_nonce
    ];
    $simpbook_export_url = add_query_arg($simpbook_export_url_params, $simpbook_base_url);
    ?>

    <?php if (empty($simpbook_reservierungen)) : ?>
        <div class="notice notice-info"><p><?php esc_html_e('No reservations found.', 'simple-appointment-booking'); ?></p></div>
    <?php else : ?>

    <?php if (in_array($simpbook_filter, ['vergangene', 'storniert'], true)) : ?>
    <div id="bulk-actions-container" style="margin-bottom: 15px; display: none;">
        <button type="button" id="bulk-delete-btn" class="button button-danger" style="background-color: #dc3545; color: white; border-color: #dc3545;">
            <span class="dashicons dashicons-trash" style="margin-right: 5px; vertical-align: middle;"></span>
            <?php esc_html_e('Delete Selected', 'simple-appointment-booking'); ?>
        </button>
        <span id="selected-count" style="margin-left: 15px; font-weight: 600;">0 <?php esc_html_e('selected', 'simple-appointment-booking'); ?></span>
    </div>
    <?php endif; ?>

    <div class="desktop-reservierungen-tabelle">
        <div style="overflow-x: auto; width: 100%;">
        <table class="wp-list-table widefat fixed striped reservierungen-haupttabelle">
            <thead>
                <tr>
                    <?php if (in_array($simpbook_filter, ['vergangene', 'storniert'], true)) : ?>
                    <th style="width: 3%;"><input type="checkbox" id="select-all-checkbox"></th>
                    <?php endif; ?>
                    <th style="width: 6%;">
                        <a href="<?php echo esc_url(add_query_arg(['simpbook_order' => 'name', 'simpbook_direction' => ($simpbook_order === 'name' && $simpbook_direction === 'ASC') ? 'DESC' : 'ASC', 'simpbook_filter' => $simpbook_filter], $simpbook_base_url)); ?>">
                            <?php esc_html_e('Name', 'simple-appointment-booking'); ?> <?php echo esc_html(($simpbook_order === 'name') ? ($simpbook_direction === 'ASC' ? '▲' : '▼') : ''); ?>
                        </a>
                    </th>
                     <th style="width: 10%;"><?php esc_html_e('Contact', 'simple-appointment-booking'); ?></th>
                    <th style="width: 6%;">
                        <a href="<?php echo esc_url(add_query_arg(['simpbook_order' => 'datum', 'simpbook_direction' => ($simpbook_order === 'datum' && $simpbook_direction === 'ASC') ? 'DESC' : 'ASC', 'simpbook_filter' => $simpbook_filter], $simpbook_base_url)); ?>">
                            <?php esc_html_e('Date', 'simple-appointment-booking'); ?> <?php echo esc_html(($simpbook_order === 'datum') ? ($simpbook_direction === 'ASC' ? '▲' : '▼') : ''); ?>
                        </a>
                    </th>
                    <th style="width: 5%;"><?php esc_html_e('Time', 'simple-appointment-booking'); ?></th>
                    <th style="width: 9%;"><?php esc_html_e('Service', 'simple-appointment-booking'); ?></th>
                    <th style="width: 9%;"><?php esc_html_e('Booking Option', 'simple-appointment-booking'); ?></th>
                    <th style="width: 8%;"><?php esc_html_e('Staff', 'simple-appointment-booking'); ?></th>
                    <th style="width: 7%;"><?php esc_html_e('Message', 'simple-appointment-booking'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($simpbook_reservierungen as $simpbook_reservierung) :
                    $simpbook_dienstleistung = isset($simpbook_reservierung->dienstleistung_id) && $simpbook_reservierung->dienstleistung_id > 0
                        ? simpbook_get_dienstleistung($simpbook_reservierung->dienstleistung_id)
                        : null;
                    $simpbook_mitarbeiter = isset($simpbook_reservierung->mitarbeiter_id) && $simpbook_reservierung->mitarbeiter_id > 0
                        ? simpbook_get_mitarbeiter($simpbook_reservierung->mitarbeiter_id)
                        : null;
                    
                    // Verfügbare Mitarbeiter für diese Buchung ermitteln
                    $simpbook_verfuegbare_mitarbeiter = simpbook_get_verfuegbare_mitarbeiter_fuer_buchung(
                        $simpbook_reservierung->dienstleistung_id ?? 0,
                        $simpbook_reservierung->datum ?? '',
                        $simpbook_reservierung->uhrzeit ?? ''
                    );

                    $simpbook_status_to_class = [
                        'BESTÄTIGT' => 'bestätigt',
                        'ABGELEHNT' => 'abgelehnt',
                        'AUSSTEHEND' => 'ausstehend',
                        'STORNIERT' => 'storniert'
                    ];
                    $simpbook_status_class = isset($simpbook_status_to_class[$simpbook_reservierung->status]) ? $simpbook_status_to_class[$simpbook_reservierung->status] : mb_strtolower($simpbook_reservierung->status, 'UTF-8');
                    if (isset($simpbook_reservierung->storniert) && $simpbook_reservierung->storniert == 1) {
                        $simpbook_status_class = 'storniert';
                    }
                ?>
                    <tr class="reservierung-row-clickable reservierung-status-<?php echo esc_attr($simpbook_status_class); ?><?php echo (isset($simpbook_reservierung->storniert) && $simpbook_reservierung->storniert == 1) ? ' reservierung-status-storniert' : ''; ?>"
                        data-reservierung-id="<?php echo esc_attr($simpbook_reservierung->id); ?>"
                        data-status-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_status_change_nonce_'.$simpbook_reservierung->id)); ?>"
                        data-stornieren-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_nonce_'.$simpbook_reservierung->id)); ?>"
                        data-bearbeiten-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_bearbeiten_'.$simpbook_reservierung->id)); ?>"
                        data-loeschen-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_nonce_'.$simpbook_reservierung->id)); ?>"
                        data-reservierung-data='<?php echo esc_attr(json_encode([
                            'id' => $simpbook_reservierung->id,
                            'name' => $simpbook_reservierung->name,
                            'email' => $simpbook_reservierung->email,
                            'telefon' => $simpbook_reservierung->telefon,
                            'datum' => $simpbook_reservierung->datum,
                            'uhrzeit' => $simpbook_reservierung->uhrzeit,
                            'nachricht' => $simpbook_reservierung->nachricht ?? '',
                            'status' => $simpbook_reservierung->status,
                            'storniert' => isset($simpbook_reservierung->storniert) ? $simpbook_reservierung->storniert : 0,
                            'dienstleistung' => $simpbook_dienstleistung ? $simpbook_dienstleistung->name : '-',
                            'mitarbeiter' => $simpbook_mitarbeiter ? $simpbook_mitarbeiter->name : '-',
                            'mitarbeiter_id' => isset($simpbook_reservierung->mitarbeiter_id) ? $simpbook_reservierung->mitarbeiter_id : 0,
                            'verfuegbare_mitarbeiter' => $simpbook_verfuegbare_mitarbeiter,
                            'status_class' => $simpbook_status_class,
                            'status_geaendert_datum' => isset($simpbook_reservierung->status_geaendert_datum) ? $simpbook_reservierung->status_geaendert_datum : null,
                            'buchungsoption' => ($simpbook_bo_aktiv_liste && !empty($simpbook_reservierung->buchungsoption_id) && isset($simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id])) ? $simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id] : ''
                        ])); ?>'
                        style="cursor: pointer;">
                        <?php if (in_array($simpbook_filter, ['vergangene', 'storniert'], true)) : ?>
                        <td><input type="checkbox" class="reservation-checkbox" value="<?php echo esc_attr($simpbook_reservierung->id); ?>" data-id="<?php echo esc_attr($simpbook_reservierung->id); ?>"></td>
                        <?php endif; ?>
                        <td><?php echo esc_html($simpbook_reservierung->name); ?></td>
                        <td style="font-size: 12px; line-height: 1.4;">
                            <div><?php echo esc_html($simpbook_reservierung->email); ?></div>
                            <div style="color: #666;"><?php echo esc_html($simpbook_reservierung->telefon); ?></div>
                        </td>
                        <td><?php echo esc_html(simpbook_format_date($simpbook_reservierung->datum)); ?></td>
                        <td><?php echo esc_html(simpbook_format_time($simpbook_reservierung->uhrzeit)); ?></td>
                        <td><?php echo $simpbook_dienstleistung ? esc_html($simpbook_dienstleistung->name) : '-'; ?></td>
                        <td><?php echo ($simpbook_bo_aktiv_liste && !empty($simpbook_reservierung->buchungsoption_id) && isset($simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id])) ? esc_html($simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id]) : '-'; ?></td>
                        <td><?php echo $simpbook_mitarbeiter ? esc_html($simpbook_mitarbeiter->name) : '-'; ?></td>
                        <td style="max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px;" title="<?php echo !empty($simpbook_reservierung->nachricht) ? esc_attr($simpbook_reservierung->nachricht) : ''; ?>">
                            <?php echo !empty($simpbook_reservierung->nachricht) ? esc_html(mb_substr($simpbook_reservierung->nachricht, 0, 30)) . (mb_strlen($simpbook_reservierung->nachricht) > 30 ? '...' : '') : '-'; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>

    <div id="reservierung-detail-modal" class="reservierung-modal" style="display: none;">
        <div class="reservierung-modal-overlay"></div>
        <div class="reservierung-modal-content">
            <div class="reservierung-modal-header">
                <h2><?php esc_html_e('Booking Details', 'simple-appointment-booking'); ?></h2>
                <button class="reservierung-modal-close" aria-label="<?php esc_attr_e('Close', 'simple-appointment-booking'); ?>">
                    <span class="dashicons dashicons-no-alt"></span>
                </button>
            </div>
            <div class="reservierung-modal-body">
                <div class="reservierung-detail-grid">
                    <div class="detail-card">
                        <div class="detail-card-header">
                            <span class="dashicons dashicons-admin-users"></span>
                            <h3><?php esc_html_e('Contact', 'simple-appointment-booking'); ?></h3>
                        </div>
                        <div class="detail-card-content">
                            <div class="detail-item"><strong><?php esc_html_e('Name:', 'simple-appointment-booking'); ?></strong> <span id="modal-name"></span></div>
                            <div class="detail-item"><strong><?php esc_html_e('Email:', 'simple-appointment-booking'); ?></strong> <span id="modal-email"></span></div>
                            <div class="detail-item"><strong><?php esc_html_e('Phone:', 'simple-appointment-booking'); ?></strong> <span id="modal-telefon"></span></div>
                        </div>
                    </div>

                    <div class="detail-card">
                        <div class="detail-card-header">
                            <span class="dashicons dashicons-calendar-alt"></span>
                            <h3><?php esc_html_e('Appointment', 'simple-appointment-booking'); ?></h3>
                        </div>
                        <div class="detail-card-content">
                            <div class="detail-item"><strong><?php esc_html_e('Date:', 'simple-appointment-booking'); ?></strong> <span id="modal-datum"></span></div>
                            <div class="detail-item"><strong><?php esc_html_e('Time:', 'simple-appointment-booking'); ?></strong> <span id="modal-uhrzeit"></span></div>
                            <div class="detail-item" id="modal-buchungsoption-row" style="display:none;"><strong><?php esc_html_e('Booking Option:', 'simple-appointment-booking'); ?></strong> <span id="modal-buchungsoption"></span></div>
                        </div>
                    </div>

                    <div class="detail-card">
                        <div class="detail-card-header">
                            <span class="dashicons dashicons-admin-tools"></span>
                            <h3><?php esc_html_e('Service', 'simple-appointment-booking'); ?></h3>
                        </div>
                        <div class="detail-card-content">
                            <div class="detail-item"><strong><?php esc_html_e('Service:', 'simple-appointment-booking'); ?></strong> <span id="modal-dienstleistung"></span></div>
                            <div class="detail-item">
                                <strong><?php esc_html_e('Staff:', 'simple-appointment-booking'); ?></strong>
                                <select id="modal-mitarbeiter-select" class="simpbook-mitarbeiter-dropdown" data-reservierung-id="">
                                    <option value="0"><?php esc_html_e('No Specific Staff Member', 'simple-appointment-booking'); ?></option>
                                    <?php foreach ($simpbook_alle_mitarbeiter as $simpbook_mitarbeiter) : ?>
                                        <option value="<?php echo esc_attr($simpbook_mitarbeiter->id); ?>"><?php echo esc_html($simpbook_mitarbeiter->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="simpbook-save-indicator" style="display:none; margin-left: 10px; color: #46b450;">
                                    <span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Saved', 'simple-appointment-booking'); ?>
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="detail-card">
                        <div class="detail-card-header">
                            <span class="dashicons dashicons-format-chat"></span>
                            <h3><?php esc_html_e('Message', 'simple-appointment-booking'); ?></h3>
                        </div>
                        <div class="detail-card-content">
                            <div id="modal-nachricht" style="white-space: pre-wrap; min-height: 60px;"></div>
                        </div>
                    </div>

                    <div class="detail-card full-width">
                        <div class="detail-card-header">
                            <span class="dashicons dashicons-admin-settings"></span>
                            <h3><?php esc_html_e('Status & Actions', 'simple-appointment-booking'); ?></h3>
                        </div>
                        <div class="detail-card-content">
                            <div class="detail-item-row">
                                <div class="detail-item"><strong><?php esc_html_e('Current Status:', 'simple-appointment-booking'); ?></strong> <span id="modal-status-badge"></span></div>
                                <div class="detail-item" id="modal-status-date" style="display: none;">
                                    <strong id="modal-status-date-label"></strong>
                                    <span id="modal-status-date-value"></span>
                                </div>
                            </div>
                            <div class="detail-actions" id="modal-actions"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="mobile-reservierungen-karten">
        <?php foreach ($simpbook_reservierungen as $simpbook_reservierung) :
            $simpbook_dienstleistung = isset($simpbook_reservierung->dienstleistung_id) && $simpbook_reservierung->dienstleistung_id > 0
                ? simpbook_get_dienstleistung($simpbook_reservierung->dienstleistung_id)
                : null;
            $simpbook_mitarbeiter = isset($simpbook_reservierung->mitarbeiter_id) && $simpbook_reservierung->mitarbeiter_id > 0
                ? simpbook_get_mitarbeiter($simpbook_reservierung->mitarbeiter_id)
                : null;
            
            // Verfügbare Mitarbeiter für diese Buchung ermitteln
            $simpbook_verfuegbare_mitarbeiter = simpbook_get_verfuegbare_mitarbeiter_fuer_buchung(
                $simpbook_reservierung->dienstleistung_id ?? 0,
                $simpbook_reservierung->datum ?? '',
                $simpbook_reservierung->uhrzeit ?? ''
            );
            
            $simpbook_status_to_class = [
                'BESTÄTIGT' => 'bestätigt',
                'ABGELEHNT' => 'abgelehnt',
                'AUSSTEHEND' => 'ausstehend',
                'STORNIERT' => 'storniert'
            ];
            $simpbook_status_class = isset($simpbook_status_to_class[$simpbook_reservierung->status]) ? $simpbook_status_to_class[$simpbook_reservierung->status] : mb_strtolower($simpbook_reservierung->status, 'UTF-8');
            if (isset($simpbook_reservierung->storniert) && $simpbook_reservierung->storniert == 1) {
                $simpbook_status_class = 'storniert';
            }
        ?>
            <div class="reservierung-karte reservierung-karte-clickable reservierung-status-<?php echo esc_attr($simpbook_status_class); ?><?php echo (isset($simpbook_reservierung->storniert) && $simpbook_reservierung->storniert == 1) ? ' reservierung-status-storniert' : ''; ?>"
                data-reservierung-id="<?php echo esc_attr($simpbook_reservierung->id); ?>"
                data-status-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_status_change_nonce_'.$simpbook_reservierung->id)); ?>"
                data-stornieren-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_nonce_'.$simpbook_reservierung->id)); ?>"
                data-bearbeiten-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_bearbeiten_'.$simpbook_reservierung->id)); ?>"
                data-loeschen-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_nonce_'.$simpbook_reservierung->id)); ?>"
                data-reservierung-data='<?php echo esc_attr(json_encode([
                    'id' => $simpbook_reservierung->id,
                    'name' => $simpbook_reservierung->name,
                    'email' => $simpbook_reservierung->email,
                    'telefon' => $simpbook_reservierung->telefon,
                    'datum' => $simpbook_reservierung->datum,
                    'uhrzeit' => $simpbook_reservierung->uhrzeit,
                    'nachricht' => $simpbook_reservierung->nachricht ?? '',
                    'status' => $simpbook_reservierung->status,
                    'storniert' => isset($simpbook_reservierung->storniert) ? $simpbook_reservierung->storniert : 0,
                    'dienstleistung' => $simpbook_dienstleistung ? $simpbook_dienstleistung->name : '-',
                    'mitarbeiter' => $simpbook_mitarbeiter ? $simpbook_mitarbeiter->name : '-',
                    'mitarbeiter_id' => isset($simpbook_reservierung->mitarbeiter_id) ? $simpbook_reservierung->mitarbeiter_id : 0,
                    'verfuegbare_mitarbeiter' => $simpbook_verfuegbare_mitarbeiter,
                    'status_class' => $simpbook_status_class,
                    'status_geaendert_datum' => isset($simpbook_reservierung->status_geaendert_datum) ? $simpbook_reservierung->status_geaendert_datum : null,
                    'buchungsoption' => ($simpbook_bo_aktiv_liste && !empty($simpbook_reservierung->buchungsoption_id) && isset($simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id])) ? $simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id] : ''
                ])); ?>'
                style="cursor: pointer;">
                <div class="reservierung-karte-header">
                    <div class="reservierung-name"><?php echo esc_html($simpbook_reservierung->name); ?></div>
                </div>
                <div class="reservierung-karte-body">
                    <div class="reservierung-info-gruppe">
                        <div class="reservierung-info-zeile">
                            <span class="info-label"><?php esc_html_e('Date:', 'simple-appointment-booking'); ?></span>
                            <span class="info-value"><?php echo esc_html(simpbook_format_date($simpbook_reservierung->datum)); ?></span>
                        </div>
                        <div class="reservierung-info-zeile">
                            <span class="info-label"><?php esc_html_e('Time:', 'simple-appointment-booking'); ?></span>
                            <span class="info-value"><?php echo esc_html(simpbook_format_time($simpbook_reservierung->uhrzeit)); ?></span>
                        </div>
                        <div class="reservierung-info-zeile">
                            <span class="info-label"><?php esc_html_e('Service:', 'simple-appointment-booking'); ?></span>
                            <span class="info-value"><?php echo $simpbook_dienstleistung ? esc_html($simpbook_dienstleistung->name) : '-'; ?></span>
                        </div>
                        <?php
                        $simpbook_bo_name_karte = ($simpbook_bo_aktiv_liste && !empty($simpbook_reservierung->buchungsoption_id) && isset($simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id])) ? $simpbook_buchungsoptionen_cache[(int)$simpbook_reservierung->buchungsoption_id] : '';
                        if ($simpbook_bo_name_karte) : ?>
                        <div class="reservierung-info-zeile">
                            <span class="info-label"><?php esc_html_e('Booking Option:', 'simple-appointment-booking'); ?></span>
                            <span class="info-value"><?php echo esc_html($simpbook_bo_name_karte); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($simpbook_mitarbeiter) : ?>
                        <div class="reservierung-info-zeile">
                            <span class="info-label"><?php esc_html_e('Staff:', 'simple-appointment-booking'); ?></span>
                            <span class="info-value"><?php echo esc_html($simpbook_mitarbeiter->name); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="simpbook-export-section">
        <h3 class="wp-heading-inline"><?php esc_html_e('Export:', 'simple-appointment-booking'); ?></h3>
        <a href="<?php echo esc_url($simpbook_export_url); ?>" class="page-title-action"><?php esc_html_e('Export Reservations (CSV)', 'simple-appointment-booking'); ?></a>
        <hr class="wp-header-end">
    </div>

    <?php if ($simpbook_total_pages > 1 || $simpbook_total_items > 20) : ?>
        <div class="tablenav">
            <div class="tablenav-pages">
                <!-- Einträge pro Seite Dropdown -->
                <div class="per-page-selector" style="float: left; margin-right: 20px;">
                    <label for="simpbook-per-page-select" style="margin-right: 5px;">
                        <?php esc_html_e('Entries per page:', 'simple-appointment-booking'); ?>
                    </label>
                    <select id="simpbook-per-page-select" name="simpbook_per_page" style="width: auto;">
                        <option value="20" <?php selected($simpbook_per_page, 20); ?>>20</option>
                        <option value="40" <?php selected($simpbook_per_page, 40); ?>>40</option>
                        <option value="60" <?php selected($simpbook_per_page, 60); ?>>60</option>
                        <option value="100" <?php selected($simpbook_per_page, 100); ?>>100</option>
                    </select>
                </div>
                
                <span class="displaying-num"><?php echo esc_html($simpbook_total_items); ?> <?php esc_html_e('Entries', 'simple-appointment-booking'); ?></span>
                
                <?php if ($simpbook_total_pages > 1) : ?>
                    <span class="pagination-links">
                        <?php if ($simpbook_current_page > 1) : ?>
                            <a class="first-page button" href="<?php echo esc_url(add_query_arg(['simpbook_seite_nr' => 1, 'simpbook_filter' => $simpbook_filter, 'simpbook_order' => $simpbook_order, 'simpbook_direction' => $simpbook_direction, 'simpbook_per_page' => $simpbook_per_page, 'simpbook_search' => $simpbook_search], $simpbook_base_url)); ?>">«</a>
                            <a class="prev-page button" href="<?php echo esc_url(add_query_arg(['simpbook_seite_nr' => $simpbook_current_page - 1, 'simpbook_filter' => $simpbook_filter, 'simpbook_order' => $simpbook_order, 'simpbook_direction' => $simpbook_direction, 'simpbook_per_page' => $simpbook_per_page, 'simpbook_search' => $simpbook_search], $simpbook_base_url)); ?>">‹</a>
                        <?php endif; ?>

                        <span class="paging-input">
                            <span class="current-page"><?php echo esc_html($simpbook_current_page); ?></span> <?php esc_html_e('of', 'simple-appointment-booking'); ?>
                            <span class="total-pages"><?php echo esc_html($simpbook_total_pages); ?></span>
                        </span>

                        <?php if ($simpbook_current_page < $simpbook_total_pages) : ?>
                            <a class="next-page button" href="<?php echo esc_url(add_query_arg(['simpbook_seite_nr' => $simpbook_current_page + 1, 'simpbook_filter' => $simpbook_filter, 'simpbook_order' => $simpbook_order, 'simpbook_direction' => $simpbook_direction, 'simpbook_per_page' => $simpbook_per_page, 'simpbook_search' => $simpbook_search], $simpbook_base_url)); ?>">›</a>
                            <a class="last-page button" href="<?php echo esc_url(add_query_arg(['simpbook_seite_nr' => $simpbook_total_pages, 'simpbook_filter' => $simpbook_filter, 'simpbook_order' => $simpbook_order, 'simpbook_direction' => $simpbook_direction, 'simpbook_per_page' => $simpbook_per_page, 'simpbook_search' => $simpbook_search], $simpbook_base_url)); ?>">»</a>
                        <?php endif; ?>
                    </span>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
    </div> <!-- Ende simpbook-list-container -->
<?php endif; ?>

<div id="nachrichten-modal" class="modal" style="display:none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2><?php esc_html_e('Message to', 'simple-appointment-booking'); ?> <span id="empfaenger-name"></span></h2>
        <form id="nachrichten-form">
            <input type="hidden" id="empfaenger-email" name="simpbook_email">
            <?php wp_nonce_field('simpbook_sende_nachricht_action', 'nachricht_nonce'); ?>
            <div class="form-field">
                <label for="nachricht-betreff"><?php esc_html_e('Subject:', 'simple-appointment-booking'); ?></label>
                <input type="text" id="nachricht-betreff" name="betreff" required>
            </div>
            <div class="form-field">
                <label for="nachricht-text"><?php esc_html_e('Message:', 'simple-appointment-booking'); ?></label>
                <textarea id="nachricht-text" name="nachricht" rows="10" required></textarea>
            </div>
            <button type="submit" class="button button-primary"><?php esc_html_e('Send Message', 'simple-appointment-booking'); ?></button>
        </form>
    </div>
</div>
</div>