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

// Testphase-Hinweis anzeigen
simpbook_display_trial_notice_on_admin_pages();

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

// Wochentage und Zeiten aus der Datenbank laden (for beforeShowDay Logik)
$simpbook_wochentag_zeiten_config = get_option('simpbook_wochentag_zeiten', []);
$simpbook_intervall = intval(get_option('simpbook_intervall', 30));
$simpbook_ausgeschlossene_tage_config = get_option('simpbook_ausgeschlossene_tage', '');
// Spezielle Tage-Konfiguration laden
$simpbook_default_map = simpbook_get_default_settings_map();
$simpbook_spezielle_tage_konfiguration = simpbook_get_option('simpbook_spezielle_tage_konfiguration', $simpbook_default_map['simpbook_spezielle_tage_konfiguration']);
$simpbook_max_personen_einstellung = get_option('simpbook_max_personen', 20);

// Ausgeschlossene Tage in Array umwandeln (YYYY-MM-DD Format)
$simpbook_ausgeschlossene_tage_array_config = array();
$simpbook_ausgeschlossene_tage_formatiert = array();
if (!empty($simpbook_ausgeschlossene_tage_config)) {
    $simpbook_ausgeschlossene_tage_array_config = explode("\n", str_replace("\r", "", $simpbook_ausgeschlossene_tage_config));
    $simpbook_ausgeschlossene_tage_array_config = array_map('trim', $simpbook_ausgeschlossene_tage_array_config);
    $simpbook_ausgeschlossene_tage_array_config = array_filter($simpbook_ausgeschlossene_tage_array_config); // Leere Zeilen entfernen

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

global $simpbook_db_reservierungen; // Sicherstellen, dass die Variable verfügbar ist

$simpbook_id = isset($_GET['simpbook_id']) ? intval($_GET['simpbook_id']) : 0;
$simpbook_reservierung = $simpbook_db_reservierungen->simpbook_reservierung_holen($simpbook_id);

if (!$simpbook_reservierung) {
    echo '<div class="notice notice-error"><p>' . esc_html__('Reservation not found.', 'simple-appointment-booking') . '</p></div>';
    return;
}

// Formular abgeschickt
if (isset($_POST['simpbook_reservierung_bearbeiten_submit'])) {
    // Nonce überprüfen
    check_admin_referer('simpbook_reservierung_bearbeiten_' . $simpbook_id);

    // Daten sammeln
    $simpbook_name = isset($_POST['simpbook_name']) ? sanitize_text_field(wp_unslash($_POST['simpbook_name'])) : '';
    $simpbook_email = isset($_POST['simpbook_email']) ? sanitize_email(wp_unslash($_POST['simpbook_email'])) : '';
    $simpbook_telefon = isset($_POST['simpbook_telefon']) ? sanitize_text_field(wp_unslash($_POST['simpbook_telefon'])) : '';
    $simpbook_datum_input = isset($_POST['simpbook_datum']) ? sanitize_text_field(wp_unslash($_POST['simpbook_datum'])) : ''; // Kommt jetzt als dd-mm-yy
    $simpbook_uhrzeit_raw = isset($_POST['simpbook_uhrzeit']) ? sanitize_text_field(wp_unslash($_POST['simpbook_uhrzeit'])) : '';
    // Konvertiere Zeit von 12h-Format (falls vorhanden) zu 24h-Format für DB
    $simpbook_uhrzeit = simpbook_parse_time_12h($simpbook_uhrzeit_raw);
    $simpbook_dienstleistung_id = isset($_POST['simpbook_dienstleistung_id']) ? intval(wp_unslash($_POST['simpbook_dienstleistung_id'])) : 0;
    $simpbook_mitarbeiter_id = isset($_POST['simpbook_mitarbeiter_id']) ? intval(wp_unslash($_POST['simpbook_mitarbeiter_id'])) : 0;
    $simpbook_nachricht = isset($_POST['simpbook_nachricht']) ? sanitize_textarea_field(wp_unslash($_POST['simpbook_nachricht'])) : '';
    $simpbook_status = isset($_POST['simpbook_status']) ? sanitize_text_field(wp_unslash($_POST['simpbook_status'])) : '';

    // Datum von dd.mm.yyyy (aus Datepicker) in YYYY-MM-DD (für DB) umwandeln
    $simpbook_datum_mysql = $simpbook_reservierung->datum; // Standardwert falls Umwandlung fehlschlägt
    if (!empty($simpbook_datum_input)) {
        // Versuche verschiedene Formate: dd.mm.yyyy, dd.mm.yy, mm/dd/yyyy (US), dd-mm-yy (Fallback)
        $simpbook_current_lang = simpbook_get_current_language();
        $simpbook_dt_obj = DateTime::createFromFormat('d.m.Y', $simpbook_datum_input); // dd.mm.yyyy (z.B. 16.12.2025)
        if ($simpbook_dt_obj === false) {
            $simpbook_dt_obj = DateTime::createFromFormat('d.m.y', $simpbook_datum_input); // dd.mm.yy (z.B. 16.12.25)
        }
        // US-Format: mm/dd/yyyy oder mm/dd/yy
        if ($simpbook_dt_obj === false && $simpbook_current_lang === 'en_US_AMPM') {
            $simpbook_dt_obj = DateTime::createFromFormat('m/d/Y', $simpbook_datum_input); // mm/dd/yyyy
        }
        if ($simpbook_dt_obj === false && $simpbook_current_lang === 'en_US_AMPM') {
            $simpbook_dt_obj = DateTime::createFromFormat('m/d/y', $simpbook_datum_input); // mm/dd/yy
        }
        if ($simpbook_dt_obj === false) {
            $simpbook_dt_obj = DateTime::createFromFormat('d-m-y', $simpbook_datum_input); // Fallback: dd-mm-yy
        }
        if ($simpbook_dt_obj === false) {
            $simpbook_dt_obj = DateTime::createFromFormat('d-m-Y', $simpbook_datum_input); // Fallback: dd-mm-yyyy
        }
        if ($simpbook_dt_obj !== false) {
            $simpbook_datum_mysql = $simpbook_dt_obj->format('Y-m-d');
        } else {
            // Fehlerbehandlung, falls das Datum ungültig ist
            echo '<div class="notice notice-error"><p>' . esc_html__('Invalid date format submitted. Changes to the date may not have been saved.', 'simple-appointment-booking') . '</p></div>';
        }
    }

    // In die Datenbank aktualisieren
    global $wpdb;
    $simpbook_tabellen_name = $wpdb->prefix . 'buchungen';

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

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-specific table
    $simpbook_erfolg = $wpdb->update(
        $simpbook_tabellen_name,
        array(
            'name' => $simpbook_name,
            'email' => $simpbook_email,
            'telefon' => $simpbook_telefon,
            'datum' => $simpbook_datum_mysql, // Konvertiertes Datum
            'uhrzeit' => $simpbook_uhrzeit,
            'dienstleistung_id' => $simpbook_dienstleistung_id,
            'mitarbeiter_id' => $simpbook_mitarbeiter_id > 0 ? $simpbook_mitarbeiter_id : null,
            'nachricht' => $simpbook_nachricht,
            'status' => $simpbook_status
        ),
        array('id' => $simpbook_id),
        array('%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s'), // Format für Daten
        array('%d')  // Format für WHERE-Klausel
    );

    if ($simpbook_erfolg !== false) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Reservation successfully updated.', 'simple-appointment-booking') . '</p></div>';
        // Daten neu laden, um die Änderungen im Formular anzuzeigen
        $simpbook_reservierung = $simpbook_db_reservierungen->simpbook_reservierung_holen($simpbook_id);
    } else {
        echo '<div class="notice notice-error"><p>' . esc_html__('Error updating reservation.', 'simple-appointment-booking') . '</p></div>';
    }
}
?>

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

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

    <form method="post" action="<?php echo esc_attr(simpbook_get_form_action()); ?>">
        <?php wp_nonce_field('simpbook_reservierung_bearbeiten_' . $simpbook_id); ?>

        <table class="form-table">
            <tr>
                <th scope="row"><label for="simpbook_name"><?php esc_html_e('Name', 'simple-appointment-booking'); ?></label></th>
                <td><input name="simpbook_name" id="simpbook_name" type="text" value="<?php echo esc_attr($simpbook_reservierung->name); ?>" class="regular-text" required></td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_email"><?php esc_html_e('Email', 'simple-appointment-booking'); ?></label></th>
                <td><input name="simpbook_email" id="simpbook_email" type="email" value="<?php echo esc_attr($simpbook_reservierung->email); ?>" class="regular-text" required></td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_telefon"><?php esc_html_e('phone', 'simple-appointment-booking'); ?></label></th>
                <td><input name="simpbook_telefon" id="simpbook_telefon" type="text" value="<?php echo esc_attr($simpbook_reservierung->telefon); ?>" class="regular-text" required></td>
            </tr>
		   <tr>
				<th scope="row"><label for="simpbook_datum"><?php esc_html_e('Date', 'simple-appointment-booking'); ?></label></th>
				<td>
					<?php
					// Datum von YYYY-MM-DD (DB) zu dd.mm.yyyy (europäische Schreibweise) konvertieren
					$simpbook_anzeige_datum = '';
					if (!empty($simpbook_reservierung->datum)) {
						$simpbook_dt_obj_anzeige = DateTime::createFromFormat('Y-m-d', $simpbook_reservierung->datum);
						if ($simpbook_dt_obj_anzeige !== false) {
							$simpbook_anzeige_datum = $simpbook_dt_obj_anzeige->format('d.m.Y'); // dd.mm.yyyy (z.B. 16.12.2025)
						} else {
							$simpbook_anzeige_datum = $simpbook_reservierung->datum; // Fallback
						}
					}
					?>
					<input name="simpbook_datum" id="simpbook_datum" type="text" value="<?php echo esc_attr($simpbook_anzeige_datum); ?>" class="datepicker regular-text" required autocomplete="off">
					 <?php if (!empty($simpbook_ausgeschlossene_tage_array_config)): ?>
						<p class="description"><?php echo esc_html(esc_html__('Note: The following days are excluded:', 'simple-appointment-booking') . ' ' . implode(', ', $simpbook_ausgeschlossene_tage_formatiert)); ?></p>
					<?php endif; ?>
				</td>
			</tr>
            <tr>
                <th scope="row"><label for="simpbook_dienstleistung_id"><?php esc_html_e('Service *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_dienstleistung_id" id="simpbook_dienstleistung_id" required>
                        <option value="">-- <?php esc_html_e('Select Service', 'simple-appointment-booking'); ?> --</option>
                        <?php
                        $simpbook_alle_dienstleistungen = simpbook_get_all_dienstleistungen_sorted_by_kategorie(true); // Nur aktive
                        $simpbook_selected_dienstleistung = isset($simpbook_reservierung->dienstleistung_id) ? intval($simpbook_reservierung->dienstleistung_id) : 0;
                        foreach ($simpbook_alle_dienstleistungen as $simpbook_dl) {
                            echo '<option value="' . esc_attr($simpbook_dl->id) . '"'
                                . selected($simpbook_selected_dienstleistung, $simpbook_dl->id, false) . '>'
                                . esc_html(simpbook_format_dienstleistung_with_kategorie($simpbook_dl)) . '</option>';
                        }
                        ?>
                    </select>
                    <p class="description"><?php esc_html_e('Please select a service first.', 'simple-appointment-booking'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_mitarbeiter_id"><?php esc_html_e('Staff', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_mitarbeiter_id" id="simpbook_mitarbeiter_id">
                        <option value="0">-- <?php esc_html_e('No Specific Staff Member', 'simple-appointment-booking'); ?> --</option>
                        <option value="" disabled><?php esc_html_e('Please select a service first', 'simple-appointment-booking'); ?></option>
                    </select>
                    <p class="description"><?php esc_html_e('Optional: Select a specific staff member. Leave the field empty to automatically assign the first available staff member.', 'simple-appointment-booking'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_uhrzeit"><?php esc_html_e('Time *', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_uhrzeit" id="simpbook_uhrzeit" required>
                        <option value="">-- <?php esc_html_e('Select time', 'simple-appointment-booking'); ?> --</option>
                    </select>
                    <p class="description"><?php esc_html_e('Please select date and service first.', 'simple-appointment-booking'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_nachricht"><?php esc_html_e('Message', 'simple-appointment-booking'); ?></label></th>
                <td><textarea name="simpbook_nachricht" id="simpbook_nachricht" rows="5" cols="50"><?php echo esc_textarea($simpbook_reservierung->nachricht); ?></textarea></td>
            </tr>
            <tr>
                <th scope="row"><label for="simpbook_status"><?php esc_html_e('Status', 'simple-appointment-booking'); ?></label></th>
                <td>
                    <select name="simpbook_status" id="simpbook_status">
                        <option value="AUSSTEHEND" <?php selected($simpbook_reservierung->status, 'AUSSTEHEND'); ?>><?php esc_html_e('Pending', 'simple-appointment-booking'); ?></option>
                        <option value="BESTÄTIGT" <?php selected($simpbook_reservierung->status, 'BESTÄTIGT'); ?>><?php esc_html_e('Confirmed', 'simple-appointment-booking'); ?></option>
                        <option value="ABGELEHNT" <?php selected($simpbook_reservierung->status, 'ABGELEHNT'); ?>><?php esc_html_e('Rejected', 'simple-appointment-booking'); ?></option>
                    </select>
                </td>
            </tr>
        </table>

        <input type="submit" name="simpbook_reservierung_bearbeiten_submit" class="button button-primary" value="<?php esc_attr_e('Save Changes', 'simple-appointment-booking'); ?>">
    </form>

</div>

<?php
// Scripts und Styles werden jetzt zentral in admin_skripte_laden() in simple-appointment-booking.php enqueued
?>








