<?php
/**
 * Vermietung-Buchungen-Liste — admin/vermietung-buchungen-liste.php
 *
 * Listet alle Aufenthalte/Buchungen im Vermietungsmodus.
 *
 * @package PocketBookingPro
 */

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

simpbook_display_trial_notice_on_admin_pages();

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

// Filter-Parameter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_filter = isset( $_GET['simpbook_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['simpbook_filter'] ) ) : 'alle';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_search = isset( $_GET['simpbook_search'] ) ? sanitize_text_field( wp_unslash( $_GET['simpbook_search'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_per_page    = 20;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$simpbook_current_page = isset( $_GET['simpbook_seite_nr'] ) ? max( 1, intval( $_GET['simpbook_seite_nr'] ) ) : 1;
$simpbook_offset       = ( $simpbook_current_page - 1 ) * $simpbook_per_page;

// WHERE-Bedingungen
$simpbook_where = '1=1';
$simpbook_heute = current_time( 'Y-m-d' );

switch ( $simpbook_filter ) {
    case 'heute_checkin':
        $simpbook_where = $wpdb->prepare( 'a.checkin_datum = %s AND a.storniert = 0', $simpbook_heute );
        break;
    case 'heute_checkout':
        $simpbook_where = $wpdb->prepare( 'a.checkout_datum = %s AND a.storniert = 0', $simpbook_heute );
        break;
    case 'zukuenftige':
        $simpbook_where = $wpdb->prepare( 'a.checkin_datum > %s AND a.storniert = 0', $simpbook_heute );
        break;
    case 'ausstehend':
        $simpbook_where = "a.status = 'AUSSTEHEND' AND a.storniert = 0";
        break;
    case 'bestaetigt':
        $simpbook_where = "a.status IN ('BESTÄTIGT','BESTAETIGT') AND a.storniert = 0";
        break;
    case 'storniert':
        $simpbook_where = '(a.storniert = 1 OR a.status = \'STORNIERT\')';
        break;
    default:
        $simpbook_where = '1=1';
}

if ( ! empty( $simpbook_search ) ) {
    $simpbook_like    = '%' . $wpdb->esc_like( $simpbook_search ) . '%';
    $simpbook_where .= $wpdb->prepare( ' AND (a.gast_name LIKE %s OR a.gast_email LIKE %s)', $simpbook_like, $simpbook_like );
}

// Daten laden
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$simpbook_aufenthalte = $wpdb->get_results(
    "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 {$simpbook_where}
     ORDER BY a.checkin_datum DESC, a.erstellt_am DESC
     LIMIT {$simpbook_per_page} OFFSET {$simpbook_offset}"
);

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$simpbook_total = (int) $wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->prefix}simpbook_aufenthalte a WHERE {$simpbook_where}"
);
$simpbook_total_pages = ceil( $simpbook_total / $simpbook_per_page );

// Status-Labels
$simpbook_status_labels = [
    'AUSSTEHEND' => __( 'Ausstehend', 'simple-appointment-booking' ),
    'BESTÄTIGT'  => __( 'Bestätigt', 'simple-appointment-booking' ),
    'BESTAETIGT' => __( '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' ),
];

// Nachrichten
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['simpbook_nachricht'] ) ) {
    $simpbook_msg_key = sanitize_text_field( wp_unslash( $_GET['simpbook_nachricht'] ) );
    $simpbook_msgs = [
        'bestaetigt'   => __( 'Buchung bestätigt.', 'simple-appointment-booking' ),
        'abgelehnt'    => __( 'Buchung abgelehnt.', 'simple-appointment-booking' ),
        'storniert'    => __( 'Buchung storniert.', 'simple-appointment-booking' ),
        'aktualisiert' => __( 'Buchung aktualisiert.', 'simple-appointment-booking' ),
        'geloescht'    => __( 'Buchung gelöscht.', 'simple-appointment-booking' ),
    ];
    if ( isset( $simpbook_msgs[ $simpbook_msg_key ] ) ) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $simpbook_msgs[ $simpbook_msg_key ] ) . '</p></div>';
    }
}

// Basis-URL für Filter
$simpbook_base_url = admin_url( 'admin.php?page=simpbook-reservierungen' );
?>

<div class="wrap simpbook-admin-wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e( 'Aufenthalte / Buchungen', 'simple-appointment-booking' ); ?></h1>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=simpbook-neue-reservierung' ) ); ?>" class="page-title-action"><?php esc_html_e( 'Neuen Aufenthalt anlegen', 'simple-appointment-booking' ); ?></a>
    <hr class="wp-header-end">

    <!-- Filter-Tabs -->
    <ul class="subsubsub" style="margin-bottom: 10px;">
        <?php
        $simpbook_filters = [
            'alle'            => __( 'Alle', 'simple-appointment-booking' ),
            'heute_checkin'   => __( 'Check-in heute', 'simple-appointment-booking' ),
            'heute_checkout'  => __( 'Check-out heute', 'simple-appointment-booking' ),
            'zukuenftige'     => __( 'Zukünftige', 'simple-appointment-booking' ),
            'ausstehend'      => __( 'Ausstehend', 'simple-appointment-booking' ),
            'bestaetigt'      => __( 'Bestätigt', 'simple-appointment-booking' ),
            'storniert'       => __( 'Storniert', 'simple-appointment-booking' ),
        ];
        $simpbook_first = true;
        foreach ( $simpbook_filters as $key => $label ) :
            if ( ! $simpbook_first ) { echo ' | '; }
            $simpbook_first = false;
            $simpbook_class = ( $simpbook_filter === $key ) ? 'current' : '';
        ?>
            <li><a href="<?php echo esc_url( add_query_arg( 'simpbook_filter', $key, $simpbook_base_url ) ); ?>" class="<?php echo esc_attr( $simpbook_class ); ?>"><?php echo esc_html( $label ); ?></a></li>
        <?php endforeach; ?>
    </ul>
    <br class="clear">

    <!-- Suche -->
    <form method="get" action="" style="margin-bottom: 15px;">
        <input type="hidden" name="page" value="simpbook-reservierungen">
        <input type="hidden" name="simpbook_filter" value="<?php echo esc_attr( $simpbook_filter ); ?>">
        <input type="search" name="simpbook_search" value="<?php echo esc_attr( $simpbook_search ); ?>" placeholder="<?php esc_attr_e( 'Name oder E-Mail suchen…', 'simple-appointment-booking' ); ?>" class="regular-text">
        <input type="submit" class="button" value="<?php esc_attr_e( 'Suchen', 'simple-appointment-booking' ); ?>">
    </form>

    <?php if ( empty( $simpbook_aufenthalte ) ) : ?>
        <div class="notice notice-info"><p><?php esc_html_e( 'Keine Buchungen gefunden.', 'simple-appointment-booking' ); ?></p></div>
    <?php else : ?>

        <table class="wp-list-table widefat fixed striped">
            <thead><tr>
                <th style="width: 50px;">#</th>
                <th><?php esc_html_e( 'Gast', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Unterkunft', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Zimmer', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Check-in', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Check-out', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Nächte', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Preis', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Status', 'simple-appointment-booking' ); ?></th>
                <th><?php esc_html_e( 'Aktionen', 'simple-appointment-booking' ); ?></th>
            </tr></thead>
            <tbody>
            <?php foreach ( $simpbook_aufenthalte as $a ) : ?>
                <tr>
                    <td><?php echo esc_html( $a->id ); ?></td>
                    <td>
                        <strong><?php echo esc_html( $a->gast_name ); ?></strong><br>
                        <small><?php echo esc_html( $a->gast_email ); ?></small>
                    </td>
                    <td><?php echo esc_html( $a->unterkunft_titel ?? '—' ); ?></td>
                    <td><?php echo esc_html( $a->zimmer_name ?? '—' ); ?></td>
                    <td><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( $a->checkin_datum ) ) ); ?></td>
                    <td><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( $a->checkout_datum ) ) ); ?></td>
                    <td><?php echo esc_html( $a->anzahl_naechte ); ?></td>
                    <td><?php echo $a->gesamtpreis ? esc_html( number_format( (float) $a->gesamtpreis, 2, ',', '.' ) . ' €' ) : '—'; ?></td>
                    <td>
                        <?php
                        $simpbook_sl = strtolower( $a->status );
                        $simpbook_st = $simpbook_status_labels[ $a->status ] ?? $a->status;
                        if ( $a->storniert ) {
                            $simpbook_sl = 'storniert';
                            $simpbook_st = __( 'Storniert', 'simple-appointment-booking' );
                        }
                        ?>
                        <span class="simpbook-status-badge simpbook-status-<?php echo esc_attr( $simpbook_sl ); ?>"><?php echo esc_html( $simpbook_st ); ?></span>
                    </td>
                    <td>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=simpbook-reservierungen&simpbook_aktion=bearbeiten&simpbook_id=' . $a->id ) ); ?>"
                           class="button button-small" title="<?php esc_attr_e( 'Bearbeiten', 'simple-appointment-booking' ); ?>">
                            <span class="dashicons dashicons-edit" style="vertical-align: middle;"></span>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <?php if ( $simpbook_total_pages > 1 ) : ?>
            <div class="tablenav bottom">
                <div class="tablenav-pages">
                    <span class="displaying-num">
                        <?php
                        /* translators: %s: number of items */
                        printf( esc_html__( '%s Einträge', 'simple-appointment-booking' ), esc_html( $simpbook_total ) );
                        ?>
                    </span>
                    <span class="pagination-links">
                        <?php for ( $i = 1; $i <= $simpbook_total_pages; $i++ ) : ?>
                            <?php if ( $i === $simpbook_current_page ) : ?>
                                <span class="tablenav-pages-navspan button disabled"><?php echo esc_html( $i ); ?></span>
                            <?php else : ?>
                                <a class="button" href="<?php echo esc_url( add_query_arg( 'simpbook_seite_nr', $i ) ); ?>"><?php echo esc_html( $i ); ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>
                    </span>
                </div>
            </div>
        <?php endif; ?>

    <?php endif; ?>
</div>
