<?php

/**
 * EventBookings Settings Class
 *
 * Handles admin settings and menu management for the EventBookings plugin
 *
 * @since 1.1
 */
class Eventbookings_Settings
{
    /**
     * Add admin menu and submenu pages
     *
     * @since 1.1
     */
    public static function eventbookings_add_admin_menu()
    {
        // Main Menu: EventBookings (Redirects to Events)
        add_menu_page('EventBookings', 'EventBookings', 'manage_options', 'eventbookings-events', array(__CLASS__, 'eventbookings_events_page'), EVENTBOOKINGS_PLUGIN_URL . '/assets/icons/icon.png', 25);
        add_submenu_page('eventbookings-events', 'EventBookings', 'Events', 'manage_options', 'eventbookings-events', array(__CLASS__, 'eventbookings_events_page'));
        add_submenu_page('eventbookings-events', 'EventBookings', 'Settings', 'manage_options', 'eventbookings-settings', array(__CLASS__, 'eventbookings_settings_page'));
    }

    // Redirects to Events when the main "EventBookings" menu is clicked
    public static function eventbookings_redirect_to_events()
    {
        wp_redirect(admin_url('admin.php?page=event-list'));
        exit;
    }

    /**
     * Register plugin settings
     *
     * @since 1.1
     */
    public static function eventbookings_register_settings()
    {
        register_setting('my_plugin_options_group', 'eventbookings_client_id', [
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        register_setting('my_plugin_options_group', 'eventbookings_client_secret', [
            'sanitize_callback' => 'sanitize_text_field',
        ]);
    }

    /**
     * Check if plugin has saved credentials in database
     *
     * @since 1.1
     * @return object|false Database row with credentials or false if not found
     */
    private static function eventbookings_has_saved_credentials()
    {
        global $wpdb;

        // Execute with a prepared statement for the LIMIT value
        $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}eb_plugin_users LIMIT %d", 1));

        return $row ? $row : false;
    }


    // Event Settings Page
    public static function eventbookings_settings_page()
    {
        // Hook scripts/styles specifically for this settings page

        global $wpdb;

        $post_data = wp_unslash($_POST);

        $table_name = $wpdb->prefix . 'customized_events';

        // Get the first row from the table
        $event_settings = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i LIMIT %d", $table_name, 1));
        // Handle saving settings
        if (isset($post_data['save_settings'])) {
            if (!isset($post_data['eventbookings_nonce_field']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($post_data['eventbookings_nonce_field'])), 'eventbookings_secure_action')) {
                wp_send_json_error(['message' => 'Invalid nonce']);
                wp_die();
            }
            $wpdb->update(
                $table_name,
                [
                    'display_event_description' => isset($post_data['display_event_description']) ? 1 : 0,
                    'display_countdown' => isset($post_data['display_countdown']) ? 1 : 0,
                    'display_booking_start_countdown' => isset($post_data['display_booking_start_countdown']) ? 1 : 0,
                    'display_discount_end_countdown' => isset($post_data['display_discount_end_countdown']) ? 1 : 0,
                    'display_event_start_countdown' => isset($post_data['display_event_start_countdown']) ? 1 : 0,
                    'display_event_end_countdown' => isset($post_data['display_event_end_countdown']) ? 1 : 0,
                    'display_ticket_price_on_event_page' => isset($post_data['display_ticket_price_on_event_page']) ? 1 : 0,
                    'display_event_location_map' => isset($post_data['display_event_location_map']) ? 1 : 0,
                    'display_terms_and_condition' => isset($post_data['display_terms_and_condition']) ? 1 : 0,
                ],
                ['id' => $event_settings->id] // Update first row
            );
        }
        $event_settings = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i LIMIT %d", $table_name, 1));
        // Handle Connect or Disconnect actions
        if (isset($post_data['connect'])) {


            if (!isset($post_data['eventbookings_nonce_field']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($post_data['eventbookings_nonce_field'])), 'eventbookings_secure_action')) {
                wp_send_json_error(['message' => 'Invalid nonce']);
                wp_die();
            }
            self::eventbookings_connect_user();
        }
        if (isset($post_data['disconnect'])) {
            if (!isset($post_data['eventbookings_nonce_field']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($post_data['eventbookings_nonce_field'])), 'eventbookings_secure_action')) {
                wp_send_json_error(['message' => 'Invalid nonce']);
                wp_die();
            }
            self::eventbookings_disconnect_plugin();
        }

        $saved_data = self::eventbookings_has_saved_credentials();
        $client_id = get_option('eventbookings_client_id', '');
        $client_secret = get_option('eventbookings_client_secret', '');

        ?>

        <div class="event-settings-wrap">
            <h1 style="margin: 30px 0 20px;">Event Settings</h1>
            <h2 style="margin: 0 0 10px;">Connection Setting</h2>
            <form method="post">
                <div class="connection-settings-display-table-wrap">
                    <table class="connection-settings-display-table wp-list-table widefat fixed">
                        <tr>
                            <th><label for="eb_client_id">Client ID</label></th>
                            <td>
                                <input type="text" id="eb_client_id" name="eb_client_id"
                                       value="<?php echo esc_attr($client_id); ?>"
                                       class="regular-text"
                                    <?php echo $saved_data ? 'disabled' : ''; ?> />
                                <a class="" style="margin-top: 6px; display: inline-flex; align-items: center;"
                                   href="https://support.eventbookings.com/how-to-create-an-application-for-eventbookings/"
                                   target="_blank">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12px" height="12px"
                                         viewBox="0 0 24 24" fill="none">
                                        <circle cx="12" cy="12" r="10" stroke="#2271b1" stroke-width="1.5"/>
                                        <path d="M12 17V11" stroke="#2271b1" stroke-width="1.5" stroke-linecap="round"/>
                                        <circle cx="1" cy="1" r="1" transform="matrix(1 0 0 -1 11 9)" fill="#2271b1"/>
                                        <script xmlns=""/>
                                    </svg>
                                    <span style="margin-left: 5px; margin-top: -2px;">How to Get Client ID and Client Secret</span>
                                </a>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="eb_client_secret">Client Secret</label></th>
                            <td>
                                <input type="text" id="eb_client_secret" name="eb_client_secret"
                                       value="<?php echo esc_attr($client_secret); ?>"
                                       class="regular-text"
                                    <?php echo $saved_data ? 'disabled' : ''; ?> />
                            </td>
                        </tr>
                        <?php wp_nonce_field('eventbookings_save_client_credentials', 'eventbookings_client_nonce'); ?>
                    </table>
                </div>

                <?php if ($saved_data): ?>
                    <?php wp_nonce_field('eventbookings_secure_action', 'eventbookings_nonce_field'); ?>
                    <button type="submit" name="disconnect" class="button button-secondary">Disconnect</button>
                    <hr style="margin: 20px 0; max-width: 780px; width: 100%;"/>
                    <h2 style="margin: 0 0 10px;">Shortcode</h2>
                    <div class="shortcode-input-box">
                        <label>Events Shortcode</label>
                        <input type="text" class="event_shortcode" value="[eventbookings_events_shortcode]" disabled>
                        <button type="button" class="js-copy-button">Copy</button>
                        <div class="js-copy-success shortcode-copy-success" style="display: none">Copied</div>
                    </div>

                    <div class="shortcode-input-box">
                        <label>Features Events Shortcode</label>
                        <input type="text" class="event_shortcode" value="[eventbookings_feature_events_shortcode]"
                               disabled>
                        <button type="button" class="js-copy-button">Copy</button>
                        <div class="js-copy-success shortcode-copy-success" style="display: none">Copied</div>
                    </div>
                    <hr style="margin: 20px 0; max-width: 780px; width: 100%;"/>
                    <h2 style="margin: 0 0 10px;">Customize Event Display</h2>
                    <div class="customize-event-display-table-wrap">
                        <table class="customize-event-display-table wp-list-table widefat fixed">
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox" name="display_event_description"
                                        <?php echo $event_settings->display_event_description ? 'checked' : ''; ?> />
                                    <span>Display Event Description</span>
                                </td>
                            </tr>

                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox"
                                           name="display_booking_start_countdown"
                                        <?php echo $event_settings->display_booking_start_countdown ? 'checked' : ''; ?> />
                                    <span>Display Booking Start Countdown</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox"
                                           name="display_discount_end_countdown"
                                        <?php echo $event_settings->display_discount_end_countdown ? 'checked' : ''; ?> />
                                    <span>Display early bird discount ends countdown</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox"
                                           name="display_event_start_countdown"
                                        <?php echo $event_settings->display_event_start_countdown ? 'checked' : ''; ?> />
                                    <span>Display event starts countdown</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox"
                                           name="display_event_end_countdown"
                                        <?php echo $event_settings->display_event_end_countdown ? 'checked' : ''; ?> />
                                    <span>Display event ends countdown</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox" name="display_event_location_map"
                                        <?php echo $event_settings->display_event_location_map ? 'checked' : ''; ?> />
                                    <span>Display event location map</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox"
                                           name="display_ticket_price_on_event_page"
                                        <?php echo $event_settings->display_ticket_price_on_event_page ? 'checked' : ''; ?> />
                                    <span>Display Ticket Price</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input style="margin-bottom: 2px;" type="checkbox"
                                           name="display_terms_and_condition"
                                        <?php echo $event_settings->display_terms_and_condition ? 'checked' : ''; ?> />
                                    <span>Display terms and conditions</span>
                                </td>
                            </tr>

                        </table>
                    </div>
                    <?php wp_nonce_field('eventbookings_secure_action', 'eventbookings_nonce_field'); ?>
                    <button type="submit" name="save_settings" class="button button-primary">Save Settings</button>
                <?php else: ?>
                    <?php wp_nonce_field('eventbookings_secure_action', 'eventbookings_nonce_field'); ?>
                    <button type="submit" name="connect" class="button button-primary">Connect</button>
                <?php endif; ?>
            </form>
        </div>

        <?php
        if (!$saved_data && isset($post_data['connect'])) {
            echo '<div class="error"><p>Invalid Client ID or Client Secret.</p></div>';
            return;
        }
        // Handle saving settings
        if (isset($post_data['save_settings'])) {

            echo '<div class="updated"><p>Settings saved successfully!</p></div>';
        }
    }

    public static function eventbookings_connect_user()
    {
        if (
            !isset($_POST['eventbookings_client_nonce']) ||
            !wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['eventbookings_client_nonce'])),
                'eventbookings_save_client_credentials'
            )
        ) {
            wp_die();
        }
        if (!isset($_POST['eb_client_id'], $_POST['eb_client_secret'])) {
            wp_die();
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'eb_plugin_users';

        $client_id = sanitize_text_field(wp_unslash($_POST['eb_client_id']));
        $client_secret = sanitize_text_field(wp_unslash($_POST['eb_client_secret']));

        // Step 1: Get access token
        $access_token = self::eventbookings_token_by_client_id_secret($client_id, $client_secret);
        if (!$access_token) {
            eventbookings_log('error', 'Failed to obtain access token', ['client_id' => $client_id]);
            return;
        }

        eventbookings_log('info', 'Successfully obtained access token', ['client_id' => $client_id]);

        // Step 2: Decode JWT to get org_uuid
        $org_uuid = self::eventbookings_extract_org_uuid($access_token);

        // Step 3: Save to DB
        $wpdb->replace(
            $table_name,
            [
                'client_id' => $client_id,
                'client_secret' => $client_secret,
                'access_token' => $access_token,
                'org_uuid' => $org_uuid
            ],
            ['%s', '%s', '%s', '%s']
        );

        // Step 4: Save in WP options
        update_option('eventbookings_client_id', $client_id);
        update_option('eventbookings_client_secret', $client_secret);

//        require_once EB_PLUGIN_PATH . 'includes/class-eventbookings-event-sync.php';
//        EB_Event_Sync::sync_events();

//        wp_redirect(admin_url('admin.php?page=eventbookings-settings'));
//        exit;
    }

    public static function eventbookings_disconnect_plugin()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'eb_plugin_users';
        $wpdb->query($wpdb->prepare("DELETE FROM %i", $table_name));  // Remove credentials
        $table_name = $wpdb->prefix . 'events';
        $wpdb->query($wpdb->prepare("DELETE FROM %i", $table_name));  // Remove credentials
        delete_option('eventbookings_client_id');
        delete_option('eventbookings_client_secret');

        wp_redirect(admin_url('admin.php?page=eventbookings-settings'));
//        exit;
    }


    private static function eventbookings_token_by_client_id_secret($client_id, $client_secret)
    {
        $url = EVENTBOOKINGS_IDENTITY_URL . '/connect/token';

        $post_fields = [
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'grant_type' => 'client_credentials',
            'scopes' => 'openid profile offline_access email',
        ];

        $response = wp_remote_post($url, [
            'body' => $post_fields,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'timeout' => 20,
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        return $body['access_token'] ?? false;
    }


    private static function eventbookings_extract_org_uuid($jwt_token)
    {
        $token_parts = explode('.', $jwt_token);
        if (count($token_parts) < 2) return null;

        $payload = json_decode(base64_decode($token_parts[1]), true);
        return $payload['client_OrgId'] ?? null;
    }

    // Events Page
    public static function eventbookings_events_page()
    {
        ?>
        <div class='wrap event-list-wrap'>
            <h1>Events List</h1>
            <p>Here, you can manage all events.</p>

            <!-- Filters & Bulk Actions -->
            <div class="meta-box">
                <select id="bulk-action">
                    <option value="">Bulk Actions</option>
                    <option value="activate">Bulk Activate</option>
                    <option value="deactivate">Bulk Deactivate</option>
                </select>
                <button id="apply-bulk-action" class="button">Apply</button>
                <div class="search-box">
                    <input type="text" id="search-events" placeholder="Search Events">
                    <span>
                        <svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M11.2667 12.9824L6.88333 8.59909C6.55 8.88798 6.16111 9.11298 5.71667 9.27409C5.27222 9.4352 4.8 9.51575 4.3 9.51575C3.1 9.51575 2.08333 9.09909 1.25 8.26575C0.416667 7.43242 0 6.42687 0 5.24909C0 4.07131 0.416667 3.06576 1.25 2.23242C2.08333 1.39909 3.09444 0.982422 4.28333 0.982422C5.46111 0.982422 6.46389 1.39909 7.29167 2.23242C8.11944 3.06576 8.53333 4.07131 8.53333 5.24909C8.53333 5.72687 8.45556 6.18798 8.3 6.63242C8.14444 7.07687 7.91111 7.49353 7.6 7.88242L12 12.2491L11.2667 12.9824ZM4.28333 8.51575C5.18333 8.51575 5.95 8.19631 6.58333 7.55742C7.21667 6.91853 7.53333 6.14909 7.53333 5.24909C7.53333 4.34909 7.21667 3.57964 6.58333 2.94076C5.95 2.30187 5.18333 1.98242 4.28333 1.98242C3.37222 1.98242 2.59722 2.30187 1.95833 2.94076C1.31944 3.57964 1 4.34909 1 5.24909C1 6.14909 1.31944 6.91853 1.95833 7.55742C2.59722 8.19631 3.37222 8.51575 4.28333 8.51575Z"
                              fill="black"/>
                        </svg>
                    </span>
                </div>
                <select id="filter-status">
                    <option value="">Event Status: All</option>
                    <option value="published">Published</option>
                    <option value="ended">Ended</option>
                    <option value="draft">Draft</option>
                    <option value="live">Live</option>
                    <option value="unpublished">Unpublished</option>
                </select>

                <select id="filter-display">
                    <option value="">Event Display: All</option>
                    <option value="showed">Showed Event</option>
                    <option value="hidden">Hidden Event</option>
                </select>
                <button id="apply-clear-action" class="button">Clear</button>

                <button id="sync-event-action" class="button btn-right-align"
                        style="margin-left: auto; display: inline-flex; align-items: center; justify-content: center; gap: 5px;">
                    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"
                         width="12" height="12" x="0" y="0" viewBox="0 0 128 128"
                         style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g>
                            <path d="M16 64a4 4 0 0 1-8 0C8 33.121 33.121 8 64 8c15.391 0 29.632 6.133 40 16.693V12a4 4 0 0 1 8 0v24a4 4 0 0 1-4 4H84a4 4 0 0 1 0-8h15.908C90.933 21.904 78.022 16 64 16c-26.467 0-48 21.533-48 48zm100-4a4 4 0 0 0-4 4c0 26.467-21.533 48-48 48-14.022 0-26.933-5.904-35.908-16H44a4 4 0 0 0 0-8H20a4 4 0 0 0-4 4v24a4 4 0 0 0 8 0v-12.693C34.368 113.867 48.609 120 64 120c30.879 0 56-25.121 56-56a4 4 0 0 0-4-4z"
                                  fill="#2271b1" opacity="1" data-original="#000000" class=""></path>
                        </g></svg>
                    Sync
                </button>
            </div>

            <!-- Events Table -->
            <div class="table-wrap">
                <table class='wp-list-table widefat fixed striped event-lists'>
                    <thead>
                    <tr>
                        <th><input type='checkbox' id="select-all" style="margin: 0;"></th>
                        <th>Event Name</th>
                        <th>Starts On</th>
                        <th>Ticket Price</th>
                        <th>Qty Sold</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>View on list</th>
                        <th>Feature</th>
                    </tr>
                    </thead>
                    <tbody id="event-table-body">
                    <!-- Events will be loaded via AJAX -->
                    </tbody>
                </table>
            </div>
            <!-- Pagination Controls -->
            <div class="bottom-pagination-wrap">
                <select id="filter-limit">
                    <option value="10">10</option>
                    <option value="15">15</option>
                    <option value="25">25</option>
                    <!--                    <option value="50">50</option>-->
                </select>
                <div id="pagination" class="bottom-pagination"></div>
            </div>
        </div>


        <?php
    }

    public static function eventbookings_fetch_events($query)
    {
        $saved_data = self::eventbookings_has_saved_credentials();

        $org_uuid = $saved_data->org_uuid; // Get this dynamically

        $api_url = EVENTBOOKINGS_BASE_URL . '/orgs/' . $org_uuid . '/events?' . $query; // Replace with actual API

        $response = Eventbookings_Api_Service::eventbookings_api_request_handler('GET', $api_url);
        // Check for errors
        if (isset($response['error'])) {
            return [];
        }

        return $response;
    }


}

function eventbookings_save_event_status()
{
    global $wpdb;

    // Check nonce for security
    if (
        !isset($_POST['event_status_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['event_status_nonce'])), 'eventbookings_admin_nonce')
    ) {
        wp_send_json_error(['message' => 'Invalid nonce.']);
        wp_die(); // always exit after sending JSON error
    }

    // Get data from request
    $event_uuid = isset($_POST['event_uuid']) ? sanitize_text_field(wp_unslash($_POST['event_uuid'])) : '';
    $status = isset($_POST['status']) ? intval($_POST['status']) : 0;

    if (!$event_uuid) {
        wp_send_json_error(['message' => 'Invalid event UUID']);
    }

    $table_name = $wpdb->prefix . 'events';

    if ($status == 1) {
        // Insert event if it's checked
        $wpdb->insert($table_name, [
            'uuid' => $event_uuid,
        ]);
    } else {
        // Delete event if unchecked
        $wpdb->delete($table_name, ['uuid' => $event_uuid]);
    }

    wp_send_json_success(['message' => 'Event status updated successfully']);
}

add_action('wp_ajax_eventbookings_save_event_status', 'eventbookings_save_event_status');
add_action('wp_ajax_nopriv_eventbookings_save_event_status', 'eventbookings_save_event_status'); // For non-logged-in users if needed

function eventbookings_save_featured_event_status()
{
    global $wpdb;

    // Check nonce for security
    if (
        !isset($_POST['event_status_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['event_status_nonce'])), 'eventbookings_admin_nonce')
    ) {
        wp_send_json_error(['message' => 'Invalid nonce.']);
        wp_die(); // always exit after sending JSON error
    }

    // Get data from request
    $event_uuid = isset($_POST['event_uuid']) ? sanitize_text_field(wp_unslash($_POST['event_uuid'])) : '';
    $status = isset($_POST['status']) ? intval($_POST['status']) : 0;

    if (!$event_uuid) {
        wp_send_json_error(['message' => 'Invalid event UUID']);
    }

    $table_name = $wpdb->prefix . 'eb_feature_events';

    if ($status == 1) {
        // Insert event if it's checked
        $wpdb->insert($table_name, [
            'uuid' => $event_uuid,
        ]);
    } else {
        // Delete event if unchecked
        $wpdb->delete($table_name, ['uuid' => $event_uuid]);
    }

    wp_send_json_success(['message' => 'Event status updated successfully']);
}

add_action('wp_ajax_eventbookings_save_featured_event_status', 'eventbookings_save_featured_event_status');
add_action('wp_ajax_nopriv_eventbookings_save_featured_event_status', 'eventbookings_save_featured_event_status'); // For non-logged-in users if needed


add_action('wp_ajax_eventbookings_load_events', 'eventbookings_load_events_ajax');
add_action('wp_ajax_nopriv_eventbookings_load_events', 'eventbookings_load_events_ajax'); // Allow for non-logged-in users if needed

function eventbookings_load_events_ajax()
{
    // Validate nonce for security
    if (!wp_verify_nonce($_POST['nonce'] ?? '', 'eventbookings_admin_nonce')) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }

    $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
    $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
    $status = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : '';
    $display = isset($_POST['display']) ? sanitize_text_field(wp_unslash($_POST['display'])) : '';

//    $per_page = 25; // Number of events per page
    $per_page = isset($_POST['limit']) ? max(5, min(100, intval($_POST['limit']))) : 10; // Number of events per page (5-100 range)

    $query_params = [
        'status' => $status,
        'order_by' => 'created_descending',
        'search_q' => $search,
        'position' => $page,
        'rows' => $per_page,
    ];

    $query = http_build_query($query_params);

    if (!empty($display) && $display == "showed") {
        global $wpdb;

        // Get event UUIDs from the events table
        $table_name = $wpdb->prefix . 'events';
        $event_uuids = $wpdb->get_col($wpdb->prepare("SELECT uuid FROM %i", $table_name));
        $event_uuids_str = implode(',', $event_uuids);

        $query = $query . '&filter_by_ids=' . $event_uuids_str;
    }

    $res = Eventbookings_Settings::eventbookings_fetch_events($query);
    $events = $res['events'];


    // Apply pagination
    $total_events = $res['pagination']['records'];
    $total_pages = ceil($total_events / $per_page);


    // Generate table rows
    $html = "";
    foreach ($events as $event) {
        $event_uuid = $event['uuid'];
        global $wpdb;
        // Check if the event exists in the `eb_plugin_events` table
        $event_exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}events WHERE uuid = %s",
            $event_uuid
        ));
        $event_featured_exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}eb_feature_events WHERE uuid = %s",
            $event_uuid
        ));

        if ($display == "showed") {
            if (!$event_exists) {
                continue;
            }
        } else if ($display == "hidden") {
            if ($event_exists) {
                continue;
            }
        }

        // If event exists, checkbox should be checked
        $checked = ($event_exists > 0) ? 'checked' : '';
        $featured_checked = ($event_featured_exists > 0) ? 'checked' : '';
        if (!isset($event['activities'])) {
            $tickets_sold = 0;

        } else {
            $tickets_sold = array_column($event['activities'], 'value', 'name')['tickets_sold'] ?? 0;
        }

        $publishing_value = "";
        foreach ($event['extended_status'] as $item) {
            if ($item['name'] === 'publishing') {
                $publishing_value = $item['value'];
                break;
            }
        }

        $price = '';
        if (count($event['tickets']['levels']) != 0) {
            if (count($event['tickets']['levels']) == 1) {
                if ($event['tickets']['levels'][0]['pricing_details'][0]['price'] != 0) {
                    $price = $event['tickets']['levels'][0]['pricing_details'][0]['price'] . ' ' . $event['currency'];
                } else {
                    $price = "Free";
                }
            } else {
                $lastIndex = count($event['tickets']['levels']) - 1;
                $price1 = $event['tickets']['levels'][0]['pricing_details'][0]['price'] . ' ' . $event['currency'];
                $price2 = $event['tickets']['levels'][$lastIndex]['pricing_details'][0]['price'] . ' ' . $event['currency'];
                if ($price1 > $price2) {
                    $price = $price2;
                    $price .= " - ";
                    $price .= $price1;
                } else if ($price1 == $price2) {
                    $price = $price2;
                } else {
                    $price = $price1;
                    $price .= " - ";
                    $price .= $price2;
                }


            }

        }

        $html .= "<tr>
            <td><input type='checkbox' class='event-checkbox'></td>
            <td>{$event['display_name']}</td>
            <td>{$event['publising']['published_on']['local']}</td>
            <td>$price</td>
            <td>" . htmlspecialchars($tickets_sold) . "</td>
            <td>{$publishing_value}</td>
            <td>{$event['created_on']}</td>
            <td>
                <label class='switch'>
                    <input type='checkbox' class='toggle-status' data-id='{$event['uuid']}' $checked>
                    <span class='slider round'></span>
                </label>
            </td>
            <td>
                <label class='switch'>
                    <input type='checkbox' class='toggle-feature-status' data-id='{$event['uuid']}' $featured_checked>
                    <span class='slider round'></span>
                </label>
            </td>
        </tr>";
    }

    if (empty($html)) {
        $html = "<tr><td colspan='8' style='text-align: center;'>No events found.</td></tr>";
    }

    // Generate pagination
    $pagination = "";
    if ($total_pages > 1) {
        for ($i = 1; $i <= $total_pages; $i++) {
            $active_class = ($i == $page) ? "style='border-color: #007fff; color: #007fff;'" : "";
            $pagination .= "<a href='#' class='pagination-link' data-page='$i' $active_class>$i</a> ";
        }
    }

    wp_send_json([
        'html' => $html,
        'pagination' => $pagination,
        'total_pages' => $total_pages,
        'total_events' => $total_events,
        'events' => $events,
        'per_page' => $per_page,
        'page' => $page,
        'query' => $query,
    ]);
}
