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

simpbook_display_trial_notice_on_admin_pages();

global $wpdb;
$bo_table = $wpdb->prefix . 'simpbook_buchungsoptionen';

// ------- Speichern (POST) -------
if (isset($_POST['simpbook_buchungsoption_speichern'], $_POST['simpbook_buchungsoption_nonce'])) {
    if (wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['simpbook_buchungsoption_nonce'])), 'simpbook_save_buchungsoption')) {
        $bo_name      = isset($_POST['simpbook_buchungsoption_name'])          ? sanitize_text_field(wp_unslash($_POST['simpbook_buchungsoption_name']))     : '';
        $bo_dauer     = isset($_POST['simpbook_buchungsoption_dauer_minuten']) ? intval($_POST['simpbook_buchungsoption_dauer_minuten'])                     : 60;
        $bo_sortierung = isset($_POST['simpbook_buchungsoption_sortierung'])   ? intval($_POST['simpbook_buchungsoption_sortierung'])                        : 0;
        $bo_id        = isset($_POST['simpbook_buchungsoption_id'])            ? intval($_POST['simpbook_buchungsoption_id'])                                : 0;

        if (!empty($bo_name) && $bo_dauer > 0) {
            $data   = ['name' => $bo_name, 'dauer_minuten' => $bo_dauer, 'sortierung' => $bo_sortierung];
            $format = ['%s', '%d', '%d'];
            if ($bo_id > 0) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($bo_table, $data, ['id' => $bo_id], $format, ['%d']);
            } else {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->insert($bo_table, $data, $format);
            }
            simpbook_pwa_redirect(admin_url('admin.php?page=simpbook-buchungsoptionen&simpbook_nachricht=gespeichert'));
        }
    }
}

// ------- Alle laden -------
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$alle_optionen = $wpdb->get_results($wpdb->prepare('SELECT * FROM %i ORDER BY sortierung ASC, name ASC', $bo_table));

// ------- Nachrichten -------
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if (isset($_GET['simpbook_nachricht'])) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $msg_key = sanitize_text_field(wp_unslash($_GET['simpbook_nachricht']));
    $msgs = [
        'gespeichert' => esc_html__('Booking option saved successfully.', 'simple-appointment-booking'),
        'geloescht'   => esc_html__('Booking option deleted successfully.', 'simple-appointment-booking'),
    ];
    if (isset($msgs[$msg_key])) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($msgs[$msg_key]) . '</p></div>';
    }
}
?>

<div class="wrap simpbook-admin-wrap simpbook-gruppierungen-wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e('Booking Options', 'simple-appointment-booking'); ?></h1>
    <hr class="wp-header-end">

    <p class="description" style="margin: 8px 0 16px;">
        <?php esc_html_e('Define global booking options here (e.g. 1 hour, 2 hours, half day, full day). These can then be assigned to each service in the service modal with an individual price.', 'simple-appointment-booking'); ?>
    </p>

    <?php if (empty($alle_optionen)) : ?>
        <button type="button" id="add-new-buchungsoption-btn" class="button button-primary" style="margin: 20px 0; padding: 10px 20px; font-size: 14px;">
            <span class="dashicons dashicons-plus-alt" style="margin-right: 5px; vertical-align: middle;"></span>
            <?php esc_html_e('Add New Option', 'simple-appointment-booking'); ?>
        </button>
        <div class="notice notice-info">
            <p><?php esc_html_e('No booking options yet. Create options like "1 Hour", "2 Hours" or "Full Day".', 'simple-appointment-booking'); ?></p>
        </div>
    <?php else : ?>
        <div class="view-toggle-container">
            <button type="button" id="add-new-buchungsoption-btn" class="page-title-action">
                <?php esc_html_e('Add New Option', 'simple-appointment-booking'); ?>
            </button>
        </div>

        <div class="simpbook-list-container">
            <div class="desktop-gruppierungen-tabelle">
                <div style="overflow-x: auto; width: 100%;">
                    <table class="wp-list-table widefat fixed striped gruppierungen-haupttabelle">
                        <thead>
                            <tr>
                                <th style="width: 60px;"><?php esc_html_e('Sort Order', 'simple-appointment-booking'); ?></th>
                                <th><?php esc_html_e('Name', 'simple-appointment-booking'); ?></th>
                                <th style="width: 160px;"><?php esc_html_e('Duration (Minutes)', 'simple-appointment-booking'); ?></th>
                                <th style="width: 120px;"><?php esc_html_e('Actions', 'simple-appointment-booking'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($alle_optionen as $option) : ?>
                                <tr class="buchungsoption-row-clickable" style="cursor: pointer;"
                                    data-buchungsoption-data="<?php echo esc_attr(wp_json_encode([
                                        'id'            => $option->id,
                                        'name'          => $option->name,
                                        'dauer_minuten' => $option->dauer_minuten,
                                        'sortierung'    => $option->sortierung,
                                    ])); ?>">
                                    <td><?php echo esc_html($option->sortierung); ?></td>
                                    <td><strong><?php echo esc_html($option->name); ?></strong></td>
                                    <td><?php echo esc_html($option->dauer_minuten); ?> <?php esc_html_e('Min.', 'simple-appointment-booking'); ?></td>
                                    <td>
                                        <button type="button" class="button button-small buchungsoption-delete-btn"
                                            data-id="<?php echo esc_attr($option->id); ?>"
                                            data-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_buchungsoption')); ?>">
                                            <span class="dashicons dashicons-trash" style="font-size: 14px; vertical-align: middle;"></span>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Modal -->
<div id="buchungsoption-modal" class="reservierung-modal" style="display: none;">
    <div class="reservierung-modal-overlay"></div>
    <div class="reservierung-modal-content" style="max-width: 500px;">
        <div class="reservierung-modal-header">
            <h2 id="buchungsoption-modal-title"><?php esc_html_e('Booking Option', 'simple-appointment-booking'); ?></h2>
            <button type="button" class="reservierung-modal-close" aria-label="<?php esc_attr_e('Close', 'simple-appointment-booking'); ?>">
                <span class="dashicons dashicons-no-alt"></span>
            </button>
        </div>
        <div class="reservierung-modal-body">
            <form id="buchungsoption-form" method="post">
                <?php wp_nonce_field('simpbook_save_buchungsoption', 'simpbook_buchungsoption_nonce'); ?>
                <input type="hidden" id="buchungsoption-edit-id" name="simpbook_buchungsoption_id" value="">

                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="buchungsoption-name"><?php esc_html_e('Name *', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input type="text" id="buchungsoption-name" name="simpbook_buchungsoption_name" class="regular-text" required
                                placeholder="<?php esc_attr_e('e.g. 1 Hour, Half Day, Full Day', 'simple-appointment-booking'); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="buchungsoption-dauer"><?php esc_html_e('Duration (Minutes) *', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input type="number" id="buchungsoption-dauer" name="simpbook_buchungsoption_dauer_minuten" class="small-text" min="1" step="1" required value="60">
                            <p class="description"><?php esc_html_e('Duration in minutes. Examples: 60 = 1 hr., 120 = 2 hrs., 480 = 8 hrs. (Full day)', 'simple-appointment-booking'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="buchungsoption-sortierung"><?php esc_html_e('Sort Order', 'simple-appointment-booking'); ?></label></th>
                        <td>
                            <input type="number" id="buchungsoption-sortierung" name="simpbook_buchungsoption_sortierung" class="small-text" min="0" value="0">
                        </td>
                    </tr>
                </table>

                <div class="reservierung-modal-footer">
                    <div id="buchungsoption-delete-section" style="display: none;">
                        <button type="button" id="buchungsoption-delete-confirm-btn" class="button button-small button-link-delete">
                            <span class="dashicons dashicons-trash"></span> <?php esc_html_e('Delete', 'simple-appointment-booking'); ?>
                        </button>
                    </div>
                    <div>
                        <button type="button" class="button reservierung-modal-close" style="margin-right: 10px;"><?php esc_html_e('Cancel', 'simple-appointment-booking'); ?></button>
                        <button type="submit" name="simpbook_buchungsoption_speichern" class="button button-primary"><?php esc_html_e('Save', 'simple-appointment-booking'); ?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
