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

// Wochentage als Array für JavaScript und PHP
$simpbook_wochentage_keys = ['sonntag', 'montag', 'dienstag', 'mittwoch', 'donnerstag', 'freitag', 'samstag'];

// Tagesweise Einstellungen aus der Datenbank laden
$simpbook_wochentag_zeiten = get_option('simpbook_wochentag_zeiten', []);
$simpbook_intervall = get_option('simpbook_intervall', 30);

// Standardwerte falls noch keine Einstellungen vorhanden
$simpbook_standard_beginn = '11:00';
$simpbook_standard_ende = '22:00';

// Stellen Sie sicher, dass für jeden Wochentag Werte vorhanden sind
foreach ($simpbook_wochentage_keys as $simpbook_tag_key) {
    if (!isset($simpbook_wochentag_zeiten[$simpbook_tag_key])) {
        $simpbook_wochentag_zeiten[$simpbook_tag_key] = [
            'aktiv' => '1',
            'beginn' => $simpbook_standard_beginn,
            'ende' => $simpbook_standard_ende
        ];
    } else {
        // Sicherstellen, dass alle Keys existieren
        if (!isset($simpbook_wochentag_zeiten[$simpbook_tag_key]['aktiv'])) $simpbook_wochentag_zeiten[$simpbook_tag_key]['aktiv'] = '1';
        if (!isset($simpbook_wochentag_zeiten[$simpbook_tag_key]['beginn'])) $simpbook_wochentag_zeiten[$simpbook_tag_key]['beginn'] = $simpbook_standard_beginn;
        if (!isset($simpbook_wochentag_zeiten[$simpbook_tag_key]['ende'])) $simpbook_wochentag_zeiten[$simpbook_tag_key]['ende'] = $simpbook_standard_ende;
    }
}

// Ausgeschlossene Tage laden
$simpbook_ausgeschlossene_tage = get_option('simpbook_ausgeschlossene_tage', '');
$simpbook_ausgeschlossene_tage_array = [];
if (!empty($simpbook_ausgeschlossene_tage)) {
    $simpbook_dates = explode("\n", str_replace("\r", "", $simpbook_ausgeschlossene_tage));
    foreach ($simpbook_dates as $simpbook_date) {
        $simpbook_trimmed_date = trim($simpbook_date);
        if (!empty($simpbook_trimmed_date)) {
            $simpbook_date_obj = DateTime::createFromFormat('Y-m-d', $simpbook_trimmed_date);
            if ($simpbook_date_obj !== false) {
                $simpbook_ausgeschlossene_tage_array[] = $simpbook_trimmed_date; // Bereits imYYYY-MM-DD Format
            }
        }
    }
}

// Buchungsoptionen für alle aktiven Dienstleistungen laden (wenn Feature aktiv)
$simpbook_bo_aktiv_frontend = get_option('simpbook_buchungsoptionen_aktiv', '0') === '1';
$simpbook_service_buchungsoptionen = [];
if ($simpbook_bo_aktiv_frontend) {
    global $wpdb;
    $simpbook_dl_bo_table = $wpdb->prefix . 'simpbook_dienstleistung_buchungsoptionen';
    $simpbook_bo_table    = $wpdb->prefix . 'simpbook_buchungsoptionen';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $simpbook_alle_dl_optionen = $wpdb->get_results(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        "SELECT dbo.dienstleistung_id, dbo.buchungsoption_id, dbo.preis, bo.name, bo.dauer_minuten
         FROM {$simpbook_dl_bo_table} dbo
         JOIN {$simpbook_bo_table} bo ON dbo.buchungsoption_id = bo.id
         ORDER BY dbo.sortierung ASC"
    );
    foreach ($simpbook_alle_dl_optionen as $simpbook_opt) {
        $simpbook_service_buchungsoptionen[ (int) $simpbook_opt->dienstleistung_id ][] = [
            'buchungsoption_id' => (int) $simpbook_opt->buchungsoption_id,
            'name'              => $simpbook_opt->name,
            'dauer_minuten'     => (int) $simpbook_opt->dauer_minuten,
            'preis'             => $simpbook_opt->preis,
        ];
    }
}

?>
<div class="reservierung-container">
    <div class="reservierung-steps">
        <div class="reservierung-step active" data-step="1">1
            <span class="reservierung-step-label"><?php esc_html_e('Service', 'simple-appointment-booking'); ?></span>
        </div>
        <div class="reservierung-step" data-step="2">2
            <span class="reservierung-step-label" id="step2-label"><?php esc_html_e('Date & Employee', 'simple-appointment-booking'); ?></span>
        </div>
        <div class="reservierung-step" data-step="3">3
            <span class="reservierung-step-label"><?php esc_html_e('Details', 'simple-appointment-booking'); ?></span>
        </div>
        <div class="reservierung-step" data-step="4">4
            <span class="reservierung-step-label"><?php esc_html_e('Confirmation', 'simple-appointment-booking'); ?></span>
        </div>
    </div>

    <div class="reservierung-nachricht"></div>

    <form id="reservierung-formular" method="post">
        <div class="reservierung-form-step active" data-step="1">
            <!-- Dienstleistungs-Auswahl -->
            <div class="form-gruppe">
                <h4 class="form-section-header"><?php echo esc_html(simpbook_get_form_header('service')); ?></h4>
                <div class="service-selection-container" id="service-selection">
                    <?php
                    // Alle aktiven Dienstleistungen gruppiert nach Kategorie laden
                    if (!empty($simpbook_shortcode_kategorie_filter ?? '')) {
                        $simpbook_gruppierte_dienstleistungen = simpbook_get_dienstleistungen_grouped_by_kategorie_filter($simpbook_shortcode_kategorie_filter);
                    } else {
                        $simpbook_gruppierte_dienstleistungen = simpbook_get_dienstleistungen_grouped_for_frontend(true);
                    }

                    if (empty($simpbook_gruppierte_dienstleistungen)) : ?>
                        <div class="service-selection-grid">
                            <div class="service-card disabled"><?php esc_html_e('No services available', 'simple-appointment-booking'); ?></div>
                        </div>
                    <?php else : ?>
                        <?php
                        // Prüfe ob es gruppierte Dienstleistungen gibt (für Trennüberschrift)
                        $simpbook_hat_gruppierte_dl = false;
                        foreach ($simpbook_gruppierte_dienstleistungen as $simpbook_gruppe_check) {
                            if ($simpbook_gruppe_check['kategorie'] !== null) {
                                $simpbook_hat_gruppierte_dl = true;
                                break;
                            }
                        }
                        ?>
                        <?php foreach ($simpbook_gruppierte_dienstleistungen as $simpbook_gruppe) : ?>
                            <?php if ($simpbook_gruppe['kategorie'] !== null) : ?>
                                <div class="service-category-group">
                                    <?php if (empty($simpbook_shortcode_kategorie_filter ?? '')) : ?>
                                        <h5 class="service-category-header"><?php echo esc_html($simpbook_gruppe['kategorie']->name); ?></h5>
                                    <?php endif; ?>
                            <?php elseif ($simpbook_hat_gruppierte_dl) : ?>
                                <div class="service-category-group">
                                    <h5 class="service-category-header"><?php echo esc_html(simpbook_get_form_header('ungrouped_services')); ?></h5>
                            <?php endif; ?>

                            <div class="service-selection-grid">
                                <?php foreach ($simpbook_gruppe['dienstleistungen'] as $simpbook_dienstleistung) : ?>
                                    <div class="service-card"
                                        data-service-id="<?php echo esc_attr($simpbook_dienstleistung->id); ?>"
                                        data-service-name="<?php echo esc_attr($simpbook_dienstleistung->name); ?>"
                                        data-service-duration="<?php echo esc_attr($simpbook_dienstleistung->dauer_minuten); ?>"
                                        data-service-price="<?php echo esc_attr(isset($simpbook_dienstleistung->preis) ? $simpbook_dienstleistung->preis : ''); ?>"
                                        data-service-price-show="<?php echo esc_attr(isset($simpbook_dienstleistung->preis_anzeigen) ? $simpbook_dienstleistung->preis_anzeigen : 0); ?>"
                                        data-service-image="<?php echo esc_attr(isset($simpbook_dienstleistung->bild_id) && $simpbook_dienstleistung->bild_id ? wp_get_attachment_url($simpbook_dienstleistung->bild_id) : ''); ?>"
                                        data-service-description="<?php echo isset($simpbook_dienstleistung->beschreibung) && !empty($simpbook_dienstleistung->beschreibung) ? esc_attr($simpbook_dienstleistung->beschreibung) : ''; ?>"
                                        data-service-options="<?php echo esc_attr(wp_json_encode($simpbook_service_buchungsoptionen[ (int) $simpbook_dienstleistung->id ] ?? [])); ?>"
                                        data-service-ohne-mitarbeiter="<?php echo esc_attr(isset($simpbook_dienstleistung->ohne_mitarbeiter) ? (int) $simpbook_dienstleistung->ohne_mitarbeiter : 0); ?>"
                                        data-service-verfuegbarkeit="<?php echo esc_attr(isset($simpbook_dienstleistung->verfuegbarkeit) && !empty($simpbook_dienstleistung->verfuegbarkeit) ? $simpbook_dienstleistung->verfuegbarkeit : '{"type":"regular","weekday_times":{},"special_dates":[]}'); ?>">
                                        <div class="service-card-content">
                                            <?php
                                            // Zeige Bild als Kreis, wenn vorhanden
                                            if (isset($simpbook_dienstleistung->bild_id) && $simpbook_dienstleistung->bild_id > 0) :
                                                $simpbook_image_url = wp_get_attachment_url($simpbook_dienstleistung->bild_id);
                                                if ($simpbook_image_url) : ?>
                                                    <div class="service-photo-wrapper">
                                                        <img src="<?php echo esc_url($simpbook_image_url); ?>" alt="<?php echo esc_attr($simpbook_dienstleistung->name); ?>" class="service-photo">
                                                    </div>
                                                <?php endif;
                                            endif;
                                            ?>
                                            <div class="service-card-info">
                                                <div class="service-name"><?php echo esc_html($simpbook_dienstleistung->name); ?></div>
                                                <?php
                                                $simpbook_dl_options      = $simpbook_service_buchungsoptionen[ (int) $simpbook_dienstleistung->id ] ?? [];
                                                $simpbook_dl_option_count = count($simpbook_dl_options);

                                                if ($simpbook_dl_option_count >= 2) :
                                                    // Mehrere Optionen: Uhr-Icon + Anzahl
                                                    if (get_option('simpbook_dauer_anzeigen', '1') === '1') : ?>
                                                        <div class="service-duration">
                                                            <svg class="service-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                                                                <polyline points="12 6 12 12 16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                                                            </svg>
                                                            <span><?php echo esc_html($simpbook_dl_option_count); ?> <?php esc_html_e('Options', 'simple-appointment-booking'); ?></span>
                                                        </div>
                                                    <?php endif;

                                                elseif ($simpbook_dl_option_count === 1) :
                                                    // Genau eine Option: Dauer und Preis der Option anzeigen
                                                    if (get_option('simpbook_dauer_anzeigen', '1') === '1') : ?>
                                                        <div class="service-duration">
                                                            <svg class="service-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                                                                <polyline points="12 6 12 12 16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                                                            </svg>
                                                            <span><?php echo esc_html($simpbook_dl_options[0]['dauer_minuten']); ?> <?php esc_html_e('Min.', 'simple-appointment-booking'); ?></span>
                                                        </div>
                                                    <?php endif;
                                                    if (!empty($simpbook_dl_options[0]['preis'])) : ?>
                                                        <div class="service-price">
                                                            <?php echo esc_html($simpbook_dl_options[0]['preis']); ?>
                                                        </div>
                                                    <?php endif;

                                                else :
                                                    // Keine Optionen: Standard-Dauer und Preis der Dienstleistung
                                                    if (get_option('simpbook_dauer_anzeigen', '1') === '1') : ?>
                                                        <div class="service-duration">
                                                            <svg class="service-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                                                                <polyline points="12 6 12 12 16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                                                            </svg>
                                                            <span><?php echo esc_html($simpbook_dienstleistung->dauer_minuten); ?> <?php esc_html_e('Min.', 'simple-appointment-booking'); ?></span>
                                                        </div>
                                                    <?php endif;
                                                    if (isset($simpbook_dienstleistung->preis_anzeigen) && $simpbook_dienstleistung->preis_anzeigen && isset($simpbook_dienstleistung->preis) && !empty($simpbook_dienstleistung->preis)) : ?>
                                                        <div class="service-price">
                                                            <?php echo esc_html($simpbook_dienstleistung->preis); ?>
                                                        </div>
                                                    <?php endif;

                                                endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <?php if ($simpbook_gruppe['kategorie'] !== null || ($simpbook_gruppe['kategorie'] === null && $simpbook_hat_gruppierte_dl)) : ?>
                                </div><!-- .service-category-group -->
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <input type="hidden" id="simpbook_dienstleistung_id" name="simpbook_dienstleistung_id" value="">
            </div>

            <!-- Buchungsoption-Auswahl (erscheint wenn Service ≥2 Optionen hat) -->
            <div class="form-gruppe" id="booking-options-group" style="display: none;">
                <h4 class="form-section-header"><?php echo esc_html(simpbook_get_form_header('booking_option')); ?></h4>
                <div class="booking-options-grid" id="booking-options-selection"></div>
                <input type="hidden" id="simpbook_buchungsoption_id" name="simpbook_buchungsoption_id" value="">
            </div>

        </div>

        <!-- Schritt 2: Datum & Mitarbeiter & Zeit -->
        <div class="reservierung-form-step" data-step="2">
            <!-- Datums-Auswahl -->
            <div class="form-gruppe" id="date-selection-group">
                <h4 class="form-section-header"><?php echo esc_html(simpbook_get_form_header('date')); ?></h4>
                <div class="date-selection-options">
                    <?php
                    $simpbook_current_lang = simpbook_get_current_language();
                    $simpbook_date_format = ($simpbook_current_lang === 'en_US_AMPM') ? 'm/d/Y' : 'd.m.Y';
                    $simpbook_today_timestamp = current_time('timestamp');
                    $simpbook_tomorrow_timestamp = $simpbook_today_timestamp + DAY_IN_SECONDS;
                    $simpbook_today_date = wp_date($simpbook_date_format, $simpbook_today_timestamp);
                    $simpbook_tomorrow_date = wp_date($simpbook_date_format, $simpbook_tomorrow_timestamp);
                    ?>
                    <div class="date-option" data-date-value="<?php echo esc_attr($simpbook_today_date); ?>">
                        <h3><?php esc_html_e('Today', 'simple-appointment-booking'); ?></h3>
                        <p><?php echo esc_html($simpbook_today_date); ?></p>
                    </div>
                    <div class="date-option" data-date-value="<?php echo esc_attr($simpbook_tomorrow_date); ?>">
                        <h3><?php esc_html_e('Tomorrow', 'simple-appointment-booking'); ?></h3>
                        <p><?php echo esc_html($simpbook_tomorrow_date); ?></p>
                    </div>
                    <div class="date-option" id="custom-date-option" data-date-value="custom">
                        <h3><?php esc_html_e('Other Date', 'simple-appointment-booking'); ?></h3>
                        <p id="custom-date-display"><?php esc_html_e('Select a date', 'simple-appointment-booking'); ?></p>
                        <input type="text" id="simpbook_datum" name="simpbook_datum" class="datepicker" readonly>
                    </div>
                </div>
                <div class="selected-date-display" id="selected-date-display" style="display: none;">
                    <?php esc_html_e('Selected Date:', 'simple-appointment-booking'); ?> <span id="display-date"></span>
                </div>
            </div>

            <!-- Mitarbeiter-Auswahl -->
            <div class="form-gruppe" id="employee-selection-group" style="display: none;">
                <h4 class="form-section-header" id="employee-section-header"><?php echo esc_html(simpbook_get_form_header('employee')); ?></h4>
                <div class="employee-selection-grid" id="employee-selection">
                    <div class="employee-card disabled"><?php esc_html_e('Loading staff...', 'simple-appointment-booking'); ?></div>
                </div>
                <input type="hidden" id="simpbook_mitarbeiter_id" name="simpbook_mitarbeiter_id" value="0">
            </div>

            <!-- Zeit-Auswahl -->
            <div class="form-gruppe" id="time-selection-group" style="display: none;">
                <h4 class="form-section-header"><?php echo esc_html(simpbook_get_form_header('time')); ?></h4>
                <div class="time-selection-grid" id="time-selection">
                    <div class="time-option disabled"><?php esc_html_e('Loading available times...', 'simple-appointment-booking'); ?></div>
                </div>
                <input type="hidden" id="simpbook_uhrzeit" name="simpbook_uhrzeit" value="">
            </div>
        </div>

        <div class="reservierung-form-step" data-step="3">
            <?php
            // Platzhalter für Systemfelder aus Formular-Konfiguration lesen
            $simpbook_form_cfg = SimpBook_DB_Reservierungen::simpbook_get_form_fields_config();
            $simpbook_sys_ph = array('name' => 'Name', 'email' => 'Email', 'telefon' => 'Phone');
            foreach ($simpbook_form_cfg['fields'] as $simpbook_sys_f) {
                if (isset($simpbook_sys_ph[$simpbook_sys_f['key']])) {
                    $simpbook_sys_ph[$simpbook_sys_f['key']] = !empty($simpbook_sys_f['placeholder']) ? $simpbook_sys_f['placeholder'] : $simpbook_sys_f['label'];
                }
            }
            ?>
            <h4 class="form-section-header"><?php echo esc_html(simpbook_get_form_header('contact')); ?></h4>
            <div class="form-gruppe">
                <label for="name"><?php esc_html_e('Name *', 'simple-appointment-booking'); ?></label>
                <input type="text" id="simpbook_name" name="simpbook_name" placeholder="<?php echo esc_attr($simpbook_sys_ph['name']); ?>" required>
            </div>
            <div class="form-gruppe">
                <label for="email"><?php esc_html_e('Email *', 'simple-appointment-booking'); ?></label>
                <input type="email" id="simpbook_email" name="simpbook_email" placeholder="<?php echo esc_attr($simpbook_sys_ph['email']); ?>" required>
            </div>
            <div class="form-gruppe">
                <label for="telefon"><?php esc_html_e('Phone *', 'simple-appointment-booking'); ?></label>
                <div class="phone-input-wrapper">
                    <div class="country-code-selector">
                        <button type="button" class="country-code-button" id="country-code-button">
                            <span class="selected-flag" id="selected-flag"><img src="<?php echo esc_url(SIMPBOOK_PLUGIN_URL . 'assets/flags/de.svg'); ?>" alt="DE" class="flag-img" width="20" height="15"></span>
                            <span class="selected-code" id="selected-code">+49</span>
                            <span class="dropdown-arrow">▼</span>
                        </button>
                        <div class="country-dropdown" id="country-dropdown" style="display: none;">
                            <input type="text" class="country-search" id="country-search" placeholder="<?php esc_attr_e('Search country...', 'simple-appointment-booking'); ?>" autocomplete="off">
                            <ul class="country-list" id="country-list"></ul>
                        </div>
                    </div>
                    <input type="tel" id="simpbook_telefon_number" class="phone-number-input" placeholder="987 654321" required>
                    <input type="hidden" id="simpbook_telefon" name="simpbook_telefon">
                </div>
            </div>
            <!-- Benutzerdefinierte Felder (per JS eingefügt) -->
            <div id="simpbook-custom-fields-container"></div>
        </div>

        <div class="reservierung-form-step" data-step="4">
			<div class="form-gruppe">
				<h4 class="form-section-header"><?php echo esc_html(simpbook_get_form_header('confirmation')); ?></h4>
            </div>
            <div class="summary-item">
                <span class="summary-label"><?php esc_html_e('Date:', 'simple-appointment-booking'); ?></span>
                <span id="summary-datum"></span>
				</br>
                <span class="summary-label"><?php esc_html_e('Time:', 'simple-appointment-booking'); ?></span>
                <span id="summary-uhrzeit"></span>
				</br>
                <span class="summary-label"><?php esc_html_e('Service:', 'simple-appointment-booking'); ?></span>
                <span id="summary-dienstleistung"></span>
				</br>
                <span class="summary-label summary-label-buchungsoption" style="display:none;"><?php esc_html_e('Booking Option:', 'simple-appointment-booking'); ?></span>
                <span id="summary-buchungsoption" style="display:none;"></span>
                <br class="summary-br-buchungsoption" style="display:none;">
                <span class="summary-label summary-label-preis" style="display:none;"><?php esc_html_e('Preis:', 'simple-appointment-booking'); ?></span>
                <span id="summary-preis" style="display:none;"></span>
                <br class="summary-br-preis" style="display:none;">
                <span class="summary-label summary-label-mitarbeiter"><?php esc_html_e('Staff:', 'simple-appointment-booking'); ?></span>
                <span id="summary-mitarbeiter"></span>
                <br class="summary-br-mitarbeiter">
                <span class="summary-label"><?php esc_html_e('Name:', 'simple-appointment-booking'); ?></span>
                <span id="summary-name"></span>
				</br>
                <span class="summary-label"><?php esc_html_e('Email:', 'simple-appointment-booking'); ?></span>
                <span id="summary-email"></span>
				</br>
                <span class="summary-label"><?php esc_html_e('Phone:', 'simple-appointment-booking'); ?></span>
                <span id="summary-telefon"></span>
				</br>
                <div id="summary-custom-fields-container"></div>
            </div>
        </div>

        <div class="form-navigation">
            <button type="button" class="form-button back" data-prev="" style="display: none;"><?php esc_html_e('Back', 'simple-appointment-booking'); ?></button>
            <button type="button" class="form-button next" data-next="2"><?php esc_html_e('Next', 'simple-appointment-booking'); ?></button>
            <button type="submit" class="form-button submit" style="display: none;"><?php esc_html_e('Submit Reservation', 'simple-appointment-booking'); ?></button>
        </div>
    </form>
    
    <!-- Service Description Modal -->
    <div id="service-description-modal" class="service-description-modal" style="display: none;">
        <div class="service-description-content">
            <h4 id="service-description-title"></h4>
            <p id="service-description-text"></p>
        </div>
    </div>

    <!-- Notification Modal -->
    <div id="simpbook-notification-modal" class="simpbook-notif-modal" style="display: none;">
        <div class="simpbook-notif-overlay"></div>
        <div class="simpbook-notif-content">
            <button class="simpbook-notif-close" aria-label="<?php esc_attr_e('Close', 'simple-appointment-booking'); ?>">&times;</button>
            <div class="simpbook-notif-icon"></div>
            <div class="simpbook-notif-message"></div>
            <button class="simpbook-notif-ok"><?php esc_html_e('OK', 'simple-appointment-booking'); ?></button>
        </div>
    </div>
</div>



