<?php
/**
 * Neue Vermietung — admin/neue-vermietung.php
 *
 * Manuelle Aufenthaltsbuchung über das Admin-Backend.
 *
 * @package PocketBookingPro
 */

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

simpbook_display_trial_notice_on_admin_pages();

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

// Formular verarbeiten
if ( isset( $_POST['simpbook_aufenthalt_erstellen'] ) && check_admin_referer( 'simpbook_neue_vermietung' ) ) {
    $simpbook_unterkunft_id = intval( $_POST['simpbook_unterkunft_id'] ?? 0 );
    $simpbook_zimmer_id     = intval( $_POST['simpbook_zimmer_id'] ?? 0 );
    $simpbook_gast_name     = sanitize_text_field( wp_unslash( $_POST['simpbook_gast_name'] ?? '' ) );
    $simpbook_gast_email    = sanitize_email( wp_unslash( $_POST['simpbook_gast_email'] ?? '' ) );
    $simpbook_gast_telefon  = sanitize_text_field( wp_unslash( $_POST['simpbook_gast_telefon'] ?? '' ) );
    $simpbook_checkin       = sanitize_text_field( wp_unslash( $_POST['simpbook_checkin'] ?? '' ) );
    $simpbook_checkout      = sanitize_text_field( wp_unslash( $_POST['simpbook_checkout'] ?? '' ) );
    $simpbook_anzahl_gaeste = intval( $_POST['simpbook_anzahl_gaeste'] ?? 1 );
    $simpbook_nachricht_txt = sanitize_textarea_field( wp_unslash( $_POST['simpbook_nachricht_text'] ?? '' ) );
    $simpbook_status        = sanitize_text_field( wp_unslash( $_POST['simpbook_status'] ?? 'BESTÄTIGT' ) );

    $simpbook_fehler = [];
    if ( $simpbook_unterkunft_id <= 0 ) { $simpbook_fehler[] = __( 'Bitte Unterkunft auswählen.', 'simple-appointment-booking' ); }
    if ( empty( $simpbook_gast_name ) ) { $simpbook_fehler[] = __( 'Bitte Gastname eingeben.', 'simple-appointment-booking' ); }
    if ( empty( $simpbook_gast_email ) ) { $simpbook_fehler[] = __( 'Bitte E-Mail eingeben.', 'simple-appointment-booking' ); }
    if ( empty( $simpbook_checkin ) || empty( $simpbook_checkout ) ) { $simpbook_fehler[] = __( 'Bitte Check-in und Check-out Datum eingeben.', 'simple-appointment-booking' ); }

    if ( empty( $simpbook_fehler ) ) {
        $simpbook_naechte = (int) ( ( strtotime( $simpbook_checkout ) - strtotime( $simpbook_checkin ) ) / DAY_IN_SECONDS );
        if ( $simpbook_naechte <= 0 ) {
            $simpbook_fehler[] = __( 'Check-out muss nach Check-in liegen.', 'simple-appointment-booking' );
        }
    }

    if ( empty( $simpbook_fehler ) ) {
        // Preis berechnen
        $simpbook_preis_info = $simpbook_v->preis_berechnen( $simpbook_unterkunft_id, $simpbook_zimmer_id > 0 ? $simpbook_zimmer_id : null, $simpbook_checkin, $simpbook_checkout );

        // Manuell eingegebenen Preis bevorzugen
        $simpbook_manueller_preis = isset( $_POST['simpbook_manueller_preis'] ) && '' !== $_POST['simpbook_manueller_preis'] ? floatval( $_POST['simpbook_manueller_preis'] ) : null;

        $simpbook_insert_data = [
            'unterkunft_id'    => $simpbook_unterkunft_id,
            'zimmer_id'        => $simpbook_zimmer_id > 0 ? $simpbook_zimmer_id : null,
            'gast_name'        => $simpbook_gast_name,
            'gast_email'       => $simpbook_gast_email,
            'gast_telefon'     => $simpbook_gast_telefon,
            'anzahl_gaeste'    => $simpbook_anzahl_gaeste,
            'nachricht'        => $simpbook_nachricht_txt,
            'checkin_datum'    => $simpbook_checkin,
            'checkout_datum'   => $simpbook_checkout,
            'anzahl_naechte'   => $simpbook_naechte,
            'preis_pro_nacht'  => $simpbook_preis_info['preis_pro_nacht'] ?? null,
            'reinigungsgebuehr' => $simpbook_preis_info['reinigungsgebuehr'] ?? null,
            'gesamtpreis'      => $simpbook_manueller_preis ?? ( $simpbook_preis_info['gesamt'] ?? null ),
            'preis_gebucht'    => $simpbook_manueller_preis ?? ( $simpbook_preis_info['gesamt'] ?? null ),
            'status'           => $simpbook_status,
            'stornierungs_token' => wp_generate_password( 32, false ),
            'erstellt_am'      => current_time( 'mysql' ),
        ];

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

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert( $wpdb->prefix . 'simpbook_aufenthalte', $simpbook_insert_data );
        $simpbook_new_id = $wpdb->insert_id;

        if ( $simpbook_new_id ) {
            do_action( 'simpbook_buchung_erstellt', $simpbook_new_id, [
                'modus'         => 'ferienhaeuser',
                'tabelle'       => 'simpbook_aufenthalte',
                'unterkunft_id' => $simpbook_unterkunft_id,
                'kunde_name'    => $simpbook_gast_name,
                'kunde_email'   => $simpbook_gast_email,
                'status'        => $simpbook_status,
            ] );
            wp_safe_redirect( admin_url( 'admin.php?page=simpbook-reservierungen&simpbook_aktion=bearbeiten&simpbook_id=' . $simpbook_new_id . '&simpbook_nachricht=aktualisiert' ) );
            exit;
        }
    }

    if ( ! empty( $simpbook_fehler ) ) {
        echo '<div class="notice notice-error"><p>' . esc_html( implode( '<br>', $simpbook_fehler ) ) . '</p></div>';
    }
}

// Unterkünfte für Dropdown
$simpbook_unterkuenfte = $simpbook_v->get_unterkuenfte( [ 'status' => 'aktiv', 'orderby' => 'titel', 'order' => 'ASC' ] );
?>

<div class="wrap simpbook-admin-wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e( 'Neuen Aufenthalt anlegen', 'simple-appointment-booking' ); ?></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">

    <form method="post" action="" id="simpbook-neue-vermietung-form">
        <?php wp_nonce_field( 'simpbook_neue_vermietung' ); ?>

        <table class="form-table">
            <tr>
                <th><label for="simpbook_unterkunft_id"><?php esc_html_e( 'Unterkunft *', 'simple-appointment-booking' ); ?></label></th>
                <td>
                    <select name="simpbook_unterkunft_id" id="simpbook_unterkunft_id" required>
                        <option value=""><?php esc_html_e( '— Unterkunft wählen —', 'simple-appointment-booking' ); ?></option>
                        <?php foreach ( $simpbook_unterkuenfte as $uk ) : ?>
                            <option value="<?php echo esc_attr( $uk->id ); ?>"
                                data-vermietungsart="<?php echo esc_attr( $uk->vermietungsart ); ?>"
                                <?php selected( intval( $_POST['simpbook_unterkunft_id'] ?? 0 ), $uk->id ); ?>>
                                <?php echo esc_html( $uk->titel ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </td>
            </tr>
            <tr id="simpbook-zimmer-row" style="display: none;">
                <th><label for="simpbook_zimmer_id"><?php esc_html_e( 'Zimmer', 'simple-appointment-booking' ); ?></label></th>
                <td>
                    <select name="simpbook_zimmer_id" id="simpbook_zimmer_id">
                        <option value=""><?php esc_html_e( '— Kein Zimmer —', 'simple-appointment-booking' ); ?></option>
                    </select>
                    <p class="description"><?php esc_html_e( 'Zimmer werden per AJAX geladen, wenn die Unterkunft Zimmerweise vermietet wird.', 'simple-appointment-booking' ); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="simpbook_gast_name"><?php esc_html_e( 'Gastname *', 'simple-appointment-booking' ); ?></label></th>
                <td><input name="simpbook_gast_name" type="text" id="simpbook_gast_name" value="<?php echo esc_attr( $_POST['simpbook_gast_name'] ?? '' ); ?>" class="regular-text" required></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( $_POST['simpbook_gast_email'] ?? '' ); ?>" class="regular-text" required></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( $_POST['simpbook_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( $_POST['simpbook_anzahl_gaeste'] ?? 1 ); ?>" min="1" class="small-text"></td>
            </tr>
            <tr>
                <th><label for="simpbook_checkin"><?php esc_html_e( 'Check-in *', 'simple-appointment-booking' ); ?></label></th>
                <td><input name="simpbook_checkin" type="date" id="simpbook_checkin" value="<?php echo esc_attr( $_POST['simpbook_checkin'] ?? '' ); ?>" required></td>
            </tr>
            <tr>
                <th><label for="simpbook_checkout"><?php esc_html_e( 'Check-out *', 'simple-appointment-booking' ); ?></label></th>
                <td><input name="simpbook_checkout" type="date" id="simpbook_checkout" value="<?php echo esc_attr( $_POST['simpbook_checkout'] ?? '' ); ?>" required></td>
            </tr>
            <tr>
                <th><label for="simpbook_manueller_preis"><?php esc_html_e( 'Preis manuell (€)', 'simple-appointment-booking' ); ?></label></th>
                <td>
                    <input name="simpbook_manueller_preis" type="number" id="simpbook_manueller_preis" value="" min="0" step="0.01" class="small-text">
                    <p class="description"><?php esc_html_e( 'Leer lassen = automatische Berechnung anhand der Unterkunftspreise.', 'simple-appointment-booking' ); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="simpbook_status"><?php esc_html_e( 'Status', 'simple-appointment-booking' ); ?></label></th>
                <td>
                    <select name="simpbook_status" id="simpbook_status">
                        <option value="BESTÄTIGT"><?php esc_html_e( 'Bestätigt', 'simple-appointment-booking' ); ?></option>
                        <option value="AUSSTEHEND"><?php esc_html_e( 'Ausstehend', 'simple-appointment-booking' ); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="simpbook_nachricht_text"><?php esc_html_e( 'Nachricht / Notiz', 'simple-appointment-booking' ); ?></label></th>
                <td><textarea name="simpbook_nachricht_text" id="simpbook_nachricht_text" rows="4" class="large-text"><?php echo esc_textarea( $_POST['simpbook_nachricht_text'] ?? '' ); ?></textarea></td>
            </tr>
        </table>

        <p class="submit">
            <input type="submit" name="simpbook_aufenthalt_erstellen" class="button button-primary" value="<?php esc_attr_e( 'Aufenthalt anlegen', 'simple-appointment-booking' ); ?>">
        </p>
    </form>
</div>
