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

// Token aus URL holen
$simpbook_token = isset($_GET['simpbook_token']) ? sanitize_text_field(wp_unslash($_GET['simpbook_token'])) : '';

if (empty($simpbook_token)) {
    // Token fehlt - Fehlerseite anzeigen
    get_header();
    ?>
    <div class="simpbook-cancellation-container">
        <div class="simpbook-cancellation-message simpbook-error">
            <h2><?php esc_html_e('Invalid Cancellation Link', 'simple-appointment-booking'); ?></h2>
            <p><?php esc_html_e('The cancellation link is invalid or incomplete. Please use the link from your confirmation email.', 'simple-appointment-booking'); ?></p>
            <a href="<?php echo esc_url(home_url()); ?>" class="simpbook-button"><?php esc_html_e('Go to Home Page', 'simple-appointment-booking'); ?></a>
        </div>
    </div>
    <?php
    get_footer();
    return;
}

// Reservierung anhand Token suchen
global $wpdb;
$simpbook_tabellen_name = $wpdb->prefix . 'buchungen';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
$simpbook_reservierung = $wpdb->get_row($wpdb->prepare(
    "SELECT * FROM %i WHERE stornierungs_token = %s AND storniert = 0",
    $simpbook_tabellen_name,
    $simpbook_token
));

if (!$simpbook_reservierung) {
    // Reservierung nicht gefunden oder bereits storniert
    get_header();
    ?>
    <div class="simpbook-cancellation-container">
        <div class="simpbook-cancellation-message simpbook-error">
            <h2><?php esc_html_e('Cancellation Not Possible', 'simple-appointment-booking'); ?></h2>
            <p><?php esc_html_e('The reservation was not found or has already been cancelled.', 'simple-appointment-booking'); ?></p>
            <a href="<?php echo esc_url(home_url()); ?>" class="simpbook-button"><?php esc_html_e('Go to Home Page', 'simple-appointment-booking'); ?></a>
        </div>
    </div>
    <?php
    get_footer();
    return;
}

// Dienstleistung und Mitarbeiter laden
$simpbook_dienstleistung = isset($simpbook_reservierung->dienstleistung_id) && $simpbook_reservierung->dienstleistung_id > 0
    ? simpbook_get_dienstleistung($simpbook_reservierung->dienstleistung_id)
    : null;
$simpbook_mitarbeiter = isset($simpbook_reservierung->mitarbeiter_id) && $simpbook_reservierung->mitarbeiter_id > 0
    ? simpbook_get_mitarbeiter($simpbook_reservierung->mitarbeiter_id)
    : null;

$simpbook_service_name = $simpbook_dienstleistung ? $simpbook_dienstleistung->name : __('Unbekannt', 'simple-appointment-booking');
$simpbook_employee_name = $simpbook_mitarbeiter ? $simpbook_mitarbeiter->name : __('No Specific Staff Member', 'simple-appointment-booking');

// Datum und Zeit formatieren
$simpbook_current_language = simpbook_get_current_language();
$simpbook_datum_formatted = simpbook_format_date($simpbook_reservierung->datum, $simpbook_current_language);
$simpbook_uhrzeit_formatted = simpbook_format_time($simpbook_reservierung->uhrzeit, $simpbook_current_language);

// Mindeststunden für Stornierung laden
$simpbook_mindeststunden = get_option('simpbook_stornierung_mindeststunden', 24);

// Aktuelle Zeit
$simpbook_current_time = current_time('timestamp');

// Reservierungszeit als Timestamp
$simpbook_reservation_datetime = strtotime($simpbook_reservierung->datum . ' ' . $simpbook_reservierung->uhrzeit);

// Prüfen, ob Stornierung noch erlaubt ist
$simpbook_time_diff_hours = ($simpbook_reservation_datetime - $simpbook_current_time) / 3600;
$simpbook_can_cancel = $simpbook_time_diff_hours >= $simpbook_mindeststunden;

// Telefonnummer für Stornierung laden
$simpbook_telefon_nummer = get_option('simpbook_stornierung_telefonnummer', '');

// Stornierungs-Status prüfen
$simpbook_cancellation_success = false;
if (isset($_POST['simpbook_confirm_cancellation']) && isset($_POST['simpbook_token']) && $_POST['simpbook_token'] === $simpbook_token) {
    check_admin_referer('simpbook_cancel_' . $simpbook_token);

    // Reservierung stornieren
    global $simpbook_db_reservierungen_instance;
    if (!isset($simpbook_db_reservierungen_instance)) {
        $simpbook_db_reservierungen_instance = new simpbook_DB_Reservierungen();
    }

    $simpbook_cancellation_result = $simpbook_db_reservierungen_instance->simpbook_frontend_reservierung_stornieren($simpbook_token);
    $simpbook_cancellation_success = $simpbook_cancellation_result;
}

if ($simpbook_cancellation_success) {
    // Erfolg anzeigen
    get_header();
    ?>
    <div class="simpbook-cancellation-container">
        <div class="simpbook-cancellation-message simpbook-success">
            <h2><?php esc_html_e('Reservation Successfully Cancelled', 'simple-appointment-booking'); ?></h2>
            <p><?php esc_html_e('Your reservation has been successfully cancelled. You will receive a confirmation by email.', 'simple-appointment-booking'); ?></p>
            <div class="simpbook-reservation-details">
                <p><strong><?php esc_html_e('Service:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_service_name); ?></p>
                <p><strong><?php esc_html_e('Date:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_datum_formatted); ?></p>
                <p><strong><?php esc_html_e('Time:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_uhrzeit_formatted); ?></p>
                <p><strong><?php esc_html_e('Staff:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_employee_name); ?></p>
            </div>
            <a href="<?php echo esc_url(home_url()); ?>" class="simpbook-button"><?php esc_html_e('Go to Home Page', 'simple-appointment-booking'); ?></a>
        </div>
    </div>
    <?php
    get_footer();
    return;
}

// Stornierungs-Formular anzeigen
get_header();
?>
<div class="simpbook-cancellation-container">
    <?php if (!$simpbook_can_cancel) : ?>
        <div class="simpbook-cancellation-message simpbook-error">
            <h2><?php esc_html_e('Cancellation no longer possible', 'simple-appointment-booking'); ?></h2>
            <p><?php 
                printf( 
                    /* translators: 1: hours, 2: phone number link */
                    esc_html__('The cancellation period of %d hours has expired. Please contact us by phone at %s for a cancellation.', 'simple-appointment-booking'),
                    intval($simpbook_mindeststunden),
                    '<a href="tel:' . esc_attr($simpbook_telefon_nummer) . '">' . esc_html($simpbook_telefon_nummer) . '</a>'
                );
            ?></p>
            <a href="<?php echo esc_url(home_url()); ?>" class="simpbook-button"><?php esc_html_e('Go to Home Page', 'simple-appointment-booking'); ?></a>
        </div>
    <?php else : ?>
    <div class="simpbook-cancellation-form">
        <h2><?php esc_html_e('Cancel Reservation', 'simple-appointment-booking'); ?></h2>
        <p><?php esc_html_e('Are you sure you want to cancel this reservation?', 'simple-appointment-booking'); ?></p>

        <div class="simpbook-reservation-details">
            <h3><?php esc_html_e('Reservation Details:', 'simple-appointment-booking'); ?></h3>
            <p><strong><?php esc_html_e('Name:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_reservierung->name); ?></p>
            <p><strong><?php esc_html_e('Service:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_service_name); ?></p>
            <p><strong><?php esc_html_e('Date:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_datum_formatted); ?></p>
            <p><strong><?php esc_html_e('Time:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_uhrzeit_formatted); ?></p>
            <?php if ($simpbook_mitarbeiter) : ?>
                <p><strong><?php esc_html_e('Staff:', 'simple-appointment-booking'); ?></strong> <?php echo esc_html($simpbook_employee_name); ?></p>
            <?php endif; ?>
        </div>

        <form method="post" action="">
            <?php wp_nonce_field('simpbook_cancel_' . $simpbook_token); ?>
            <input type="hidden" name="simpbook_token" value="<?php echo esc_attr($simpbook_token); ?>">
            <div class="simpbook-form-actions">
                <button type="submit" name="simpbook_confirm_cancellation" class="simpbook-button simpbook-button-danger">
                    <?php esc_html_e('Yes, Cancel Reservation', 'simple-appointment-booking'); ?>
                </button>
                <a href="<?php echo esc_url(home_url()); ?>" class="simpbook-button simpbook-button-secondary">
                    <?php esc_html_e('Cancel', 'simple-appointment-booking'); ?>
                </a>
            </div>
        </form>
    </div>
    <?php endif; ?>
</div>
<?php
get_footer();
?>



