<?php
defined('ABSPATH') || exit; // Exit if accessed directly

if (! class_exists('Gridpress_Grid_Shortcode')) {
    class Gridpress_Grid_Shortcode {

        private static function verify_front_request() {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Central nonce validation function
            check_ajax_referer('gridpress_front_nonce', 'gridpress_nonce');
        }

        public function __construct() {
            add_shortcode('gridpress_grid', [$this, 'gridpress_shortcode']);
            add_action('gridpress_card_item_term_classes', [$this, 'gridpress_item_term_classes'], 10, 3);

            add_action('wp_ajax_gridpress_cards_pagination_pagenum_call', [$this, 'gridpress_cards_pagination_pagenum_call']);
            add_action('wp_ajax_nopriv_gridpress_cards_pagination_pagenum_call', [$this, 'gridpress_cards_pagination_pagenum_call']);

            add_action('wp_ajax_gridpress_cards_top_terms_filter_call', [$this, 'gridpress_cards_top_terms_filter_call']);
            add_action('wp_ajax_nopriv_gridpress_cards_top_terms_filter_call', [$this, 'gridpress_cards_top_terms_filter_call']);

            add_action('wp_ajax_gridpress_addin_card_video', [$this, 'gridpress_addin_card_video']);
            add_action('wp_ajax_nopriv_gridpress_addin_card_video', [$this, 'gridpress_addin_card_video']);
            add_action('wp_footer', [$this, 'gridpress_grid_sh_popup']);
            add_action('wp_head', [$this, 'gridpress_grid_sh_styles']);
        }

        public function gridpress_shortcode($atts = []) {
            $gridpress_grid_id = isset($atts['id']) ? $atts['id'] : '';

            if (get_post_type($gridpress_grid_id) != 'gridpress_grid') {
                return '';
            }

            set_query_var('gridpress_grid_id', $gridpress_grid_id);

            $gridpress_grid_all_settings = get_post_meta($gridpress_grid_id, 'gridpress_grid_settings', true);
            $gridpress_grid_style = isset($gridpress_grid_all_settings['grid_style']) ? $gridpress_grid_all_settings['grid_style'] : '';
            $gridpress_source_data_type = isset($gridpress_grid_all_settings['data_source']) ? $gridpress_grid_all_settings['data_source'] : '';

            set_query_var('gridpress_grid_style', $gridpress_grid_style);
            set_query_var('gridpress_display_settings', isset($gridpress_grid_all_settings['display']) ? $gridpress_grid_all_settings['display'] : '');

            $gridpress_pagination = false;

            $gridpress_itms_data = [];
            if ($gridpress_source_data_type == 'manual') {
                $gridpress_card_items = isset($gridpress_grid_all_settings['cards']) ? $gridpress_grid_all_settings['cards'] : '';
                if (!empty($gridpress_card_items) && is_array($gridpress_card_items)) {

                    $gridpress_title_length = isset($gridpress_grid_all_settings['display']['title_length']) ? $gridpress_grid_all_settings['display']['title_length'] : '';
                    $gridpress_excerpt_length = isset($gridpress_grid_all_settings['display']['excerpt_length']) ? $gridpress_grid_all_settings['display']['excerpt_length'] : '';

                    foreach ($gridpress_card_items as $gridpress_card_item_id => $gridpress_card_item) {
                        $gridpress_post_title = isset($gridpress_card_item['title']) ? $gridpress_card_item['title'] : '';
                        //
                        $gridpress_short_title = $gridpress_post_title;
                        if ($gridpress_title_length > 0) {
                            $gridpress_short_title = wp_trim_words($gridpress_post_title, $gridpress_title_length, '...');
                        }
                        //
                        $gridpress_item_url = isset($gridpress_card_item['item_url']) ? $gridpress_card_item['item_url'] : '';
                        $gridpress_media_type = isset($gridpress_card_item['m_type']) ? $gridpress_card_item['m_type'] : 'image';
                        $gridpress_imag_url = isset($gridpress_card_item['image']) ? $gridpress_card_item['image'] : '';
                        $gridpress_imag_attach_id = isset($gridpress_card_item['image_attach_id']) ? $gridpress_card_item['image_attach_id'] : '';
                        $gridpress_video_url = isset($gridpress_card_item['video']) ? $gridpress_card_item['video'] : '';
                        $gridpress_post_excerpt = isset($gridpress_card_item['excerpt']) ? $gridpress_card_item['excerpt'] : '';
                        //
                        $gridpress_short_excerpt = $gridpress_post_excerpt;
                        if ($gridpress_excerpt_length > 0) {
                            $gridpress_short_excerpt = wp_trim_words($gridpress_post_excerpt, $gridpress_excerpt_length, '...');
                        }
                        //
                        $gridpress_post_date = isset($gridpress_card_item['date']) ? $gridpress_card_item['date'] : '';
                        $gridpress_author_name = isset($gridpress_card_item['author_name']) ? $gridpress_card_item['author_name'] : '';
                        $gridpress_category = isset($gridpress_card_item['category']) ? $gridpress_card_item['category'] : '';
                        $gridpress_comments = isset($gridpress_card_item['comments']) ? $gridpress_card_item['comments'] : '';
                        $gridpress_itm_data_topass = [
                            'id' => $gridpress_card_item_id,
                            'type' => 'manual',
                            'title' => $gridpress_post_title,
                            'short_title' => $gridpress_short_title,
                            'url' => $gridpress_item_url,
                            'excerpt' => $gridpress_post_excerpt,
                            'short_excerpt' => $gridpress_short_excerpt,
                            'media_type' => $gridpress_media_type,
                            'imag_url' => $gridpress_imag_url,
                            'imag_attach_id' => $gridpress_imag_attach_id,
                            'post_date' => $gridpress_post_date,
                            'author' => $gridpress_author_name,
                            'author_image' => (isset($gridpress_card_item['author_image']) ? $gridpress_card_item['author_image'] : ''),
                            'author_image_attach_id' => (isset($gridpress_card_item['author_image_attach_id']) ? $gridpress_card_item['author_image_attach_id'] : ''),
                            'item_views' => (isset($gridpress_card_item['item_views']) ? $gridpress_card_item['item_views'] : ''),
                            'item_likes' => (isset($gridpress_card_item['item_likes']) ? $gridpress_card_item['item_likes'] : ''),
                            'behance_url' => (isset($gridpress_card_item['behance_url']) ? $gridpress_card_item['behance_url'] : ''),
                            'category' => $gridpress_category,
                            'comments' => $gridpress_comments,
                        ];
                        if ($gridpress_grid_style == 'style15') {
                            $gridpress_itm_data_topass['sec_image'] = isset($gridpress_card_item['sec_image']) ? $gridpress_card_item['sec_image'] : '';
                            $gridpress_itm_data_topass['sec_image_attach_id'] = isset($gridpress_card_item['sec_image_attach_id']) ? $gridpress_card_item['sec_image_attach_id'] : '';
                            $gridpress_itm_data_topass['sec_image_url'] = isset($gridpress_card_item['sec_image_url']) ? $gridpress_card_item['sec_image_url'] : '';
                        }
                        if ($gridpress_grid_style == 'style19') {
                            $gridpress_itm_data_topass['bg_color'] = isset($gridpress_card_item['bg_color']) ? $gridpress_card_item['bg_color'] : '';
                        }
                        if ($gridpress_media_type == 'video') {
                            $gridpress_itm_data_topass['video_url'] = $gridpress_video_url;
                            $gridpress_itm_data_topass['thumb_image'] = isset($gridpress_card_item['thumb_image']) ? $gridpress_card_item['thumb_image'] : '';
                            $gridpress_itm_data_topass['thumb_image_attach_id'] = isset($gridpress_card_item['thumb_image_attach_id']) ? $gridpress_card_item['thumb_image_attach_id'] : '';
                            $gridpress_itm_data_topass['video_views'] = isset($gridpress_card_item['video_views']) ? $gridpress_card_item['video_views'] : '';
                            $gridpress_itm_data_topass['video_likes'] = isset($gridpress_card_item['video_likes']) ? $gridpress_card_item['video_likes'] : '';
                        }
                        $gridpress_itms_data[] = $gridpress_itm_data_topass;
                    }
                }
            } else {
                $gridpress_posts_data_type = isset($gridpress_grid_all_settings['posts']['data_type']) ? $gridpress_grid_all_settings['posts']['data_type'] : '';
                $gridpress_posts_post_type = isset($gridpress_grid_all_settings['posts']['post_type']) ? $gridpress_grid_all_settings['posts']['post_type'] : '';
                //
                set_query_var('gridpress_posts_data_type', $gridpress_posts_data_type);
                set_query_var('gridpress_post_type', $gridpress_posts_post_type);
                if ($gridpress_posts_data_type == 'selected') {
                    $gridpress_posts_ids = isset($gridpress_grid_all_settings['posts']['selected']['items']) ? $gridpress_grid_all_settings['posts']['selected']['items'] : '';
                    if (!empty($gridpress_posts_ids)) {
                        $gridpress_posts_order_by = 'ID';
                        $gridpress_posts_order = 'DESC';
                        $gridpress_args = array(
                            'post_type' => $gridpress_posts_post_type,
                            'posts_per_page' => count($gridpress_posts_ids),
                            'post__in' => $gridpress_posts_ids,
                            'orderby' => $gridpress_posts_order_by,
                            'order' => $gridpress_posts_order,
                        );

                        $gridpress_posts_query = new WP_Query($gridpress_args);
                        $gridpress_found_posts = $gridpress_posts_query->found_posts;
                        if ($gridpress_posts_query->have_posts()) {
                            $gridpress_posts_data = $gridpress_posts_query->posts;
                            foreach ($gridpress_posts_data as $gridpress_post_obj) {
                                if (isset($gridpress_post_obj->ID)) {
                                    $gridpress_itms_data[] = $this->gridpress_post_obj_to_itm_data($gridpress_post_obj, $gridpress_grid_all_settings);
                                }
                            }
                            wp_reset_postdata();
                        }
                        set_query_var('gridpress_total_posts', $gridpress_found_posts);
                    }
                } else {
                    $gridpress_posts_order_by = isset($gridpress_grid_all_settings['posts']['all']['order_by']) ? $gridpress_grid_all_settings['posts']['all']['order_by'] : '';
                    $gridpress_posts_order = isset($gridpress_grid_all_settings['posts']['all']['order']) ? $gridpress_grid_all_settings['posts']['all']['order'] : '';
                    $gridpress_num_posts = isset($gridpress_grid_all_settings['posts']['all']['num_posts']) ? $gridpress_grid_all_settings['posts']['all']['num_posts'] : '';
                    $gridpress_num_posts = $gridpress_num_posts > 0 ? $gridpress_num_posts : 20;
                    $gridpress_page_type = isset($gridpress_grid_all_settings['posts']['all']['page_type']) ? $gridpress_grid_all_settings['posts']['all']['page_type'] : '';

                    $gridpress_args = array(
                        'post_type' => $gridpress_posts_post_type,
                        'posts_per_page' => $gridpress_num_posts,
                        'orderby' => $gridpress_posts_order_by,
                        'order' => $gridpress_posts_order,
                    );

                    $gridpress_post_taxonomies = Gridpress_Grid_settings::gridpress_get_post_taxonomies($gridpress_posts_post_type);
                    if (!empty($gridpress_post_taxonomies)) {
                        $gridpress_tax_query = [];
                        foreach ($gridpress_post_taxonomies as $gridpress_post_taxkey => $gridpress_post_taxonomy) {
                            $gridpress_post_tax_terms = isset($gridpress_grid_all_settings['posts']['all'][$gridpress_post_taxkey . '_terms']) ? $gridpress_grid_all_settings['posts']['all'][$gridpress_post_taxkey . '_terms'] : '';

                            if (!empty($gridpress_post_tax_terms) && is_array($gridpress_post_tax_terms)) {
                                $gridpress_tax_query[] = array(
                                    'taxonomy' => $gridpress_post_taxkey,
                                    'terms' => $gridpress_post_tax_terms,
                                    'field' => 'term_id',
                                    'operator' => 'IN',
                                );
                            }
                        }
                        if (!empty($gridpress_tax_query)) {
                            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Grid filtering requires taxonomy filtering
                            $gridpress_args['tax_query'] = $gridpress_tax_query;
                        }
                    }

                    $gridpress_posts_query = new WP_Query($gridpress_args);
                    $gridpress_found_posts = $gridpress_posts_query->found_posts;
                    if ($gridpress_posts_query->have_posts()) {
                        $gridpress_posts_data = $gridpress_posts_query->posts;

                        if ($gridpress_found_posts > $gridpress_num_posts) {
                            $gridpress_pagination = true;
                        }

                        foreach ($gridpress_posts_data as $gridpress_post_obj) {
                            if (isset($gridpress_post_obj->ID)) {
                                $gridpress_itms_data[] = $this->gridpress_post_obj_to_itm_data($gridpress_post_obj, $gridpress_grid_all_settings);
                            }
                        }
                        wp_reset_postdata();
                    }
                    set_query_var('gridpress_total_posts', $gridpress_found_posts);
                }
                //
            }
            // Top Filters
            if ($gridpress_source_data_type != 'manual' && isset($gridpress_grid_all_settings['display']['top_filters']) && $gridpress_grid_all_settings['display']['top_filters'] == 'on') {
                if (isset($gridpress_grid_all_settings['display']['top_filter_tax']) && !empty($gridpress_grid_all_settings['display']['top_filter_tax'])) {
                    $gridpress_filter_tax = $gridpress_grid_all_settings['display']['top_filter_tax'];
                    $gridpress_top_terms_list = [];
                    if (isset($gridpress_posts_data_type) && $gridpress_posts_data_type == 'selected') {
                        if (!empty($gridpress_posts_ids)) {
                            foreach ($gridpress_posts_ids as $gridpress_post_itm_id) {
                                $gridpress_fltr_tax_terms = wp_get_post_terms($gridpress_post_itm_id, $gridpress_filter_tax);
                                if (!is_wp_error($gridpress_fltr_tax_terms) && !empty($gridpress_fltr_tax_terms)) {
                                    foreach ($gridpress_fltr_tax_terms as $gridpress_fltr_term) {
                                        $gridpress_fltr_term_id = $gridpress_fltr_term->term_id;
                                        if (!isset($gridpress_top_terms_list[$gridpress_fltr_term_id])) {
                                            $gridpress_top_terms_list[$gridpress_fltr_term_id] = [
                                                'slug' => $gridpress_fltr_term->slug,
                                                'name' => $gridpress_fltr_term->name,
                                                'count' => 1,
                                            ];
                                        } else {
                                            $gridpress_top_terms_list[$gridpress_fltr_term_id]['count'] += 1;
                                        }
                                    }
                                }
                            }
                            if (!empty($gridpress_top_terms_list)) {
                                uasort($gridpress_top_terms_list, function ($gridpress_sort_a, $gridpress_sort_b) {
                                    if ($gridpress_sort_a['count'] == $gridpress_sort_b['count']) {
                                        $gridpress_sort_ret_val = 0;
                                    }
                                    $gridpress_sort_ret_val = ($gridpress_sort_b['count'] < $gridpress_sort_a['count']) ? -1 : 1;
                                    return $gridpress_sort_ret_val;
                                });
                            }
                        }
                    } else {
                        $gridpress_trms_args = array(
                            'taxonomy' => $gridpress_filter_tax,
                            'hide_empty' => true,
                            'orderby' => 'count',
                            'order' => 'DESC',
                        );
                        $gridpress_top_terms = get_terms($gridpress_trms_args);
                        if (!empty($gridpress_top_terms)) {
                            foreach ($gridpress_top_terms as $gridpress_term_itm) {
                                $gridpress_top_terms_list[$gridpress_term_itm->term_id] = [
                                    'slug' => $gridpress_term_itm->slug,
                                    'name' => $gridpress_term_itm->name,
                                    'count' => $gridpress_term_itm->count,
                                ];
                            }
                        }
                    }
                    set_query_var('gridpress_top_terms', $gridpress_top_terms_list);
                }
            }

            // Pagination
            if ($gridpress_pagination) {
                $gridpress_items_pagination = '<div class="gridpress-items-paginatcon">' . self::gridpress_pagination($gridpress_page_type, $gridpress_posts_query, $gridpress_num_posts) . '</div>';
                set_query_var('gridpress_pagination', $gridpress_items_pagination);
            }

            //
            ob_start();
            if (!empty($gridpress_itms_data)) {
                gridpress_get_template_part('loop', 'before', 'loop');
                $this->gridpress_items_list_common($gridpress_itms_data, $gridpress_grid_style);
                gridpress_get_template_part('loop', 'after', 'loop');
            } else {
                gridpress_get_template_part('no', 'record', 'loop');
            }

            $gridpress_html = ob_get_clean();
            return wp_kses_post($gridpress_html);
        }

        public function gridpress_post_obj_to_itm_data($gridpress_post_obj, $gridpress_grid_all_settings) {
            $gridpress_itms_data = [];

            $gridpress_title_length = isset($gridpress_grid_all_settings['display']['title_length']) ? $gridpress_grid_all_settings['display']['title_length'] : '';
            $gridpress_excerpt_length = isset($gridpress_grid_all_settings['display']['excerpt_length']) ? $gridpress_grid_all_settings['display']['excerpt_length'] : '';

            $gridpress_post_id = $gridpress_post_obj->ID;
            $gridpress_post_title = $gridpress_post_obj->post_title;
            $gridpress_post_excerpt = $gridpress_post_obj->post_excerpt;
            $gridpress_post_date = $gridpress_post_obj->post_date;
            $gridpress_post_author = $gridpress_post_obj->post_author;
            $gridpress_author_name = get_the_author_meta('display_name', $gridpress_post_author);

            $gridpress_thumb_id = get_post_thumbnail_id($gridpress_post_id);
            $gridpress_imag_url = '';

            if ($gridpress_thumb_id) {
                $gridpress_imag_url = wp_get_attachment_image_url($gridpress_thumb_id, 'large');
            }
            //
            $gridpress_short_title = $gridpress_post_title;
            if ($gridpress_title_length > 0) {
                $gridpress_short_title = wp_trim_words($gridpress_post_title, $gridpress_title_length, '...');
            }
            //
            $gridpress_short_excerpt = $gridpress_post_excerpt;
            if ($gridpress_excerpt_length > 0) {
                $gridpress_short_excerpt = wp_trim_words($gridpress_post_excerpt, $gridpress_excerpt_length, '...');
            }
            //
            $gridpress_itms_data = [
                'id' => $gridpress_post_id,
                'type' => 'post',
                'title' => $gridpress_post_title,
                'short_title' => $gridpress_short_title,
                'url' => get_permalink($gridpress_post_id),
                'excerpt' => $gridpress_post_excerpt,
                'short_excerpt' => $gridpress_short_excerpt,
                'imag_url' => $gridpress_imag_url,
                'post_date' => $gridpress_post_date,
                'author' => $gridpress_author_name,
                'author_id' => $gridpress_post_author,
            ];

            return $gridpress_itms_data;
        }

        public function gridpress_items_list_common($gridpress_itms_data, $gridpress_grid_style, $gridpress_num_posts = 0) {
            $gridpress_style5_clor_classes = $this->gridpress_style5_bg_colors();
            $gridpress_style15_clor_classes = $this->gridpress_style15_bg_colors();
            $gridpress_style30_clors = $this->gridpress_style30_bg_colors();

            $gridpress_style5_countr = 0;
            $gridpress_style11_countr = 1;
            $gridpress_style12_countr = 0;
            $gridpress_style15_countr = 0;
            $gridpress_style28_countr = 1;
            $gridpress_style30_countr = 0;
            $gridpress_common_countr = 1;

            if(isset($_GET['page_num'])){
                if (!check_ajax_referer('gridpress_front_nonce', 'gridpress_nonce')) {
                    wp_die(esc_html__('Security check failed.', 'gridpress-grid-layout-design'));
                }
            }
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $gridpress_page_num = isset($_GET['page_num'])
                ? max(1, absint($_GET['page_num']))
                : 1;

            if ($gridpress_num_posts > 0) {
                $gridpress_common_countr = (($gridpress_page_num - 1) * $gridpress_num_posts) + 1;
            }
            foreach ($gridpress_itms_data as $gridpress_itm_data) {
                set_query_var('gridpress_card_data', $gridpress_itm_data);
                if ($gridpress_grid_style == 'style5') {
                    set_query_var('gridpress_bg_class', $gridpress_style5_clor_classes[$gridpress_style5_countr]);
                }
                if ($gridpress_grid_style == 'style11') {
                    set_query_var('gridpress_card_counter', $gridpress_style11_countr);
                }
                if ($gridpress_grid_style == 'style12') {
                    set_query_var('gridpress_card_counter', $gridpress_style12_countr);
                }
                if ($gridpress_grid_style == 'style15') {
                    set_query_var('gridpress_bg_class', $gridpress_style15_clor_classes[$gridpress_style15_countr]);
                }
                if ($gridpress_grid_style == 'style28') {
                    set_query_var('gridpress_card_counter', $gridpress_style28_countr);
                }
                if ($gridpress_grid_style == 'style30') {
                    set_query_var('gridpress_bg_color', $gridpress_style30_clors[$gridpress_style30_countr]);
                }
                if ($gridpress_grid_style == 'style13' || $gridpress_grid_style == 'style14' || $gridpress_grid_style == 'style16' ||
                $gridpress_grid_style == 'style17' || $gridpress_grid_style == 'style19' || $gridpress_grid_style == 'style22') {
                    set_query_var('gridpress_card_counter', $gridpress_common_countr);
                }
                gridpress_get_template_part('loop', 'item-' . $gridpress_grid_style, 'loop/styles');
                if ($gridpress_style5_countr >= 7) {
                    $gridpress_style5_countr = 0;
                } else {
                    $gridpress_style5_countr++;
                }
                if ($gridpress_style11_countr >= 10) {
                    $gridpress_style11_countr = 0;
                } else {
                    $gridpress_style11_countr++;
                }
                if ($gridpress_style12_countr == 0) {
                    $gridpress_style12_countr = 2;
                }
                if ($gridpress_style12_countr >= 4) {
                    $gridpress_style12_countr = 1;
                } else {
                    $gridpress_style12_countr++;
                }
                if ($gridpress_style15_countr >= 4) {
                    $gridpress_style15_countr = 0;
                } else {
                    $gridpress_style15_countr++;
                }
                if ($gridpress_style28_countr >= 5) {
                    $gridpress_style28_countr = 1;
                } else {
                    $gridpress_style28_countr++;
                }
                if ($gridpress_style30_countr >= 7) {
                    $gridpress_style30_countr = 0;
                } else {
                    $gridpress_style30_countr++;
                }
                $gridpress_common_countr++;
            }
        }

        private function gridpress_style5_bg_colors() {
            return ['pink', 'brown', 'cyan', 'purple', 'blue', 'dark', 'orange', ''];
        }

        private function gridpress_style15_bg_colors() {
            return ['', 'pink', 'brown', 'cyan', 'purple'];
        }

        private function gridpress_style30_bg_colors() {
            return ['#cee56a', '#f7c0ff', '#c0d6ff', '#fdffc0', '#ffcdce', '#c0ffff', '#dbdbdb', '#dfffb8'];
        }

        public function gridpress_item_term_classes($gridpress_classes, $gridpress_taxonomy, $gridpress_post_id) {
            $gridpress_tax_terms_ids = wp_get_post_terms($gridpress_post_id, $gridpress_taxonomy, ['fields' => 'ids']);
            if (!is_wp_error($gridpress_tax_terms_ids) && !empty($gridpress_tax_terms_ids)) {
                foreach ($gridpress_tax_terms_ids as $gridpress_tax_trm_id) {
                    $gridpress_classes .= ' gridpress-term-' . $gridpress_tax_trm_id;
                }
            }
            return $gridpress_classes;
        }

        public static function gridpress_pagination($gridpress_page_type, $gridpress_query, $gridpress_per_page, $gridpress_page_numbr = 1) {

            $gridpress_html = '';

            if ($gridpress_page_type == 'load_more') {
                $gridpress_total_posts = $gridpress_query->found_posts;
                $gridpress_number_of_pages = ceil($gridpress_total_posts / $gridpress_per_page);
                $gridpress_html .= '<div class="gridpress-cardslodmore-btncon"><a href="javascript:;" data-pagenum="' . esc_attr($gridpress_page_numbr+1) . '" data-pages="' . intval($gridpress_number_of_pages) . '">' . esc_html__('Load more', 'gridpress-grid-layout-design') . '</a></div>';
            } else if ($gridpress_page_type == 'infinite') {
                $gridpress_total_posts = $gridpress_query->found_posts;
                $gridpress_number_of_pages = ceil($gridpress_total_posts / $gridpress_per_page);
                $gridpress_html .= '<div class="gridpress-cardslodmore-btncon gridpress-cardsinfint-lodcon"><a href="javascript:;" data-pagenum="' . intval($gridpress_page_numbr+1) . '" data-pages="' . intval($gridpress_number_of_pages) . '">' . esc_html__('Load more', 'gridpress-grid-layout-design') . '</a></div>';
            } else {

                $gridpress_big_intiger = 999999999;
                $gridpress_paginate_links = paginate_links(array(
                    'base' => str_replace($gridpress_big_intiger, '%#%', esc_url(get_pagenum_link($gridpress_big_intiger))),
                    'format' => '?paged=%#%',
                    'current' => max(1, $gridpress_page_numbr),
                    'total' => $gridpress_query->max_num_pages,
                    'prev_text' => '<i class="gridpress-icon-chevron-left"></i>',
                    'next_text' => '<i class="gridpress-icon-chevron-right"></i>',
                    'type' => 'array'
                ));
                $gridpress_html .= '<div class="gridpress-carditms-pagelinks">';
                foreach ($gridpress_paginate_links as $gridpress_page_link) {
                    // Extract page number
                    preg_match('/\'?paged?=(\d+)\'?/', $gridpress_page_link, $gridpress_matches);
                    if (!isset($gridpress_matches[1])) {
                        preg_match('/\/page\/(\d+)\//', $gridpress_page_link, $gridpress_matches);
                    }
                    $gridpress_page_num = isset($gridpress_matches[1]) ? $gridpress_matches[1] : 1;

                    $gridpress_is_current = strpos($gridpress_page_link, 'current') !== false;

                    if (!$gridpress_is_current) {
                        $gridpress_page_link = preg_replace('/href="http[^"]*"/', 'href=""', $gridpress_page_link);
                    }

                    // Replace href and add data attribute
                    $gridpress_html .= str_replace(
                        'href=""',
                        'href="#" data-pagenum="' . $gridpress_page_num . '"',
                        $gridpress_page_link
                    );
                }
                $gridpress_html .= '</div>';
            }

            return $gridpress_html;
        }

        public function gridpress_cards_pagination_pagenum_call() {
            check_ajax_referer('gridpress_front_nonce', 'gridpress_nonce');

            $gridpress_grid_id = isset($_POST['gid']) ? absint($_POST['gid']) : 0;
            $gridpress_term_id = isset($_POST['term_id']) ? absint($_POST['term_id']) : 0;
            $gridpress_page_num = isset($_POST['page_num']) ? absint($_POST['page_num']) : 1;

            $gridpress_grid_all_settings = get_post_meta($gridpress_grid_id, 'gridpress_grid_settings', true);
            $gridpress_grid_style = isset($gridpress_grid_all_settings['grid_style']) ? $gridpress_grid_all_settings['grid_style'] : '';
            $gridpress_posts_post_type = isset($gridpress_grid_all_settings['posts']['post_type']) ? $gridpress_grid_all_settings['posts']['post_type'] : '';

            $gridpress_posts_order_by = isset($gridpress_grid_all_settings['posts']['all']['order_by']) ? $gridpress_grid_all_settings['posts']['all']['order_by'] : '';
            $gridpress_posts_order = isset($gridpress_grid_all_settings['posts']['all']['order']) ? $gridpress_grid_all_settings['posts']['all']['order'] : '';
            $gridpress_num_posts = isset($gridpress_grid_all_settings['posts']['all']['num_posts']) ? $gridpress_grid_all_settings['posts']['all']['num_posts'] : '';
            $gridpress_num_posts = $gridpress_num_posts > 0 ? $gridpress_num_posts : 20;
            $gridpress_page_type = isset($gridpress_grid_all_settings['posts']['all']['page_type']) ? $gridpress_grid_all_settings['posts']['all']['page_type'] : '';

            $gridpress_filter_taxonomy = isset($gridpress_grid_all_settings['display']['top_filter_tax']) ? $gridpress_grid_all_settings['display']['top_filter_tax'] : '';

            $gridpress_args = array(
                'post_type' => $gridpress_posts_post_type,
                'posts_per_page' => $gridpress_num_posts,
                'paged' => $gridpress_page_num,
                'orderby' => $gridpress_posts_order_by,
                'order' => $gridpress_posts_order,
            );

            if (!empty($gridpress_filter_taxonomy) && !empty($gridpress_term_id) && $gridpress_term_id != 'all' && $gridpress_term_id > 0) {
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Grid filtering requires taxonomy filtering
                $gridpress_args['tax_query'] = array(
                        array(
                        'taxonomy' => $gridpress_filter_taxonomy,
                        'terms' => [$gridpress_term_id],
                        'field' => 'term_id',
                    )
                );
            } else {
                $gridpress_post_taxonomies = Gridpress_Grid_settings::gridpress_get_post_taxonomies($gridpress_posts_post_type);
                if (!empty($gridpress_post_taxonomies)) {
                    $gridpress_tax_query = [];
                    foreach ($gridpress_post_taxonomies as $gridpress_post_taxkey => $gridpress_post_taxonomy) {
                        $gridpress_post_tax_terms = isset($gridpress_grid_all_settings['posts']['all'][$gridpress_post_taxkey . '_terms']) ? $gridpress_grid_all_settings['posts']['all'][$gridpress_post_taxkey . '_terms'] : '';
                        if (!empty($gridpress_post_tax_terms) && is_array($gridpress_post_tax_terms)) {
                            $gridpress_tax_query[] = array(
                                'taxonomy' => $gridpress_post_taxkey,
                                'terms' => $gridpress_post_tax_terms,
                                'field' => 'term_id',
                            );
                        }
                    }
                    if (!empty($gridpress_tax_query)) {
                        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Grid filtering requires taxonomy filtering
                        $gridpress_args['tax_query'] = $gridpress_tax_query;
                    }
                }
            }

            $gridpress_posts_query = new WP_Query($gridpress_args);

            $gridpress_itms_data = [];
            if ($gridpress_posts_query->have_posts()) {
                $gridpress_posts_data = $gridpress_posts_query->posts;

                foreach ($gridpress_posts_data as $gridpress_post_obj) {
                    if (isset($gridpress_post_obj->ID)) {
                        $gridpress_itms_data[] = $this->gridpress_post_obj_to_itm_data($gridpress_post_obj, $gridpress_grid_all_settings);
                    }
                }
                wp_reset_postdata();
            }

            set_query_var('gridpress_grid_style', $gridpress_grid_style);
            set_query_var('gridpress_display_settings', isset($gridpress_grid_all_settings['display']) ? $gridpress_grid_all_settings['display'] : '');

            ob_start();
            if (!empty($gridpress_itms_data)) {
                $this->gridpress_items_list_common($gridpress_itms_data, $gridpress_grid_style, $gridpress_num_posts);
            }
            $gridpress_cards_html = ob_get_clean();

            $gridpress_pagination = self::gridpress_pagination($gridpress_page_type, $gridpress_posts_query, $gridpress_num_posts, $gridpress_page_num);

            wp_send_json(array('cards' => $gridpress_cards_html, 'pagination' => $gridpress_pagination));
        }

        public function gridpress_cards_top_terms_filter_call() {
            check_ajax_referer('gridpress_front_nonce', 'gridpress_nonce');

            $gridpress_grid_id = isset($_POST['gid']) ? absint($_POST['gid']) : 0;
            $gridpress_term_id = isset($_POST['term_id']) ? absint($_POST['term_id']) : 0;

            $gridpress_grid_all_settings = get_post_meta($gridpress_grid_id, 'gridpress_grid_settings', true);
            $gridpress_grid_style = isset($gridpress_grid_all_settings['grid_style']) ? $gridpress_grid_all_settings['grid_style'] : '';
            $gridpress_posts_post_type = isset($gridpress_grid_all_settings['posts']['post_type']) ? $gridpress_grid_all_settings['posts']['post_type'] : '';

            $gridpress_posts_order_by = isset($gridpress_grid_all_settings['posts']['all']['order_by']) ? $gridpress_grid_all_settings['posts']['all']['order_by'] : '';
            $gridpress_posts_order = isset($gridpress_grid_all_settings['posts']['all']['order']) ? $gridpress_grid_all_settings['posts']['all']['order'] : '';
            $gridpress_num_posts = isset($gridpress_grid_all_settings['posts']['all']['num_posts']) ? $gridpress_grid_all_settings['posts']['all']['num_posts'] : '';
            $gridpress_num_posts = $gridpress_num_posts > 0 ? $gridpress_num_posts : 20;
            $gridpress_page_type = isset($gridpress_grid_all_settings['posts']['all']['page_type']) ? $gridpress_grid_all_settings['posts']['all']['page_type'] : '';

            $gridpress_filter_taxonomy = isset($gridpress_grid_all_settings['display']['top_filter_tax']) ? $gridpress_grid_all_settings['display']['top_filter_tax'] : '';

            $gridpress_args = array(
                'post_type' => $gridpress_posts_post_type,
                'posts_per_page' => $gridpress_num_posts,
                'paged' => '1',
                'orderby' => $gridpress_posts_order_by,
                'order' => $gridpress_posts_order,
            );

            if (!empty($gridpress_filter_taxonomy) && !empty($gridpress_term_id) && $gridpress_term_id != 'all' && $gridpress_term_id > 0) {
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Grid filtering requires taxonomy filtering
                $gridpress_args['tax_query'] = array(
                        array(
                        'taxonomy' => $gridpress_filter_taxonomy,
                        'terms' => [$gridpress_term_id],
                        'field' => 'term_id',
                    )
                );
            } else {
                $gridpress_post_taxonomies = Gridpress_Grid_settings::gridpress_get_post_taxonomies($gridpress_posts_post_type);
                if (!empty($gridpress_post_taxonomies)) {
                    $gridpress_tax_query = [];
                    foreach ($gridpress_post_taxonomies as $gridpress_post_taxkey => $gridpress_post_taxonomy) {
                        $gridpress_post_tax_terms = isset($gridpress_grid_all_settings['posts']['all'][$gridpress_post_taxkey . '_terms']) ? $gridpress_grid_all_settings['posts']['all'][$gridpress_post_taxkey . '_terms'] : '';
                        if (!empty($gridpress_post_tax_terms) && is_array($gridpress_post_tax_terms)) {
                            $gridpress_tax_query[] = array(
                                'taxonomy' => $gridpress_post_taxkey,
                                'terms' => $gridpress_post_tax_terms,
                                'field' => 'term_id',
                            );
                        }
                    }
                    if (!empty($gridpress_tax_query)) {
                        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Grid filtering requires taxonomy filtering
                        $gridpress_args['tax_query'] = $gridpress_tax_query;
                    }
                }
            }

            $gridpress_posts_query = new WP_Query($gridpress_args);

            $gridpress_itms_data = [];
            if ($gridpress_posts_query->have_posts()) {
                $gridpress_posts_data = $gridpress_posts_query->posts;

                foreach ($gridpress_posts_data as $gridpress_post_obj) {
                    if (isset($gridpress_post_obj->ID)) {
                        $gridpress_itms_data[] = $this->gridpress_post_obj_to_itm_data($gridpress_post_obj, $gridpress_grid_all_settings);
                    }
                }
                wp_reset_postdata();
            }

            set_query_var('gridpress_grid_style', $gridpress_grid_style);
            set_query_var('gridpress_display_settings', isset($gridpress_grid_all_settings['display']) ? $gridpress_grid_all_settings['display'] : '');

            ob_start();
            if (!empty($gridpress_itms_data)) {
                $this->gridpress_items_list_common($gridpress_itms_data, $gridpress_grid_style);
            }
            $gridpress_cards_html = ob_get_clean();

            $gridpress_pagination = '';
            if ($gridpress_posts_query->found_posts > $gridpress_num_posts) {
                $gridpress_pagination = self::gridpress_pagination($gridpress_page_type, $gridpress_posts_query, $gridpress_num_posts);
            }

            wp_send_json(array('cards' => $gridpress_cards_html, 'pagination' => $gridpress_pagination));
        }

        public function gridpress_addin_card_video() {
            check_ajax_referer('gridpress_front_nonce', 'gridpress_nonce');

            $gridpress_grid_id = isset($_POST['gid']) ? absint($_POST['gid']) : 0;
            $gridpress_card_id = isset($_POST['card_id']) ? sanitize_key(wp_unslash($_POST['card_id'])) : '';
            $gridpress_grid_all_settings = get_post_meta($gridpress_grid_id, 'gridpress_grid_settings', true);
            $gridpress_cards_data = isset($gridpress_grid_all_settings['cards']) ? $gridpress_grid_all_settings['cards'] : '';
            ob_start();
            if (isset($gridpress_cards_data[$gridpress_card_id]['video']) && !empty($gridpress_cards_data[$gridpress_card_id]['video'])) {
                $gridpress_video_url = $gridpress_cards_data[$gridpress_card_id]['video'];
                $gridpress_embed = '<div class="gridpress-responsive-video">' . wp_oembed_get( $gridpress_video_url ) . '</div>';

                if (!empty($gridpress_embed)) {
                    // Successfully got the embed HTML from oEmbed provider
                    echo wp_kses_post($gridpress_embed);
                }

                // Fallback for self-hosted video URLs (e.g., .mp4, .webm, etc.)
                $gridpress_file_ext = pathinfo(wp_parse_url($gridpress_video_url, PHP_URL_PATH), PATHINFO_EXTENSION);
                $gridpress_supported_formats = ['mp4', 'webm', 'ogg'];

                $gridpress_file_ext = strtolower( sanitize_key( $gridpress_file_ext ) );

                if ( in_array( $gridpress_file_ext, $gridpress_supported_formats, true ) ) {
                    ?>
                    <div class="gridpress-responsive-video">
                        <video controls height="360">
                            <source
                                src="<?php echo esc_url( $gridpress_video_url ); ?>"
                                type="<?php echo esc_attr( 'video/' . $gridpress_file_ext ); ?>"
                            >
                            <?php
                            /* translators: Message shown when browser cannot play HTML5 video. */
                            esc_html_e( 'Your browser does not support the video tag.', 'gridpress-grid-layout-design' );
                            ?>
                        </video>
                    </div>
                    <?php
                }
            }
            $gridpress_html = ob_get_clean();

            wp_send_json(array('video_html' => $gridpress_html));
        }

        public function gridpress_grid_sh_popup() {
            ?>
            <div id="gridpress-common-popup" class="gridpress-modal-popup gridpress-popup-hide">
                <div class="gridpress-modal-container">
                    <div class="gridpress-modal-inner-area">
                        <div class="gridpress-modal-content-area">
                            <a href="javascript:;" class="gridpress-popup-closebtn"><i class="gridpress-icon-close"></i></a>
                            <div class="gridpress-modalinit-con"></div>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }

        public function gridpress_grid_sh_styles() {

            global $post;

            if (
                empty( $post ) ||
                empty( $post->post_content ) ||
                ! has_shortcode( $post->post_content, 'gridpress_grid' )
            ) {
                return;
            }

            $gridpress_grid_styles = '';

            preg_match_all(
                '/' . get_shortcode_regex( [ 'gridpress_grid' ] ) . '/',
                $post->post_content,
                $gridpress_shortcodes,
                PREG_SET_ORDER
            );

            if ( empty( $gridpress_shortcodes ) ) {
                return;
            }

            foreach ( $gridpress_shortcodes as $gridpress_shortcode ) {

                $gridpress_attributes = shortcode_parse_atts( $gridpress_shortcode[3] );

                if (
                    empty( $gridpress_attributes['id'] ) ||
                    ! is_numeric( $gridpress_attributes['id'] )
                ) {
                    continue;
                }

                $gridpress_grid_id = absint( $gridpress_attributes['id'] );

                $gridpress_style = get_post_meta(
                    $gridpress_grid_id,
                    'grid_styles_str',
                    true
                );

                if ( ! empty( $gridpress_style ) ) {
                    $gridpress_grid_styles .= (string) $gridpress_style;
                }
            }

            if ( empty( $gridpress_grid_styles ) ) {
                return;
            }

            wp_register_style(
                'gridpress-inline-style',
                false,
                [ 'gridpress-cards' ],
                GRIDPRESS_VERSION
            );

            wp_enqueue_style( 'gridpress-inline-style' );

            $gridpress_grid_styles = wp_strip_all_tags( $gridpress_grid_styles );

            wp_add_inline_style(
                'gridpress-inline-style',
                wp_kses( $gridpress_grid_styles, array() )
            );
        }
    }

    new Gridpress_Grid_Shortcode();
}