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

simpbook_display_trial_notice_on_admin_pages();

global $wpdb;
$simpbook_kategorien_table = $wpdb->prefix . 'simpbook_dienstleistung_kategorien';

// Löschen
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if (isset($_GET['simpbook_aktion']) && $_GET['simpbook_aktion'] === 'loeschen' && isset($_GET['simpbook_id'])) {
    $simpbook_id = intval($_GET['simpbook_id']);
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (isset($_GET['simpbook_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['simpbook_nonce'])), 'simpbook_delete_kategorie_' . $simpbook_id)) {
        simpbook_delete_kategorie($simpbook_id, true);
        simpbook_pwa_redirect(admin_url('admin.php?page=simpbook-gruppierungen&simpbook_nachricht=geloescht'));
    }
}

// Speichern (POST)
if (isset($_POST['simpbook_kategorie_speichern']) && isset($_POST['simpbook_kategorie_nonce'])) {
    if (wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['simpbook_kategorie_nonce'])), 'simpbook_save_kategorie')) {
        $simpbook_kategorie_data = array(
            'name' => isset($_POST['simpbook_kategorie_name']) ? sanitize_text_field(wp_unslash($_POST['simpbook_kategorie_name'])) : '',
            'beschreibung' => isset($_POST['simpbook_kategorie_beschreibung']) ? sanitize_textarea_field(wp_unslash($_POST['simpbook_kategorie_beschreibung'])) : '',
            'sortierung' => isset($_POST['simpbook_kategorie_sortierung']) ? intval($_POST['simpbook_kategorie_sortierung']) : 0,
            'farbe' => isset($_POST['simpbook_kategorie_farbe']) ? sanitize_hex_color(wp_unslash($_POST['simpbook_kategorie_farbe'])) : '#2271b1'
        );
        
        $simpbook_kategorie_id = isset($_POST['simpbook_kategorie_id']) ? intval($_POST['simpbook_kategorie_id']) : null;
        
        if (!empty($simpbook_kategorie_data['name'])) {
            $simpbook_result = simpbook_save_kategorie($simpbook_kategorie_data, $simpbook_kategorie_id);
            if ($simpbook_result) {
                simpbook_pwa_redirect(admin_url('admin.php?page=simpbook-gruppierungen&simpbook_nachricht=gespeichert'));
            }
        }
    }
}

// Alle Kategorien laden
$simpbook_kategorien = simpbook_get_all_kategorien();

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

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

    <?php if (empty($simpbook_kategorien)) : ?>
        <button type="button" id="add-new-kategorie-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 Category', 'simple-appointment-booking'); ?>
        </button>
        <div class="notice notice-info">
            <p><?php esc_html_e('No categories available yet. Create categories to categorize your services.', 'simple-appointment-booking'); ?></p>
        </div>
    <?php else : ?>
        <div class="view-toggle-container">
            <button type="button" id="add-new-kategorie-btn" class="page-title-action"><?php esc_html_e('Add New Category', 'simple-appointment-booking'); ?></button>
        </div>

        <div class="simpbook-list-container">
            <!-- Desktop-Tabelle -->
            <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: 40px;"><?php esc_html_e('Sort Order', 'simple-appointment-booking'); ?></th>
                                <th><?php esc_html_e('Name', 'simple-appointment-booking'); ?></th>
                                <th><?php esc_html_e('Description', 'simple-appointment-booking'); ?></th>
                                <th style="width: 120px;"><?php esc_html_e('Services', 'simple-appointment-booking'); ?></th>                            <th><?php esc_html_e('Shortcode', 'simple-appointment-booking'); ?></th>                                <th style="width: 150px;"><?php esc_html_e('Actions', 'simple-appointment-booking'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($simpbook_kategorien as $simpbook_kategorie) : 
                                $simpbook_dl_count = simpbook_count_dienstleistungen_in_kategorie($simpbook_kategorie->id);
                                $simpbook_dl_list = simpbook_get_dienstleistungen_by_kategorie($simpbook_kategorie->id);
                                $simpbook_dl_names = array_map(function($dl) { return $dl->name; }, $simpbook_dl_list);
                            ?>
                                <tr class="kategorie-row-clickable"
                                    data-kategorie-id="<?php echo esc_attr($simpbook_kategorie->id); ?>"
                                    data-kategorie-name="<?php echo esc_attr($simpbook_kategorie->name); ?>"
                                    data-delete-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_kategorie_' . $simpbook_kategorie->id)); ?>"
                                    data-dl-count="<?php echo esc_attr($simpbook_dl_count); ?>"
                                    data-dl-names="<?php echo esc_attr(wp_json_encode($simpbook_dl_names)); ?>"
                                    data-kategorie-data="<?php echo esc_attr(wp_json_encode([
                                        'id' => $simpbook_kategorie->id,
                                        'name' => $simpbook_kategorie->name,
                                        'beschreibung' => $simpbook_kategorie->beschreibung,
                                        'sortierung' => $simpbook_kategorie->sortierung,
                                        'farbe' => $simpbook_kategorie->farbe ?? '#2271b1'
                                    ])); ?>"
                                    style="cursor: pointer;">
                                    <td><?php echo esc_html($simpbook_kategorie->sortierung); ?></td>
                                    <td><strong><?php echo esc_html($simpbook_kategorie->name); ?></strong></td>
                                    <td><?php echo esc_html(wp_trim_words($simpbook_kategorie->beschreibung, 10, '...')); ?></td>
                                    <td>
                                        <span class="simpbook-badge" style="background-color: <?php echo esc_attr($simpbook_kategorie->farbe ?? '#2271b1'); ?>;"><?php echo esc_html($simpbook_dl_count); ?></span>
                                    </td>
                                    <td>
                                        <code style="font-size:11px;background:#f5f5f5;padding:3px 6px;border-radius:3px;display:inline-block;">[simpbook_bookingform kategorie="<?php echo esc_attr($simpbook_kategorie->id); ?>"]</code>
                                    </td>
                                    <td>
                                        <button type="button" class="button button-small edit-kategorie-btn" 
                                                data-kategorie-id="<?php echo esc_attr($simpbook_kategorie->id); ?>">
                                            <span class="dashicons dashicons-edit" style="vertical-align: middle;"></span>
                                        </button>
                                        <a href="<?php echo esc_url(wp_nonce_url(
                                            admin_url('admin.php?page=simpbook-gruppierungen&simpbook_aktion=loeschen&simpbook_id=' . $simpbook_kategorie->id),
                                            'simpbook_delete_kategorie_' . $simpbook_kategorie->id,
                                            'simpbook_nonce'
                                        )); ?>" 
                                           class="button button-small delete-kategorie-btn">
                                            <span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Mobile/Tablet Kartenansicht -->
            <div class="mobile-gruppierungen-karten">
                <?php foreach ($simpbook_kategorien as $simpbook_kategorie) : 
                    $simpbook_dl_count = simpbook_count_dienstleistungen_in_kategorie($simpbook_kategorie->id);
                    $simpbook_dl_list_mobile = simpbook_get_dienstleistungen_by_kategorie($simpbook_kategorie->id);
                    $simpbook_dl_names_mobile = array_map(function($dl) { return $dl->name; }, $simpbook_dl_list_mobile);
                ?>
                    <div class="gruppierung-karte"
                         data-kategorie-id="<?php echo esc_attr($simpbook_kategorie->id); ?>"
                         data-kategorie-name="<?php echo esc_attr($simpbook_kategorie->name); ?>"
                         data-delete-nonce="<?php echo esc_attr(wp_create_nonce('simpbook_delete_kategorie_' . $simpbook_kategorie->id)); ?>"
                         data-dl-count="<?php echo esc_attr($simpbook_dl_count); ?>"
                         data-dl-names="<?php echo esc_attr(wp_json_encode($simpbook_dl_names_mobile)); ?>"
                         data-kategorie-data="<?php echo esc_attr(wp_json_encode([
                             'id' => $simpbook_kategorie->id,
                             'name' => $simpbook_kategorie->name,
                             'beschreibung' => $simpbook_kategorie->beschreibung,
                             'sortierung' => $simpbook_kategorie->sortierung,
                             'farbe' => $simpbook_kategorie->farbe ?? '#2271b1'
                         ])); ?>">
                        <div class="gruppierung-karte-header">
                            <h3><?php echo esc_html($simpbook_kategorie->name); ?></h3>
                            <span class="simpbook-badge" style="background-color: <?php echo esc_attr($simpbook_kategorie->farbe ?? '#2271b1'); ?>;"><?php echo esc_html($simpbook_dl_count); ?> <?php esc_html_e('Services', 'simple-appointment-booking'); ?></span>
                        </div>
                        <?php if (!empty($simpbook_kategorie->beschreibung)) : ?>
                            <p class="gruppierung-beschreibung"><?php echo esc_html(wp_trim_words($simpbook_kategorie->beschreibung, 20, '...')); ?></p>
                        <?php endif; ?>
                        <div class="gruppierung-karte-actions">
                            <button type="button" class="button button-small edit-kategorie-btn">
                                <span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'simple-appointment-booking'); ?>
                            </button>
                            <a href="<?php echo esc_url(wp_nonce_url(
                                admin_url('admin.php?page=simpbook-gruppierungen&simpbook_aktion=loeschen&simpbook_id=' . $simpbook_kategorie->id),
                                'simpbook_delete_kategorie_' . $simpbook_kategorie->id,
                                'simpbook_nonce'
                            )); ?>" 
                               class="button button-small delete-kategorie-btn">
                                <span class="dashicons dashicons-trash"></span>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Modal für Gruppierung hinzufügen/bearbeiten -->
<div id="kategorie-modal" class="simpbook-modal" style="display: none;">
    <div class="simpbook-modal-overlay"></div>
    <div class="simpbook-modal-content">
        <div class="simpbook-modal-header">
            <h2 id="kategorie-modal-title"><?php esc_html_e('New Category', 'simple-appointment-booking'); ?></h2>
            <button type="button" class="simpbook-modal-close">&times;</button>
        </div>
        <form method="post" id="kategorie-form">
            <?php wp_nonce_field('simpbook_save_kategorie', 'simpbook_kategorie_nonce'); ?>
            <input type="hidden" name="simpbook_kategorie_id" id="simpbook_kategorie_id" value="">
            
            <div class="simpbook-modal-body">
                <div class="simpbook-form-group">
                    <label for="simpbook_kategorie_name"><?php esc_html_e('Name', 'simple-appointment-booking'); ?> <span class="required">*</span></label>
                    <input type="text" name="simpbook_kategorie_name" id="simpbook_kategorie_name" class="regular-text" required>
                </div>
                
                <div class="simpbook-form-group">
                    <label for="simpbook_kategorie_beschreibung"><?php esc_html_e('Description', 'simple-appointment-booking'); ?></label>
                    <textarea name="simpbook_kategorie_beschreibung" id="simpbook_kategorie_beschreibung" rows="3" class="large-text"></textarea>
                    <p class="description"><?php esc_html_e('Optional: Short description of the category.', 'simple-appointment-booking'); ?></p>
                </div>
                
                <div class="simpbook-form-group">
                    <label for="simpbook_kategorie_sortierung"><?php esc_html_e('Sort Order', 'simple-appointment-booking'); ?></label>
                    <input type="number" name="simpbook_kategorie_sortierung" id="simpbook_kategorie_sortierung" class="small-text" value="0" min="0">
                    <p class="description"><?php esc_html_e('Lower numbers are displayed first.', 'simple-appointment-booking'); ?></p>
                </div>
                
                <div class="simpbook-form-group">
                    <label for="simpbook_kategorie_farbe"><?php esc_html_e('Badge Color', 'simple-appointment-booking'); ?></label>
                    <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 10px;">
                        <input type="color" id="kategorie_color_picker" value="#2271b1">
                        <input name="simpbook_kategorie_farbe" type="text" id="simpbook_kategorie_farbe"
                               value="#2271b1"
                               pattern="^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"
                               placeholder="#2271b1"
                               style="width: 100px;">
                        <button type="button" id="apply_kategorie_color_btn" class="button"><?php esc_html_e('Apply', 'simple-appointment-booking'); ?></button>
                    </div>
                    <p class="description"><?php esc_html_e('Choose a color for the category badge.', 'simple-appointment-booking'); ?></p>
                </div>
                <div class="simpbook-form-group" id="kategorie-shortcode-group" style="display:none;">
                    <label><?php esc_html_e('Shortcode', 'simple-appointment-booking'); ?></label>
                    <div style="display:flex;gap:10px;align-items:center;">
                        <input type="text" id="simpbook_kategorie_shortcode" readonly
                               style="flex:1;background:#f5f5f5;font-family:monospace;font-size:13px;" value="">
                        <button type="button" id="copy-shortcode-btn" class="button"><?php esc_html_e('Copy', 'simple-appointment-booking'); ?></button>
                    </div>
                    <p class="description"><?php esc_html_e('Insert this shortcode on a WordPress page to display only the services of this category.', 'simple-appointment-booking'); ?></p>
                </div>
            </div>
            
            <div class="simpbook-modal-footer">
                <button type="button" class="button simpbook-modal-cancel"><?php esc_html_e('Cancel', 'simple-appointment-booking'); ?></button>
                <button type="submit" name="simpbook_kategorie_speichern" class="button button-primary"><?php esc_html_e('Save', 'simple-appointment-booking'); ?></button>
            </div>
        </form>
    </div>
</div>
