<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
if (!class_exists('NBD_Templates_Global')) {
    class NBD_Templates_Global
    {
        protected static $instance;
        public static function get_instance()
        {
            if (is_null(self::$instance)) {
                self::$instance = new self();
            }
            return self::$instance;
        }
        public function __construct()
        {
            add_action('nbd_menu', array($this, 'add_sub_menu'), 90);
            add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
            $this->ajax();
        }
        public function enqueue_scripts($hook)
        {
            if ($hook == 'pc-designer_page_nbd-templates') {
                wp_enqueue_style('admin_nbdesigner');
                wp_register_script(
                    'nbd-manager-templates-global',
                    NBDESIGNER_JS_URL . 'views/manager-templates-global.js',
                    array('jquery'),
                    NBDESIGNER_VERSION,
                    true
                );
                $base_link_create_template = add_query_arg(array(
                    'task'          => 'create',
                    'rd'            => 'admin_templates',
                ), getUrlPageNBD('create'));
                wp_localize_script('nbd-manager-templates-global', 'nbdTemplatesGlobal', array(
                    'nonceSearch'   => wp_create_nonce('nbd_search_products'),
                    'typeToSearch'  => __('Type to search products…', 'web-to-print-online-designer'),
                    'searching'     => __('Searching…', 'web-to-print-online-designer'),
                    'noProducts'    => __('No products found.', 'web-to-print-online-designer'),
                    'baseLinkCreateTemplate' => $base_link_create_template,
                ));
                wp_enqueue_script('nbd-manager-templates-global');
            }
        }
        public function ajax()
        {
            $ajax_events = array(
                'nbd_search_products'          => false,
            );
            foreach ($ajax_events as $ajax_event => $nopriv) {
                add_action('wp_ajax_' . $ajax_event, array($this, $ajax_event));
                if ($nopriv) {
                    add_action('wp_ajax_nopriv_' . $ajax_event, array($this, $ajax_event));
                }
            }
        }

        public function nbd_search_products()
        {
            check_ajax_referer('nbd_search_products', 'nonce');
            if (!current_user_can('manage_woocommerce')) {
                wp_send_json_error(__('Permission denied.', 'web-to-print-online-designer'));
            }
            $keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : '';
            $query = new WP_Query(array(
                'post_type'      => 'product',
                'post_status'    => 'publish',
                's'              => $keyword,
                'posts_per_page' => 20,
                'fields'         => 'ids',
                'meta_query'        => array(
                    array(
                        'key' => '_nbdesigner_enable',
                        'value' => 1,
                    )
                )
            ));
            $results = array();
            foreach ($query->posts as $product_id) {
                $product   = wc_get_product($product_id);
                $thumbnail = get_the_post_thumbnail_url($product_id, 'thumbnail');
                $results[] = array(
                    'id'        => $product_id,
                    'name'      => $product->get_name(),
                    'thumbnail' => $thumbnail ?: '',
                );
            }
            wp_send_json_success($results);
        }

        public function add_sub_menu()
        {
            if (current_user_can('manage_nbd_tool')) {
                add_submenu_page(
                    'nbdesigner',
                    esc_html__('Templates', 'web-to-print-online-designer'),
                    esc_html__('Templates', 'web-to-print-online-designer'),
                    'manage_nbd_tool',
                    'nbd-templates',
                    array($this, 'render'),
                    null
                );
            }
        }

        public function render()
        {
            require_once NBDESIGNER_PLUGIN_DIR . 'includes/class.nbdesigner.pagination.php';
            $cats = nbd_get_global_template_cat();
            $cat_id = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;
            $limit = 20;
            $page = isset($_GET['p']) ? intval($_GET['p']) : 1;
            $templates = nbd_get_global_templates($page, $limit, $cat_id);
            $number_pro = isset($templates->total) ? intval($templates->total) : 0;
            if ($cat_id) {
                $url = add_query_arg(array('cat_id' => $cat_id), admin_url('admin.php?page=nbd-templates'));
            } else {
                $url = admin_url('admin.php?page=nbd-templates');
            }
            $paging = new Nbdesigner_Pagination();
            $config = array(
                'current_page' => isset($page) ? $page : 1,
                'total_record' => $number_pro,
                'limit' => $limit,
                'link_full' => $url . '&p={p}',
                'link_first' => $url
            );
            $paging->init($config);
            include NBDESIGNER_PLUGIN_DIR . 'views/templates-global.php';
        }
    }
}
function NBD_Templates_Global()
{
    return NBD_Templates_Global::get_instance();
}
NBD_Templates_Global();
