<?php
/**
 * Vermietung-Buchung bearbeiten — admin/vermietung-buchung-bearbeiten.php
 *
 * Detail-/Bearbeitungsansicht eines Aufenthalts.
 *
 * @package PocketBookingPro
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

simpbook_display_trial_notice_on_admin_pages();

global $wpdb;
$simpbook_v = Simpbook_Vermietung::instance();

// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_id = isset( $_GET['simpbook_id'] ) ? intval( $_GET['simpbook_id'] ) : 0;
if ( $simpbook_id <= 0 ) {
    wp_die( esc_html__( 'Ungültige Buchungs-ID.', 'simple-appointment-booking' ) );
}

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$simpbook_aufenthalt = $wpdb->get_row( $wpdb->prepare(
    "SELECT a.*, u.titel AS unterkunft_titel, z.name AS zimmer_name
     FROM {$wpdb->prefix}simpbook_aufenthalte a
     LEFT JOIN {$wpdb->prefix}simpbook_unterkuenfte u ON a.unterkunft_id = u.id
     LEFT JOIN {$wpdb->prefix}simpbook_unterkunft_zimmer z ON a.zimmer_id = z.id
     WHERE a.id = %d",
    $simpbook_id
) );

if ( ! $simpbook_aufenthalt ) {
    wp_die( esc_html__( 'Buchung nicht gefunden.', 'simple-appointment-booking' ) );
}

// Status ändern per POST
if ( isset( $_POST['simpbook_aufenthalt_status_aendern'] ) && check_admin_referer( 'simpbook_aufenthalt_status_' . $simpbook_id ) ) {
    $simpbook_neuer_status = sanitize_text_field( wp_unslash( $_POST['simpbook_neuer_status'] ) );
    $simpbook_erlaubte     = [ 'AUSSTEHEND', 'BESTÄTIGT', 'ABGELEHNT', 'STORNIERT', 'EINGECHECKT', 'AUSGECHECKT' ];

    if ( in_array( $simpbook_neuer_status, $simpbook_erlaubte, true ) ) {
        $simpbook_update_data = [
            'status'                 => $simpbook_neuer_status,
            'status_geaendert_datum' => current_time( 'mysql' ),
        ];

        if ( 'STORNIERT' === $simpbook_neuer_status ) {
            $simpbook_update_data['storniert']           = 1;
            $simpbook_update_data['stornierungs_datum']   = current_time( 'mysql' );
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            $wpdb->prefix . 'simpbook_aufenthalte',
            $simpbook_update_data,
            [ 'id' => $simpbook_id ],
        );

        // Hook feuern
        $simpbook_hook_context = [
            'modus'      => 'ferienhaeuser',
            'tabelle'    => 'simpbook_aufenthalte',
            'neuer_status' => $simpbook_neuer_status,
        ];
        if ( 'BESTÄTIGT' === $simpbook_neuer_status ) {
            do_action( 'simpbook_buchung_bestaetigt', $simpbook_id, $simpbook_hook_context );
        } elseif ( 'STORNIERT' === $simpbook_neuer_status ) {
            do_action( 'simpbook_buchung_storniert', $simpbook_id, $simpbook_hook_context );
        }

        wp_safe_redirect( admin_url( 'admin.php?page=simpbook-reservierungen&simpbook_aktion=bearbeiten&simpbook_id=' . $simpbook_id . '&simpbook_nachricht=aktualisiert' ) );
        exit;
    }
}

// Aufenthalt-Daten bearbeiten per POST
if ( isset( $_POST['simpbook_aufenthalt_speichern'] ) && check_admin_referer( 'simpbook_aufenthalt_bearbeiten_' . $simpbook_id ) ) {
    $simpbook_update = [
        'gast_name'      => isset( $_POST['simpbook_gast_name'] ) ? sanitize_text_field( wp_unslash( $_POST['simpbook_gast_name'] ) ) : $simpbook_aufenthalt->gast_name,
        'gast_email'     => isset( $_POST['simpbook_gast_email'] ) ? sanitize_email( wp_unslash( $_POST['simpbook_gast_email'] ) ) : $simpbook_aufenthalt->gast_email,
        'gast_telefon'   => isset( $_POST['simpbook_gast_telefon'] ) ? sanitize_text_field( wp_unslash( $_POST['simpbook_gast_telefon'] ) ) : $simpbook_aufenthalt->gast_telefon,
        'anzahl_gaeste'  => isset( $_POST['simpbook_anzahl_gaeste'] ) ? intval( $_POST['simpbook_anzahl_gaeste'] ) : $simpbook_aufenthalt->anzahl_gaeste,
        'nachricht'      => isset( $_POST['simpbook_nachricht_text'] ) ? sanitize_textarea_field( wp_unslash( $_POST['simpbook_nachricht_text'] ) ) : $simpbook_aufenthalt->nachricht,
        'gesamtpreis'    => isset( $_POST['simpbook_gesamtpreis'] ) ? floatval( $_POST['simpbook_gesamtpreis'] ) : $simpbook_aufenthalt->gesamtpreis,
    ];

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->update( $wpdb->prefix . 'simpbook_aufenthalte', $simpbook_update, [ 'id' => $simpbook_id ] );
    wp_safe_redirect( admin_url( 'admin.php?page=simpbook-reservierungen&simpbook_aktion=bearbeiten&simpbook_id=' . $simpbook_id . '&simpbook_nachricht=aktualisiert' ) );
    exit;
}

$a = $simpbook_aufenthalt; // Kurzname für Template

// Nachricht
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['simpbook_nachricht'] ) && 'aktualisiert' === $_GET['simpbook_nachricht'] ) {
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Buchung aktualisiert.', 'simple-appointment-booking' ) . '</p></div>';
}

// Status-Optionen
$simpbook_status_options = [
    'AUSSTEHEND'  => __( 'Ausstehend', 'simple-appointment-booking' ),
    'BESTÄTIGT'   => __( 'Bestätigt', 'simple-appointment-booking' ),
    'ABGELEHNT'   => __( 'Abgelehnt', 'simple-appointment-booking' ),
    'STORNIERT'   => __( 'Storniert', 'simple-appointment-booking' ),
    'EINGECHECKT' => __( 'Eingecheckt', 'simple-appointment-booking' ),
    'AUSGECHECKT' => __( 'Ausgecheckt', 'simple-appointment-booking' ),
];
?>

<div class="wrap simpbook-admin-wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e( 'Aufenthalt bearbeiten', 'simple-appointment-booking' ); ?> #<?php echo esc_html( $a->id ); ?></h1>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=simpbook-reservierungen' ) ); ?>" class="page-title-action"><?php esc_html_e( 'Zurück zur Liste', 'simple-appointment-booking' ); ?></a>
    <hr class="wp-header-end">

    <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-top: 15px;">

        <!-- Hauptbereich -->
        <div>
            <!-- Buchungsdetails -->
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.1); margin-bottom: 20px;">
                <h2 style="margin-top: 0;"><?php esc_html_e( 'Aufenthaltsdetails', 'simple-appointment-booking' ); ?></h2>
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e( 'Unterkunft', 'simple-appointment-booking' ); ?></th>
                        <td><strong><?php echo esc_html( $a->unterkunft_titel ?? '—' ); ?></strong></td>
                    </tr>
                    <?php if ( ! empty( $a->zimmer_name ) ) : ?>
                    <tr>
                        <th><?php esc_html_e( 'Zimmer', 'simple-appointment-booking' ); ?></th>
                        <td><?php echo esc_html( $a->zimmer_name ); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th><?php esc_html_e( 'Check-in', 'simple-appointment-booking' ); ?></th>
                        <td><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( $a->checkin_datum ) ) ); ?>
                            <?php echo $a->checkin_uhrzeit ? ' — ' . esc_html( $a->checkin_uhrzeit ) : ''; ?></td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e( 'Check-out', 'simple-appointment-booking' ); ?></th>
                        <td><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( $a->checkout_datum ) ) ); ?>
                            <?php echo $a->checkout_uhrzeit ? ' — ' . esc_html( $a->checkout_uhrzeit ) : ''; ?></td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e( 'Nächte', 'simple-appointment-booking' ); ?></th>
                        <td><?php echo esc_html( $a->anzahl_naechte ); ?></td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e( 'Gäste', 'simple-appointment-booking' ); ?></th>
                        <td><?php echo esc_html( $a->anzahl_gaeste ); ?></td>
                    </tr>
                </table>

                <!-- Preisaufstellung -->
                <h3><?php esc_html_e( 'Preisübersicht', 'simple-appointment-booking' ); ?></h3>
                <table class="widefat" style="max-width: 400px;">
                    <tr>
                        <td><?php echo esc_html( $a->anzahl_naechte ); ?> × <?php echo esc_html( number_format( (float) ( $a->preis_pro_nacht ?? 0 ), 2, ',', '.' ) ); ?> €</td>
                        <td style="text-align: right;"><?php echo esc_html( number_format( (float) ( ( $a->preis_pro_nacht ?? 0 ) * $a->anzahl_naechte ), 2, ',', '.' ) ); ?> €</td>
                    </tr>
                    <?php if ( $a->reinigungsgebuehr ) : ?>
                    <tr>
                        <td><?php esc_html_e( 'Reinigungsgebühr', 'simple-appointment-booking' ); ?></td>
                        <td style="text-align: right;"><?php echo esc_html( number_format( (float) $a->reinigungsgebuehr, 2, ',', '.' ) ); ?> €</td>
                    </tr>
                    <?php endif; ?>
                    <?php if ( $a->rabatt_betrag ) : ?>
                    <tr style="color: #00a32a;">
                        <td><?php esc_html_e( 'Rabatt', 'simple-appointment-booking' ); ?> (<?php echo esc_html( $a->rabatt_code_angewendet ); ?>)</td>
                        <td style="text-align: right;">-<?php echo esc_html( number_format( (float) $a->rabatt_betrag, 2, ',', '.' ) ); ?> €</td>
                    </tr>
                    <?php endif; ?>
                    <tr style="font-weight: 700; border-top: 2px solid #ccc;">
                        <td><?php esc_html_e( 'Gesamt', 'simple-appointment-booking' ); ?></td>
                        <td style="text-align: right;"><?php echo esc_html( number_format( (float) ( $a->gesamtpreis ?? 0 ), 2, ',', '.' ) ); ?> €</td>
                    </tr>
                    <?php if ( $a->kaution ) : ?>
                    <tr style="color: #888;">
                        <td><?php esc_html_e( 'Kaution', 'simple-appointment-booking' ); ?></td>
                        <td style="text-align: right;"><?php echo esc_html( number_format( (float) $a->kaution, 2, ',', '.' ) ); ?> €</td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>

            <!-- Gastdaten bearbeiten -->
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.1);">
                <h2 style="margin-top: 0;"><?php esc_html_e( 'Gastdaten', 'simple-appointment-booking' ); ?></h2>
                <form method="post" action="">
                    <?php wp_nonce_field( 'simpbook_aufenthalt_bearbeiten_' . $simpbook_id ); ?>
                    <table class="form-table">
                        <tr>
                            <th><label for="simpbook_gast_name"><?php esc_html_e( 'Name', 'simple-appointment-booking' ); ?></label></th>
                            <td><input name="simpbook_gast_name" type="text" id="simpbook_gast_name" value="<?php echo esc_attr( $a->gast_name ); ?>" class="regular-text"></td>
                        </tr>
                        <tr>
                            <th><label for="simpbook_gast_email"><?php esc_html_e( 'E-Mail', 'simple-appointment-booking' ); ?></label></th>
                            <td><input name="simpbook_gast_email" type="email" id="simpbook_gast_email" value="<?php echo esc_attr( $a->gast_email ); ?>" class="regular-text"></td>
                        </tr>
                        <tr>
                            <th><label for="simpbook_gast_telefon"><?php esc_html_e( 'Telefon', 'simple-appointment-booking' ); ?></label></th>
                            <td><input name="simpbook_gast_telefon" type="tel" id="simpbook_gast_telefon" value="<?php echo esc_attr( $a->gast_telefon ); ?>" class="regular-text"></td>
                        </tr>
                        <tr>
                            <th><label for="simpbook_anzahl_gaeste"><?php esc_html_e( 'Anzahl Gäste', 'simple-appointment-booking' ); ?></label></th>
                            <td><input name="simpbook_anzahl_gaeste" type="number" id="simpbook_anzahl_gaeste" value="<?php echo esc_attr( $a->anzahl_gaeste ); ?>" min="1" class="small-text"></td>
                        </tr>
                        <tr>
                            <th><label for="simpbook_gesamtpreis"><?php esc_html_e( 'Gesamtpreis (€)', 'simple-appointment-booking' ); ?></label></th>
                            <td><input name="simpbook_gesamtpreis" type="number" id="simpbook_gesamtpreis" value="<?php echo esc_attr( $a->gesamtpreis ); ?>" min="0" step="0.01" class="small-text"></td>
                        </tr>
                        <tr>
                            <th><label for="simpbook_nachricht_text"><?php esc_html_e( 'Nachricht', 'simple-appointment-booking' ); ?></label></th>
                            <td><textarea name="simpbook_nachricht_text" id="simpbook_nachricht_text" rows="4" class="large-text"><?php echo esc_textarea( $a->nachricht ); ?></textarea></td>
                        </tr>
                    </table>
                    <p><input type="submit" name="simpbook_aufenthalt_speichern" class="button button-primary" value="<?php esc_attr_e( 'Änderungen speichern', 'simple-appointment-booking' ); ?>"></p>
                </form>
            </div>
        </div>

        <!-- Seitenleiste -->
        <div>
            <!-- Status -->
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.1); margin-bottom: 20px;">
                <h3 style="margin-top: 0;"><?php esc_html_e( 'Status', 'simple-appointment-booking' ); ?></h3>
                <p>
                    <?php
                    $simpbook_current_status = $a->storniert ? 'STORNIERT' : $a->status;
                    $simpbook_label = $simpbook_status_options[ $simpbook_current_status ] ?? $simpbook_current_status;
                    ?>
                    <span class="simpbook-status-badge simpbook-status-<?php echo esc_attr( strtolower( $simpbook_current_status ) ); ?>" style="font-size: 14px; padding: 5px 12px;">
                        <?php echo esc_html( $simpbook_label ); ?>
                    </span>
                </p>
                <form method="post" action="" style="margin-top: 10px;">
                    <?php wp_nonce_field( 'simpbook_aufenthalt_status_' . $simpbook_id ); ?>
                    <select name="simpbook_neuer_status" style="width: 100%;">
                        <?php foreach ( $simpbook_status_options as $key => $label ) : ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $simpbook_current_status, $key ); ?>><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p><input type="submit" name="simpbook_aufenthalt_status_aendern" class="button" value="<?php esc_attr_e( 'Status ändern', 'simple-appointment-booking' ); ?>" style="width: 100%;"></p>
                </form>
            </div>

            <!-- Meta-Info -->
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.1); margin-bottom: 20px;">
                <h3 style="margin-top: 0;"><?php esc_html_e( 'Informationen', 'simple-appointment-booking' ); ?></h3>
                <p><strong><?php esc_html_e( 'Erstellt am:', 'simple-appointment-booking' ); ?></strong><br>
                <?php echo esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $a->erstellt_am ) ) ); ?></p>

                <?php if ( $a->status_geaendert_datum ) : ?>
                <p><strong><?php esc_html_e( 'Status geändert:', 'simple-appointment-booking' ); ?></strong><br>
                <?php echo esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $a->status_geaendert_datum ) ) ); ?></p>
                <?php endif; ?>

                <?php if ( $a->zahlungs_methode ) : ?>
                <p><strong><?php esc_html_e( 'Zahlungsmethode:', 'simple-appointment-booking' ); ?></strong><br>
                <?php echo esc_html( $a->zahlungs_methode ); ?></p>
                <?php endif; ?>

                <?php if ( $a->zahlungs_status ) : ?>
                <p><strong><?php esc_html_e( 'Zahlungsstatus:', 'simple-appointment-booking' ); ?></strong><br>
                <?php echo esc_html( $a->zahlungs_status ); ?></p>
                <?php endif; ?>

                <?php if ( $a->rechnungsnummer ) : ?>
                <p><strong><?php esc_html_e( 'Rechnungsnr.:', 'simple-appointment-booking' ); ?></strong><br>
                <?php echo esc_html( $a->rechnungsnummer ); ?></p>
                <?php endif; ?>
            </div>

            <!-- Schnellaktionen -->
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.1);">
                <h3 style="margin-top: 0;"><?php esc_html_e( 'Aktionen', 'simple-appointment-booking' ); ?></h3>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=simpbook-unterkuenfte&simpbook_aktion=bearbeiten&simpbook_id=' . $a->unterkunft_id ) ); ?>" class="button" style="width: 100%; text-align: center; margin-bottom: 8px;">
                    <?php esc_html_e( 'Unterkunft öffnen', 'simple-appointment-booking' ); ?>
                </a>
                <?php
                do_action( 'simpbook_aufenthalt_bearbeiten_aktionen', $a );
                ?>
            </div>
        </div>

    </div>
</div>
