<?php
// admin/dienstleistungen.php
if (!defined('ABSPATH')) {
    exit;
}

simpbook_display_trial_notice_on_admin_pages();

global $wpdb;
$simpbook_table_name = $wpdb->prefix . 'dienstleistungen';

// Löschen
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if (isset($_GET['simpbook_aktion']) && $_GET['simpbook_aktion'] === 'loeschen' && isset($_GET['simpbook_id'])) {
    $simpbook_id = intval($_GET['simpbook_id']);
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (isset($_GET['simpbook_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['simpbook_nonce'])), 'simpbook_delete_dienstleistung_' . $simpbook_id)) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->delete($simpbook_table_name, ['id' => $simpbook_id], ['%d']);
        simpbook_pwa_redirect(admin_url('admin.php?page=simpbook-dienstleistungen&simpbook_nachricht=geloescht'));
    }
}

// Aktivieren/Deaktivieren
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if (isset($_GET['simpbook_aktion']) && in_array($_GET['simpbook_aktion'], ['aktivieren', 'deaktivieren'], true) && isset($_GET['simpbook_id'])) {
    $simpbook_id = intval($_GET['simpbook_id']);
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (isset($_GET['simpbook_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['simpbook_nonce'])), 'simpbook_toggle_dienstleistung_' . $simpbook_id)) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $simpbook_aktiv = $_GET['simpbook_aktion'] === 'aktivieren' ? 1 : 0;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update($simpbook_table_name, ['aktiv' => $simpbook_aktiv], ['id' => $simpbook_id], ['%d'], ['%d']);

        simpbook_pwa_redirect(admin_url('admin.php?page=simpbook-dienstleistungen&simpbook_nachricht=aktualisiert'));
    }
}

// Alle Dienstleistungen laden mit Sortierung
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_order_by = isset($_GET['simpbook_order']) ? sanitize_text_field(wp_unslash($_GET['simpbook_order'])) : 'sortierung';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_direction = isset($_GET['simpbook_direction']) ? sanitize_text_field(wp_unslash($_GET['simpbook_direction'])) : 'ASC';

// Erlaubte Sortierfelder
$simpbook_allowed_order = ['name', 'kategorie_id', 'dauer_minuten', 'preis', 'sortierung'];
if (!in_array($simpbook_order_by, $simpbook_allowed_order, true)) {
    $simpbook_order_by = 'sortierung';
}

// Erlaubte Sortierrichtungen
if (!in_array($simpbook_direction, ['ASC', 'DESC'], true)) {
    $simpbook_direction = 'ASC';
}

// SQL Query mit Sortierung
if ($simpbook_order_by === 'sortierung') {
    // Standard: Nach Sortierung, dann Name
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $simpbook_dienstleistungen = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}dienstleistungen ORDER BY sortierung ASC, name ASC");
} elseif ($simpbook_order_by === 'kategorie_id') {
    // Bei Kategorie: Erst nach Kategorie, dann nach Name innerhalb der Kategorie
    // Sortierrichtung ist bereits validiert (nur ASC oder DESC erlaubt)
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $simpbook_dienstleistungen = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}dienstleistungen ORDER BY COALESCE(kategorie_id, 999999) {$simpbook_direction}, name ASC");
} else {
    // Andere Felder normal sortieren
    // Sowohl order_by als auch direction sind bereits validiert
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $simpbook_dienstleistungen = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}dienstleistungen ORDER BY {$simpbook_order_by} {$simpbook_direction}");
}

// Buchungsoptionen-Feature aktiv?
$simpbook_bo_aktiv = get_option('simpbook_buchungsoptionen_aktiv', '0') === '1';

// Dienstleistungen mit zugewiesenen Buchungsoptionen ermitteln
$simpbook_dl_mit_optionen = [];
if ($simpbook_bo_aktiv) {
    $simpbook_dl_bo_tbl = $wpdb->prefix . 'simpbook_dienstleistung_buchungsoptionen';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $simpbook_dl_option_ids = $wpdb->get_col("SELECT DISTINCT dienstleistung_id FROM `{$simpbook_dl_bo_tbl}`");
    $simpbook_dl_mit_optionen = array_map('intval', (array) $simpbook_dl_option_ids);
}

// Nachrichten
// 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']));
    $simpbook_messages = [
        'gespeichert'  => esc_html__('Service successfully saved.', 'simple-appointment-booking'),
        'geloescht'    => esc_html__('Service successfully deleted.', 'simple-appointment-booking'),
        'aktualisiert' => esc_html__('Service successfully updated.', 'simple-appointment-booking'),
    ];
    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>';
    }
}
?>

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

    <?php if (empty($simpbook_dienstleistungen)) : ?>
        <!-- Wenn keine Dienstleistungen vorhanden: Einfacher Button -->
        <button type="button" id="add-new-service-btn" class="button button-primary" style="margin: 20px 0; padding: 10px 20px; font-size: 14px;">
            <span class="dashicons dashicons-plus-alt" style="margin-right: 5px; vertical-align: middle;"></span>
            <?php esc_html_e('Add New Service', 'simple-appointment-booking'); ?>
        </button>
        <div class="notice notice-info"><p><?php esc_html_e('No services available yet.', 'simple-appointment-booking'); ?></p></div>
    <?php else : ?>
        <!-- Wenn Dienstleistungen vorhanden: Action Buttons Container -->
        <div class="view-toggle-container">
            <button type="button" id="add-new-service-btn" class="page-title-action"><?php esc_html_e('Add New Service', 'simple-appointment-booking'); ?></button>
            
            <div class="reservierungen-search-container">
                <span class="dashicons dashicons-search"></span>
                <input type="text" 
                       id="dienstleistungen-search-input" 
                       placeholder="<?php esc_attr_e('Search for service...', 'simple-appointment-booking'); ?>"
                       aria-label="<?php esc_attr_e('Search services', 'simple-appointment-booking'); ?>">
                <button type="button" id="clear-search-btn-dienstleistungen" class="dashicons dashicons-no-alt" style="display: none;" aria-label="<?php esc_attr_e('Clear search', 'simple-appointment-booking'); ?>"></button>
            </div>
            
            <button type="button" id="toggle-view-btn" class="button button-secondary">
                <span class="dashicons dashicons-grid-view" style="margin-right: 5px; vertical-align: middle;"></span>
                <span id="toggle-view-text"><?php esc_html_e('Card View', 'simple-appointment-booking'); ?></span>
            </button>
        </div>

        <div class="simpbook-list-container">
            <!-- Desktop-Tabelle -->
            <div class="desktop-dienstleistungen-tabelle">
            <div style="overflow-x: auto; width: 100%;">
                <?php 
                // Kategorien für die Anzeige laden
                $simpbook_alle_kategorien = simpbook_get_all_kategorien();
                $simpbook_kategorien_map = array();
                $simpbook_kategorien_farben_map = array();
                foreach ($simpbook_alle_kategorien as $simpbook_kat) {
                    $simpbook_kategorien_map[$simpbook_kat->id] = $simpbook_kat->name;
                    $simpbook_kategorien_farben_map[$simpbook_kat->id] = $simpbook_kat->farbe ?? '#2271b1';
                }
                
                // Basis-URL für Sortierung
                $simpbook_base_url = simpbook_maybe_add_pwa_param(admin_url('admin.php?page=simpbook-dienstleistungen'));
                
                // Hilfsfunktion für Sortier-URLs
                function simpbook_dienstleistungen_sort_url($field, $current_order, $current_direction, $base_url) {
                    $new_direction = 'ASC';
                    if ($current_order === $field && $current_direction === 'ASC') {
                        $new_direction = 'DESC';
                    }
                    return add_query_arg(['simpbook_order' => $field, 'simpbook_direction' => $new_direction], $base_url);
                }
                
                // Sortier-Icon-Funktion
                function simpbook_dienstleistungen_sort_icon($field, $current_order, $current_direction) {
                    if ($current_order !== $field) {
                        return '<span class="dashicons dashicons-sort" style="font-size: 14px; vertical-align: middle; color: #ccc;"></span>';
                    }
                    $icon = $current_direction === 'ASC' ? 'dashicons-arrow-up-alt2' : 'dashicons-arrow-down-alt2';
                    return '<span class="dashicons ' . $icon . '" style="font-size: 14px; vertical-align: middle;"></span>';
                }

                $simpbook_allowed_icon_html = array(
                    'span' => array(
                        'class' => array(),
                        'style' => array(),
                    ),
                );
                ?>
                <table class="wp-list-table widefat fixed striped dienstleistungen-haupttabelle">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Image', 'simple-appointment-booking'); ?></th>
                            <th>
                                <a href="<?php echo esc_url(simpbook_dienstleistungen_sort_url('name', $simpbook_order_by, $simpbook_direction, $simpbook_base_url)); ?>" style="text-decoration: none; color: inherit;">
                                    <?php esc_html_e('Name', 'simple-appointment-booking'); ?>
                                    <?php echo wp_kses(simpbook_dienstleistungen_sort_icon('name', $simpbook_order_by, $simpbook_direction), $simpbook_allowed_icon_html); ?>
                                </a>
                            </th>
                            <th>
                                <a href="<?php echo esc_url(simpbook_dienstleistungen_sort_url('kategorie_id', $simpbook_order_by, $simpbook_direction, $simpbook_base_url)); ?>" style="text-decoration: none; color: inherit;">
                                    <?php esc_html_e('Category', 'simple-appointment-booking'); ?>
                                    <?php echo wp_kses(simpbook_dienstleistungen_sort_icon('kategorie_id', $simpbook_order_by, $simpbook_direction), $simpbook_allowed_icon_html); ?>
                                </a>
                            </th>
                            <th>
                                <a href="<?php echo esc_url(simpbook_dienstleistungen_sort_url('dauer_minuten', $simpbook_order_by, $simpbook_direction, $simpbook_base_url)); ?>" style="text-decoration: none; color: inherit;">
                                    <?php esc_html_e('Duration', 'simple-appointment-booking'); ?>
                                    <?php echo wp_kses(simpbook_dienstleistungen_sort_icon('dauer_minuten', $simpbook_order_by, $simpbook_direction), $simpbook_allowed_icon_html); ?>
                                </a>
                            </th>
                            <th>
                                <a href="<?php echo esc_url(simpbook_dienstleistungen_sort_url('preis', $simpbook_order_by, $simpbook_direction, $simpbook_base_url)); ?>" style="text-decoration: none; color: inherit;">
                                    <?php esc_html_e('Price', 'simple-appointment-booking'); ?>
                                    <?php echo wp_kses(simpbook_dienstleistungen_sort_icon('preis', $simpbook_order_by, $simpbook_direction), $simpbook_allowed_icon_html); ?>
                                </a>
                            </th>
                            <th><?php esc_html_e('Status', 'simple-appointment-booking'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($simpbook_dienstleistungen as $simpbook_dienstleistung) : ?>
                            <tr class="dienstleistung-row-clickable"
                                data-dienstleistung-id="<?php echo esc_attr($simpbook_dienstleistung->id); ?>"
                                data-toggle-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_toggle_dienstleistung_' . $simpbook_dienstleistung->id)); ?>"
                                data-delete-nonce="<?php echo esc_attr(wp_create_nonce('delete_dienstleistung_' . $simpbook_dienstleistung->id)); ?>"
                                data-dienstleistung-data="<?php echo esc_attr(wp_json_encode([
                                    'id' => $simpbook_dienstleistung->id,
                                    'name' => $simpbook_dienstleistung->name,
                                    'dauer_minuten' => $simpbook_dienstleistung->dauer_minuten,
                                    'pufferzeit_minuten' => $simpbook_dienstleistung->pufferzeit_minuten,
                                    'beschreibung' => $simpbook_dienstleistung->beschreibung,
                                    'aktiv' => $simpbook_dienstleistung->aktiv,
                                    'sortierung' => $simpbook_dienstleistung->sortierung,
                                    'preis' => isset($simpbook_dienstleistung->preis) ? $simpbook_dienstleistung->preis : '',
                                    'preis_anzeigen' => isset($simpbook_dienstleistung->preis_anzeigen) ? $simpbook_dienstleistung->preis_anzeigen : 0,
                                    'bild_id' => isset($simpbook_dienstleistung->bild_id) ? $simpbook_dienstleistung->bild_id : 0,
                                    'kategorie_id' => isset($simpbook_dienstleistung->kategorie_id) ? $simpbook_dienstleistung->kategorie_id : '',
                                    'ohne_mitarbeiter' => isset($simpbook_dienstleistung->ohne_mitarbeiter) ? (int) $simpbook_dienstleistung->ohne_mitarbeiter : 0,
                                    'verfuegbarkeit' => isset($simpbook_dienstleistung->verfuegbarkeit) && !empty($simpbook_dienstleistung->verfuegbarkeit) ? json_decode($simpbook_dienstleistung->verfuegbarkeit, true) : ['type' => 'regular', 'weekday_times' => [], 'special_dates' => []],
                                ])); ?>"
                                style="cursor: pointer;">
                                <td>
                                    <?php
                                    if (isset($simpbook_dienstleistung->bild_id) && $simpbook_dienstleistung->bild_id > 0) {
                                        $simpbook_bild_url = wp_get_attachment_url($simpbook_dienstleistung->bild_id);
                                        if ($simpbook_bild_url) {
                                            echo '<img src="' . esc_url($simpbook_bild_url) . '" alt="' . esc_attr($simpbook_dienstleistung->name) . '" style="max-height: 60px; max-width: 60px; object-fit: cover;">';
                                        }
                                    }
                                    ?>
                                </td>
                                <td><strong><?php echo esc_html($simpbook_dienstleistung->name); ?></strong></td>
                                <td>
                                    <?php 
                                    if (isset($simpbook_dienstleistung->kategorie_id) && $simpbook_dienstleistung->kategorie_id > 0 && isset($simpbook_kategorien_map[$simpbook_dienstleistung->kategorie_id])) {
                                        $simpbook_badge_color = isset($simpbook_kategorien_farben_map[$simpbook_dienstleistung->kategorie_id]) ? $simpbook_kategorien_farben_map[$simpbook_dienstleistung->kategorie_id] : '#2271b1';
                                        echo '<span class="simpbook-kategorie-badge" style="background-color: ' . esc_attr($simpbook_badge_color) . ';">' . esc_html($simpbook_kategorien_map[$simpbook_dienstleistung->kategorie_id]) . '</span>';
                                    } else {
                                        echo '—';
                                    }
                                    ?>
                                </td>
                                <td><?php
                                    if ($simpbook_bo_aktiv && in_array((int) $simpbook_dienstleistung->id, $simpbook_dl_mit_optionen, true)) {
                                        echo '<span style="color:#666; font-style:italic;">' . esc_html__('Depending on booking option', 'simple-appointment-booking') . '</span>';
                                    } else {
                                        echo esc_html($simpbook_dienstleistung->dauer_minuten) . ' ';
                                        esc_html_e('Min.', 'simple-appointment-booking');
                                    }
                                ?></td>
                                <td><?php
                                    if ($simpbook_bo_aktiv && in_array((int) $simpbook_dienstleistung->id, $simpbook_dl_mit_optionen, true)) {
                                        echo '<span style="color:#666; font-style:italic;">' . esc_html__('Depending on booking option', 'simple-appointment-booking') . '</span>';
                                    } else {
                                        echo isset($simpbook_dienstleistung->preis) && !empty($simpbook_dienstleistung->preis) ? esc_html($simpbook_dienstleistung->preis) : '—';
                                    }
                                ?></td>
                                <td>
                                    <?php if ($simpbook_dienstleistung->aktiv) : ?>
                                        <span style="color: #46b450;"><?php esc_html_e('Active', 'simple-appointment-booking'); ?></span>
                                    <?php else : ?>
                                        <span style="color: #dc3232;"><?php esc_html_e('Inactive', 'simple-appointment-booking'); ?></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Mobile/Tablet Kartenansicht - Gruppiert nach Kategorie -->
        <div class="mobile-dienstleistungen-karten">
            <?php 
            // Dienstleistungen nach Kategorien gruppieren
            $simpbook_gruppierte_dl = simpbook_get_dienstleistungen_grouped_for_frontend(false); // false = alle (nicht nur aktive)
            
            foreach ($simpbook_gruppierte_dl as $simpbook_gruppe) : 
                $simpbook_kategorie = $simpbook_gruppe['kategorie'];
                $simpbook_gruppe_dls = $simpbook_gruppe['dienstleistungen'];
            ?>
                <?php if ($simpbook_kategorie !== null) : ?>
                    <div class="dienstleistung-kategorie-header" style="border-left: 4px solid <?php echo esc_attr($simpbook_kategorie->farbe ?? '#2271b1'); ?>;">
                        <h3><?php echo esc_html($simpbook_kategorie->name); ?></h3>
                    </div>
                <?php elseif (count($simpbook_gruppierte_dl) > 1) : ?>
                    <div class="dienstleistung-kategorie-header">
                        <h3><?php esc_html_e('Ohne Gruppierung', 'simple-appointment-booking'); ?></h3>
                    </div>
                <?php endif; ?>
                
                <div class="dienstleistung-karten-gruppe" data-kategorie-id="<?php echo esc_attr($simpbook_kategorie !== null ? $simpbook_kategorie->id : '0'); ?>">
                <?php foreach ($simpbook_gruppe_dls as $simpbook_dienstleistung) : ?>
                    <div class="dienstleistung-karte dienstleistung-karte-clickable"
                        data-dienstleistung-id="<?php echo esc_attr($simpbook_dienstleistung->id); ?>"
                        data-toggle-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_toggle_dienstleistung_' . $simpbook_dienstleistung->id)); ?>"
                        data-delete-nonce="<?php echo esc_attr(wp_create_nonce('delete_dienstleistung_' . $simpbook_dienstleistung->id)); ?>"
                        data-dienstleistung-data="<?php echo esc_attr(wp_json_encode([
                            'id' => $simpbook_dienstleistung->id,
                            'name' => $simpbook_dienstleistung->name,
                            'dauer_minuten' => $simpbook_dienstleistung->dauer_minuten,
                            'pufferzeit_minuten' => $simpbook_dienstleistung->pufferzeit_minuten,
                            'beschreibung' => $simpbook_dienstleistung->beschreibung,
                            'aktiv' => $simpbook_dienstleistung->aktiv,
                            'sortierung' => $simpbook_dienstleistung->sortierung,
                            'preis' => isset($simpbook_dienstleistung->preis) ? $simpbook_dienstleistung->preis : '',
                            'preis_anzeigen' => isset($simpbook_dienstleistung->preis_anzeigen) ? $simpbook_dienstleistung->preis_anzeigen : 0,
                            'bild_id' => isset($simpbook_dienstleistung->bild_id) ? $simpbook_dienstleistung->bild_id : 0,
                            'kategorie_id' => isset($simpbook_dienstleistung->kategorie_id) ? $simpbook_dienstleistung->kategorie_id : '',
                            'ohne_mitarbeiter' => isset($simpbook_dienstleistung->ohne_mitarbeiter) ? (int) $simpbook_dienstleistung->ohne_mitarbeiter : 0,
                            'verfuegbarkeit' => isset($simpbook_dienstleistung->verfuegbarkeit) && !empty($simpbook_dienstleistung->verfuegbarkeit) ? json_decode($simpbook_dienstleistung->verfuegbarkeit, true) : ['type' => 'regular', 'weekday_times' => [], 'special_dates' => []],
                        ])); ?>"
                        style="cursor: pointer;">
                        <div class="simpbook-karte-actions">
                            <button class="simpbook-duplicate-btn" title="<?php esc_attr_e('Duplicate service', 'simple-appointment-booking'); ?>" aria-label="<?php esc_attr_e('Duplicate service', 'simple-appointment-booking'); ?>" data-dienstleistung-id="<?php echo esc_attr($simpbook_dienstleistung->id); ?>" data-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_duplicate_dienstleistung_' . $simpbook_dienstleistung->id)); ?>">
                                <span class="dashicons dashicons-admin-page"></span>
                            </button>
                            <button class="simpbook-drag-handle" title="<?php esc_attr_e('Change order', 'simple-appointment-booking'); ?>" aria-label="<?php esc_attr_e('Change order', 'simple-appointment-booking'); ?>">
                                <span class="dashicons dashicons-move"></span>
                            </button>
                        </div>
                        <div class="dienstleistung-karte-bild">
                            <?php
                            if (isset($simpbook_dienstleistung->bild_id) && $simpbook_dienstleistung->bild_id > 0) {
                                $simpbook_bild_url = wp_get_attachment_url($simpbook_dienstleistung->bild_id);
                                if ($simpbook_bild_url) {
                                    echo '<img src="' . esc_url($simpbook_bild_url) . '" alt="' . esc_attr($simpbook_dienstleistung->name) . '" style="width: 100%; height: 100%; object-fit: cover;">';
                                }
                            }
                            ?>
                        </div>

                        <div class="dienstleistung-karte-body">
                            <div class="dienstleistung-name"><?php echo esc_html($simpbook_dienstleistung->name); ?></div>
                            <div class="dienstleistung-info-gruppe">
                                <div class="dienstleistung-info-zeile">
                                    <span class="info-label"><?php esc_html_e('Duration:', 'simple-appointment-booking'); ?></span>
                                    <span class="info-value"><?php
                                        if ($simpbook_bo_aktiv && in_array((int) $simpbook_dienstleistung->id, $simpbook_dl_mit_optionen, true)) {
                                            echo '<span style="color:#666; font-style:italic;">' . esc_html__('Depending on booking option', 'simple-appointment-booking') . '</span>';
                                        } else {
                                            echo esc_html($simpbook_dienstleistung->dauer_minuten) . ' ';
                                            esc_html_e('Min.', 'simple-appointment-booking');
                                        }
                                    ?></span>
                                </div>
                                <div class="dienstleistung-info-zeile">
                                    <span class="info-label"><?php esc_html_e('Status:', 'simple-appointment-booking'); ?></span>
                                    <span class="info-value">
                                        <?php if ($simpbook_dienstleistung->aktiv) : ?>
                                            <span style="color: #46b450;"><?php esc_html_e('Active', 'simple-appointment-booking'); ?></span>
                                        <?php else : ?>
                                            <span style="color: #dc3232;"><?php esc_html_e('Inactive', 'simple-appointment-booking'); ?></span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>
        </div> <!-- Ende simpbook-list-container -->
    <?php endif; ?>
</div>

<!-- Modal für Dienstleistungsdetails -->
<div id="dienstleistung-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 id="modal-title"><?php esc_html_e('Edit Service', '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">
            <form id="dienstleistung-edit-form" method="post" action="<?php echo esc_attr(simpbook_get_form_action()); ?>">
                <?php wp_nonce_field('simpbook_dienstleistung_speichern', 'dienstleistung_nonce'); ?>
                <input type="hidden" id="dienstleistung-edit-id" name="simpbook_dienstleistung_id" value="">

                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="edit-name"><?php esc_html_e('Name *', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input name="simpbook_name" type="text" id="edit-name" class="regular-text" required>
                            <p class="description"><?php esc_html_e('Name of the service (e.g. "Haircut", "Massage")', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit-kategorie_id"><?php esc_html_e('Category/Group', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <div style="display: flex; gap: 10px; align-items: center;">
                                <select name="simpbook_kategorie_id" id="edit-kategorie_id" class="regular-text">
                                    <option value=""><?php esc_html_e('— Keine Gruppierung —', 'simple-appointment-booking'); ?></option>
                                    <?php
                                    $simpbook_kategorien_list = simpbook_get_all_kategorien();
                                    foreach ($simpbook_kategorien_list as $simpbook_kat) :
                                    ?>
                                        <option value="<?php echo esc_attr($simpbook_kat->id); ?>">
                                            <?php echo esc_html($simpbook_kat->name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=simpbook-gruppierungen')); ?>" class="button button-small" target="_blank" title="<?php esc_attr_e('Gruppierungen verwalten', 'simple-appointment-booking'); ?>">
                                    <span class="dashicons dashicons-plus-alt2" style="vertical-align: middle;"></span>
                                </a>
                            </div>
                            <p class="description"><?php esc_html_e('Ordnen Sie die Dienstleistung einer Gruppierung zu (optional)', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <?php if (!$simpbook_bo_aktiv) : ?>
                    <tr>
                        <th scope="row"><label for="edit-dauer_minuten"><?php esc_html_e('Duration (Minutes) *', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input name="simpbook_dauer_minuten" type="number" id="edit-dauer_minuten" min="5" max="480" step="5" class="small-text" required>
                            <p class="description"><?php esc_html_e('Duration of the service in minutes', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th scope="row"><label for="edit-pufferzeit_minuten"><?php esc_html_e('Buffer Time (Minutes)', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input name="simpbook_pufferzeit_minuten" type="number" id="edit-pufferzeit_minuten" min="0" max="60" step="5" class="small-text">
                            <p class="description"><?php esc_html_e('Buffer time after the service (e.g. for cleaning, preparation). This time is used in addition to the duration for blocking.', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit-beschreibung"><?php esc_html_e('Description', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <textarea name="simpbook_beschreibung" id="edit-beschreibung" rows="5" cols="50" class="large-text"></textarea>
                            <p class="description"><?php esc_html_e('Optional description of the service', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit-upload-image"><?php esc_html_e('Image', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <div id="edit-bild-preview" style="margin-bottom: 10px;">
                                <img id="edit-bild-img" src="" alt="<?php esc_attr_e('Preview', 'simple-appointment-booking'); ?>" style="max-width: 200px; display: none; margin-bottom: 10px;">
                            </div>
                            <input type="hidden" name="simpbook_bild_id" id="edit-bild_id" value="">
                            <button type="button" id="edit-upload-image" class="button button-primary">
                                <span class="dashicons dashicons-format-image"></span> <?php esc_html_e('Upload Image', 'simple-appointment-booking'); ?>
                            </button>
                            <button type="button" id="edit-remove-image" class="button button-remove-image" style="margin-left: 5px; display: none;">
                                <span class="dashicons dashicons-trash"></span> <?php esc_html_e('Remove', 'simple-appointment-booking'); ?>
                            </button>
                            <p class="description"><?php esc_html_e('Image for the service in the booking view (optional)', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <?php if ($simpbook_bo_aktiv) : ?>
                    <tr id="row-buchungsoptionen">
                        <th scope="row"><?php esc_html_e('Booking Options', 'simple-appointment-booking'); ?></th>
                        <td>
                            <div id="buchungsoptionen-container">
                                <p class="description" style="font-style: italic; color: #999;"><?php esc_html_e('Loading options...', 'simple-appointment-booking'); ?></p>
                            </div>
                            <div style="margin-top: 10px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                                <button type="button" id="add-buchungsoption-row-btn" class="button button-small">
                                    <span class="dashicons dashicons-plus-alt2" style="vertical-align: middle; font-size: 14px;"></span>
                                    <?php esc_html_e('Add Option', 'simple-appointment-booking'); ?>
                                </button>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=simpbook-buchungsoptionen')); ?>" class="button button-small" target="_blank" title="<?php esc_attr_e('Manage Options', 'simple-appointment-booking'); ?>">
                                    <span class="dashicons dashicons-admin-settings" style="vertical-align: middle; font-size: 14px;"></span>
                                    <?php esc_html_e('Manage Options', 'simple-appointment-booking'); ?>
                                </a>
                            </div>
                            <p class="description"><?php esc_html_e('Select from the global booking options and set individual prices.', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <?php if (!$simpbook_bo_aktiv) : ?>
                    <tr>
                        <th scope="row"><label for="edit-preis"><?php esc_html_e('Price', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input name="simpbook_preis" type="text" id="edit-preis" class="regular-text" placeholder="<?php esc_attr_e('e.g. 49.99', 'simple-appointment-booking'); ?>">
                            <p class="description"><?php esc_html_e('Price for this service (optional)', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Show price in frontend', 'simple-appointment-booking'); ?></th>
                        <td>
                            <label for="edit-preis_anzeigen">
                                <input name="simpbook_preis_anzeigen" type="checkbox" id="edit-preis_anzeigen" value="1">
                                <?php esc_html_e('Show price in booking form', 'simple-appointment-booking'); ?>
                            </label>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Staff', 'simple-appointment-booking'); ?></th>
                        <td>
                            <div style="margin-bottom: 10px;">
                                <label for="edit-ohne-mitarbeiter" style="display: flex; align-items: center; gap: 6px; cursor: pointer; font-weight: 500;">
                                    <input name="simpbook_ohne_mitarbeiter" type="checkbox" id="edit-ohne-mitarbeiter" value="1">
                                    <?php esc_html_e('Service without Staff', 'simple-appointment-booking'); ?>
                                </label>
                                <p class="description" style="margin-top: 4px;"><?php esc_html_e('Enable if no staff member is required for this service (e.g. rental, room hire).', 'simple-appointment-booking'); ?></p>
                            </div>
                            <div id="dienstleistung-mitarbeiter-list" style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; border-radius: 4px;">
                                <p style="text-align: center; color: #999;"><?php esc_html_e('Loading staff...', 'simple-appointment-booking'); ?></p>
                            </div>
                            <p class="description"><?php esc_html_e('Select the staff members who offer this service.', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Availability', 'simple-appointment-booking'); ?></th>
                        <td>
                            <div class="simpbook-avail-option-wrap">
                                <label class="simpbook-avail-option-label active">
                                    <input type="radio" name="simpbook_verfuegbarkeit_type" value="regular" checked class="simpbook-avail-radio">
                                    <?php esc_html_e('Regular Opening Hours', 'simple-appointment-booking'); ?>
                                </label>
                                <label class="simpbook-avail-option-label">
                                    <input type="radio" name="simpbook_verfuegbarkeit_type" value="weekdays" class="simpbook-avail-radio">
                                    <?php esc_html_e('Special Opening Hours', 'simple-appointment-booking'); ?>
                                </label>
                                <label class="simpbook-avail-option-label">
                                    <input type="radio" name="simpbook_verfuegbarkeit_type" value="special_dates" class="simpbook-avail-radio">
                                    <?php esc_html_e('Special Appointments', 'simple-appointment-booking'); ?>
                                </label>
                            </div>
                            <!-- Wochentage -->
                            <div class="simpbook-avail-weekdays" style="display:none;">
                                <div class="simpbook-weekday-grid">
                                    <?php
                                    $simpbook_days_map = [
                                        '1' => __('Mon', 'simple-appointment-booking'),
                                        '2' => __('Tu', 'simple-appointment-booking'),
                                        '3' => __('We', 'simple-appointment-booking'),
                                        '4' => __('Th', 'simple-appointment-booking'),
                                        '5' => __('Fri', 'simple-appointment-booking'),
                                        '6' => __('Sat', 'simple-appointment-booking'),
                                        '7' => __('Su', 'simple-appointment-booking'),
                                    ];
                                    foreach ($simpbook_days_map as $simpbook_day_num => $simpbook_day_label) : ?>
                                    <div class="simpbook-weekday-item">
                                        <label class="simpbook-weekday-check-label">
                                            <input type="checkbox" class="simpbook-weekday-checkbox" name="simpbook_weekday_times[<?php echo esc_attr($simpbook_day_num); ?>][enabled]" value="1">
                                            <span><?php echo esc_html($simpbook_day_label); ?></span>
                                        </label>
                                        <div class="simpbook-weekday-item-times">
                                            <span><?php esc_html_e('From', 'simple-appointment-booking'); ?></span>
                                            <input type="time" name="simpbook_weekday_times[<?php echo esc_attr($simpbook_day_num); ?>][time_from]" value="09:00" class="simpbook-time-input" disabled>
                                            <span><?php esc_html_e('To', 'simple-appointment-booking'); ?></span>
                                            <input type="time" name="simpbook_weekday_times[<?php echo esc_attr($simpbook_day_num); ?>][time_to]" value="17:00" class="simpbook-time-input" disabled>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <!-- Spezielle Termine -->
                            <div class="simpbook-avail-special" style="display:none;">
                                <div class="simpbook-avail-special-datepicker-wrap">
                                    <input type="text" class="simpbook-avail-special-datepicker" readonly placeholder="<?php esc_attr_e('Select date…', 'simple-appointment-booking'); ?>">
                                    <button type="button" class="button button-secondary simpbook-add-avail-special-date">
                                        + <?php esc_html_e('Add appointment', 'simple-appointment-booking'); ?>
                                    </button>
                                </div>
                                <div class="simpbook-avail-special-dates-list"></div>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Status', 'simple-appointment-booking'); ?></th>
                        <td>
                            <label for="edit-aktiv">
                                <input name="simpbook_aktiv" type="checkbox" id="edit-aktiv" value="1">
                                <?php esc_html_e('Active (displayed in frontend)', 'simple-appointment-booking'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit-sortierung"><?php esc_html_e('Sort Order', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input name="simpbook_sortierung" type="number" id="edit-sortierung" min="0" step="1" class="small-text">
                            <p class="description"><?php esc_html_e('Lower numbers are displayed first. If the number is the same, it is sorted alphabetically.', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                </table>

                <div class="reservierung-modal-footer">
                    <div id="modal-delete-section">
                        <button type="button" id="dienstleistung-delete" class="button button-small button-link-delete">
                            <span class="dashicons dashicons-trash"></span> <?php esc_html_e('Delete', 'simple-appointment-booking'); ?>
                        </button>
                    </div>
                    <div>
                        <button type="button" class="button reservierung-modal-close" style="margin-right: 10px;"><?php esc_html_e('Cancel', 'simple-appointment-booking'); ?></button>
                        <button type="submit" name="simpbook_dienstleistung_speichern" class="button reservierung-modal-save" id="modal-save-btn"><?php esc_html_e('Save', 'simple-appointment-booking'); ?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>





