<?php

class Eventbookings_Plugin_Shortcode
{
    public static function eventbookings_register_shortcode()
    {
        add_shortcode('eventbookings_events_shortcode', array(__CLASS__, 'eventbookings_render_shortcode'));
        add_shortcode('eventbookings_feature_events_shortcode', array(__CLASS__, 'eventbookings_render_features_shortcode'));
        add_shortcode('eventbookings_feature_event_details', array(__CLASS__, 'eventbookings_render_details_shortcode'));
        // Conditionally enqueue scripts/styles only if shortcode is used
        add_action('wp_enqueue_scripts', [__CLASS__, 'eventbookings_conditionally_enqueue_assets']);
    }

    /**
     * Load only when shortcode exists in post content
     */
    public static function eventbookings_conditionally_enqueue_assets()
    {
        global $post;

        if (!is_a($post, 'WP_Post')) {
            return;
        }

        if (has_shortcode($post->post_content, 'eventbookings_events_shortcode') ||
            has_shortcode($post->post_content, 'eventbookings_feature_events_shortcode') ||
            has_shortcode($post->post_content, 'eventbookings_feature_event_details')) {

            // Common styles
            wp_register_style('eventbookings-bootstrap', plugin_dir_url(__FILE__) . 'css/bootstrap.min.css', [], '5.3.0');
            wp_register_style('eventbookings-style', plugin_dir_url(__FILE__) . 'css/style.css', [], '1.2');

            // Common scripts
            wp_register_script('eventbookings-bootstrap', plugin_dir_url(__FILE__) . 'js/bootstrap.min.js', ['jquery'], '5.3.0', true);
            wp_register_script('eventbookings-popper', plugin_dir_url(__FILE__) . 'js/popper.min.js', ['jquery'], '2.0.0', true);
            wp_register_script('eventbookings-bundle', plugin_dir_url(__FILE__) . 'js/dist/component-bundle.js', ['jquery'], '1.2', true);
        }
    }

    /**
     * Regular Events Shortcode
     */
    public static function eventbookings_render_shortcode($atts)
    {
        $render_id = uniqid('events_');

        // Enqueue necessary assets
        wp_enqueue_style('eventbookings-bootstrap');
        wp_enqueue_style('eventbookings-style');
        wp_enqueue_script('eventbookings-bootstrap');
        wp_enqueue_script('eventbookings-popper');
        wp_enqueue_script('eventbookings-bundle');

        wp_enqueue_script("eventbookings-events-{$render_id}", plugin_dir_url(__FILE__) . 'js/shortcode.js', ['jquery'], '1.2', true);
        $localized_object_name = "eventbookings_events_obj_" . $render_id;
        // Localize per instance
        wp_localize_script("eventbookings-events-{$render_id}", "eventbookings_events_obj_{$render_id}", [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'ajax_nonce' => wp_create_nonce('eventbookings_wp'),
            'details_slug' => get_option('eventbookings_details_page_slug'),
            'render_id' => esc_attr($render_id),
            'EVENTBOOKINGS_REMOTE_PAYMENT_URL' => EVENTBOOKINGS_REMOTE_PAYMENT_URL,
            'seatplan' => EVENTBOOKINGS_SEATPLAN_URL,
        ]);

        ob_start();
        ?>
        <div class="container">
            <div class="list-loading show" style="display:none; text-align:center;">
                <div class="eventbookings-loader">
                    <div></div>
                    <div></div>
                    <div></div>
                </div>
            </div>
            <div class="row eb-wp-event-lists-<?php echo esc_attr($render_id); ?>"></div>
            <div class="row eb-frontend-pagination eb-wp-event-lists-pagination-<?php echo esc_attr($render_id); ?>"></div>
            <div id="eb_wp_atts_<?php echo esc_attr($render_id); ?>"
                 data-localize-object="<?php echo esc_attr($localized_object_name); ?>"></div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Featured Events Shortcode
     */
    public static function eventbookings_render_features_shortcode($atts)
    {
        $render_id = uniqid('featured_');

        // Enqueue assets
        wp_enqueue_style('eventbookings-bootstrap');
        wp_enqueue_style('eventbookings-style');
        wp_enqueue_style('eventbookings-owl', plugin_dir_url(__FILE__) . 'css/owl.carousel.min.css', [], '2.3.4');
        wp_enqueue_style('eventbookings-owl-theme', plugin_dir_url(__FILE__) . 'css/owl.theme.default.min.css', [], '2.3.4');

        wp_enqueue_script('eventbookings-bootstrap');
        wp_enqueue_script('eventbookings-popper');
        wp_enqueue_script('eventbookings-bundle');
        wp_enqueue_script('eventbookings-owl', plugin_dir_url(__FILE__) . 'js/owl.carousel.min.js', ['jquery'], '2.3.4', true);

        wp_enqueue_script("eventbookings-featured-{$render_id}", plugin_dir_url(__FILE__) . 'js/featured_event.js', ['jquery'], '1.2', true);
        $localized_object_name = "eventbookings_featured_obj_" . $render_id;
        // Localize per instance
        wp_localize_script("eventbookings-featured-{$render_id}", "eventbookings_featured_obj_{$render_id}", [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'ajax_nonce' => wp_create_nonce('eventbookings_wp'),
            'details_slug' => get_option('eventbookings_details_page_slug'),
            'render_id' => esc_attr($render_id),
            'EVENTBOOKINGS_REMOTE_PAYMENT_URL' => EVENTBOOKINGS_REMOTE_PAYMENT_URL,
            'seatplan' => EVENTBOOKINGS_SEATPLAN_URL,
        ]);

        ob_start();
        ?>
        <div class="eb-event-container">
            <div class="list-loading show" style="display:none; text-align:center;">
                <div class="eventbookings-loader">
                    <div></div>
                    <div></div>
                    <div></div>
                </div>
            </div>
            <div class="eb-wp-event-lists-<?php echo esc_attr($render_id); ?>"></div>
            <div class="eb-wp-event-details-<?php echo esc_attr($render_id); ?>" style="display: none"></div>
            <div class="eb-frontend-pagination eb-wp-event-lists-pagination-<?php echo esc_attr($render_id); ?>"></div>
        </div>
        <div id="eb_wp_feature_atts_<?php echo esc_attr($render_id); ?>"
             data-localize-object="<?php echo esc_attr($localized_object_name); ?>"></div>
        <?php
        return ob_get_clean();
    }

    public static function eventbookings_render_details_shortcode($atts)
    {
        $render_id = uniqid('featured_');

        // Enqueue assets
        wp_enqueue_style('eventbookings-bootstrap');
        wp_enqueue_style('eventbookings-style');
        wp_enqueue_style('eventbookings-owl', plugin_dir_url(__FILE__) . 'css/owl.carousel.min.css', [], '2.3.4');
        wp_enqueue_style('eventbookings-owl-theme', plugin_dir_url(__FILE__) . 'css/owl.theme.default.min.css', [], '2.3.4');

        wp_enqueue_script('eventbookings-bootstrap');
        wp_enqueue_script('eventbookings-popper');
        wp_enqueue_script('eventbookings-bundle');
        wp_enqueue_script('eventbookings-owl', plugin_dir_url(__FILE__) . 'js/owl.carousel.min.js', ['jquery'], '2.3.4', true);

        wp_enqueue_script("eventbookings-featured-{$render_id}", plugin_dir_url(__FILE__) . 'js/event_details.js', ['jquery'], '1.2', true);
        $localized_object_name = "eventbookings_featured_obj_" . $render_id;
        // Localize per instance
        wp_localize_script("eventbookings-featured-{$render_id}", "eventbookings_featured_obj_{$render_id}", [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'ajax_nonce' => wp_create_nonce('eventbookings_wp'),
            'event_uuid' => isset($_GET['eventUuid']) ? sanitize_text_field(wp_unslash($_GET['eventUuid'])) : '',
            'render_id' => esc_attr($render_id),
            'EVENTBOOKINGS_REMOTE_PAYMENT_URL' => EVENTBOOKINGS_REMOTE_PAYMENT_URL,
            'seatplan' => EVENTBOOKINGS_SEATPLAN_URL,
        ]);

        ob_start();
        if (isset($_GET['status']) && sanitize_text_field(wp_unslash($_GET['status'])) === 'success') { ?>
            <!-- Bootstrap Modal (Initially Hidden) -->
            <div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel"
                 aria-hidden="true"
                 style="z-index:99999">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="successModalLabel">Purchase Successful!</h5>
                            <button type="button" class="btn-close close-modal" data-bs-dismiss="modal"
                                    aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            Thank you for your purchase! Your order has been successfully processed.
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary close-modal" data-bs-dismiss="modal">OK
                            </button>
                        </div>
                    </div>
                </div>
            </div>

        <?php } ?>
        <div class="eb-event-container">
            <div class="list-loading show" style="display:block; text-align:center;">
                <div class="eventbookings-loader">
                    <div></div>
                    <div></div>
                    <div></div>
                </div>
            </div>
            <div class="eb-wp-event-lists-<?php echo esc_attr($render_id); ?>"></div>
            <div class="eb-wp-event-details-<?php echo esc_attr($render_id); ?>"></div>
            <div class="eb-frontend-pagination eb-wp-event-lists-pagination-<?php echo esc_attr($render_id); ?>"></div>
        </div>
        <div id="eb_wp_feature_atts_<?php echo esc_attr($render_id); ?>"
             data-localize-object="<?php echo esc_attr($localized_object_name); ?>"></div>
        <?php
        return ob_get_clean();
    }
}

add_action('wp_ajax_eventbookings_wp_get_events_public', 'eventbookings_get_events_public');
add_action('wp_ajax_nopriv_eventbookings_wp_get_events_public', 'eventbookings_get_events_public');

function eventbookings_get_events_public()
{
    // Validate nonce for security
    if (!wp_verify_nonce($_GET['ajax_nonce'] ?? '', 'eventbookings_wp')) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }

    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);
    $position = isset($_GET['position']) && $_GET['position'] != '' ? max(1, intval($_GET['position'])) : 1;

    // Create unique cache key based on parameters
    $cache_key = 'eventbookings_events_' . md5($event_uuids_str . '_' . $position);

    // Try to get cached response
    $cached_response = wp_cache_get($cache_key, 'eventbookings');

    if ($cached_response !== false) {
        header("Cache-Control: max-age=30000, public");
        wp_send_json_success($cached_response);
    }

    // If not cached, call API
    $api_url = EVENTBOOKINGS_BASE_URL . '/events?rows=6&position=' . $position . '&order_by=created_descending&caching=1&filter_by_ids=' . $event_uuids_str;

    $response = Eventbookings_Api_Service::eventbookings_api_request_handler('GET', $api_url);

    // Prepare response
    if ($response && isset($response['events'])) {
        $customized_table = $wpdb->prefix . 'customized_events';
        $org_uuid = eventbookings_get_org_uuid() ?: 'default-org-uuid';
        $customized_settings = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE organisation_uuid = %s", $customized_table, $org_uuid), ARRAY_A);

        if ($customized_settings) {
            foreach ($customized_settings as $key => $value) {
                $customized_settings[$key] = (bool)$value; // Typecast 1 -> true, 0 -> false
            }
        } else {
            // Default settings if none found
            $customized_settings = [
                'display_event_description' => true,
                'display_countdown' => true,
                'display_booking_start_countdown' => true,
                'display_discount_end_countdown' => true,
                'display_event_start_countdown' => true,
                'display_event_end_countdown' => true,
                'display_event_location_map' => true,
                'display_ticket_price_on_event_page' => true,
                'display_terms_and_condition' => true
            ];
        }

        $data = [
            'result' => [
                'events' => $response['events'],
                'pagination' => $response['pagination'],
                'customized_settings' => $customized_settings,
                'event_uuids_str' => $event_uuids_str,
            ]
        ];

        // Cache result for 5 minutes (300 seconds)
        wp_cache_set($cache_key, $data, 'eventbookings', 30000);

        header("Cache-Control: max-age=30000, public");
        wp_send_json_success($data);
    } else {
        wp_send_json_error(['message' => 'No events found or API error.']);
    }
}

add_action('wp_ajax_eventbookings_wp_get_events_featured', 'eventbookings_wp_get_events_featured');
add_action('wp_ajax_nopriv_eventbookings_wp_get_events_featured', 'eventbookings_wp_get_events_featured');

function eventbookings_wp_get_events_featured()
{
    // Validate nonce for security
    if (!wp_verify_nonce($_GET['ajax_nonce'] ?? '', 'eventbookings_wp')) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        return;
    }

    global $wpdb;

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

    $position = isset($_GET['position']) && $_GET['position'] != '' ? max(1, intval($_GET['position'])) : 1;

    // Build unique cache key
    $cache_key = 'eventbookings_featured_events_' . md5($event_uuids_str . '_' . $position);

    // Try fetching from cache
    $cached_response = wp_cache_get($cache_key, 'eventbookings');
    if ($cached_response !== false) {
        header("Cache-Control: max-age=30000, public");
        wp_send_json_success($cached_response);
    }

    // API call if no cache
    $api_url = EVENTBOOKINGS_BASE_URL . '/events?rows=16&position=' . $position . '&order_by=created_descending&caching=1&filter_by_ids=' . $event_uuids_str;
    $response = Eventbookings_Api_Service::eventbookings_api_request_handler('GET', $api_url);

    if ($response && isset($response['events'])) {
        // Fetch customized settings
        $customized_table = $wpdb->prefix . 'customized_events';
        $org_uuid = eventbookings_get_org_uuid() ?: 'default-org-uuid';
        $customized_settings = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE organisation_uuid = %s", $customized_table, $org_uuid), ARRAY_A);

        if ($customized_settings) {
            foreach ($customized_settings as $key => $value) {
                $customized_settings[$key] = (bool)$value;
            }
        } else {
            $customized_settings = [
                'display_event_description' => true,
                'display_countdown' => true,
                'display_booking_start_countdown' => true,
                'display_discount_end_countdown' => true,
                'display_event_start_countdown' => true,
                'display_event_end_countdown' => true,
                'display_event_location_map' => true,
                'display_ticket_price_on_event_page' => true,
                'display_terms_and_condition' => true
            ];
        }

        $data = [
            'result' => [
                'events' => $response['events'],
                'pagination' => $response['pagination'],
                'customized_settings' => $customized_settings,
                'event_uuids_str' => $event_uuids_str,
            ]
        ];

        // Cache for 5 minutes
        wp_cache_set($cache_key, $data, 'eventbookings', 30000);

        header("Cache-Control: max-age=30000, public");
        wp_send_json_success($data);
    } else {
        wp_send_json_error(['message' => 'No events found or API error.']);
    }
}

add_action('wp_ajax_eventbookings_wp_get_event_details', 'eventbookings_wp_get_event_details');
add_action('wp_ajax_nopriv_eventbookings_wp_get_event_details', 'eventbookings_wp_get_event_details');

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

    // Validate and sanitize event UUID
    $event_uuid = isset($_POST['eventUuid']) ? sanitize_text_field(wp_unslash($_POST['eventUuid'])) : '';
    if (empty($event_uuid)) {
        wp_send_json_error(['message' => 'Event UUID is required']);
        return;
    }

    $api_url = EVENTBOOKINGS_BASE_URL . '/events/' . $event_uuid; // Replace with actual API

    $response = Eventbookings_Api_Service::eventbookings_api_request_handler('GET', $api_url);
    if ($response && isset($response['event'])) {
        // Fetch customized settings
        global $wpdb;
        $customized_table = $wpdb->prefix . 'customized_events';
        $org_uuid = eventbookings_get_org_uuid() ?: 'default-org-uuid';
        $customized_settings = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE organisation_uuid = %s", $customized_table, $org_uuid), ARRAY_A);

        if ($customized_settings) {
            foreach ($customized_settings as $key => $value) {
                $customized_settings[$key] = (bool)$value;
            }
        } else {
            $customized_settings = [
                'display_event_description' => true,
                'display_countdown' => true,
                'display_booking_start_countdown' => true,
                'display_discount_end_countdown' => true,
                'display_event_start_countdown' => true,
                'display_event_end_countdown' => true,
                'display_event_location_map' => true,
                'display_ticket_price_on_event_page' => true,
                'display_terms_and_condition' => true
            ];
        }

        $data = [

            'event' => $response['event'],

            'customized_settings' => $customized_settings,


        ];

        // Cache for 5 minutes


        header("Cache-Control: max-age=30000, public");
        wp_send_json_success($data);
    } else {
        wp_send_json_error(['message' => 'No events found or API error.']);
    }

}

add_action('wp_ajax_eventbookings_wp_ticket_purchase', 'eventbookings_wp_ticket_purchase');
add_action('wp_ajax_nopriv_eventbookings_wp_ticket_purchase', 'eventbookings_wp_ticket_purchase');

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

    // Validate required fields
    if (!isset($_POST['order']) || empty($_POST['order'])) {
        wp_send_json_error(['message' => 'Order data is required']);
        return;
    }

    // Decode the JSON string sent from AJAX into an associative array
    $order_json = wp_unslash($_POST['order']);


    // Define the API URL dynamically
    $api_url = EVENTBOOKINGS_BASE_URL . '/orders';

    // Call the place_order function and output the result
//    echo place_order($data, $api_url);
//    die();
    $response = eventbookings_place_order($order_json, $api_url);
    wp_send_json($response);

}

function eventbookings_place_order($data, $api_url, $retry = true)
{
    // Get the access token from your API service
    $access_token = Eventbookings_Api_Service::eventbookings_get_access_token();
    if (!$access_token) {
        return json_encode(['error' => 'Invalid or missing access token']);
    }

    // Prepare the request body and headers
    $json_data = json_encode(['order' => $data]);

    $args = [
        'method' => 'POST',
        'headers' => [
            'Authorization' => 'Bearer ' . $access_token,
            'Content-Type' => 'application/json',
        ],
        'body' => $json_data,
        'timeout' => 20,
    ];

    // Make the request
    $response = wp_remote_post($api_url, $args);

    // Handle WP error
    if (is_wp_error($response)) {
        return json_encode(['error' => $response->get_error_message()]);
    }

    $http_code = wp_remote_retrieve_response_code($response);
    $body = wp_remote_retrieve_body($response);
    $decoded = json_decode($body, true);

    // Retry logic: if token expired or access denied, retry once
    if (($http_code == 401 || (isset($decoded['error']) && strpos(strtolower($decoded['error']), 'access denied') !== false)) && $retry) {
        $new_token = Eventbookings_Api_Service::eventbookings_fetch_new_token();
        if ($new_token) {
            return eventbookings_place_order($data, $api_url, false); // Retry with new token
        }
    }

    return $body;
}