<?php
if ( ! defined( 'ABSPATH' ) ) exit;

if (!class_exists('CPTW_Posttype')) {

//phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound
    class CPTW_Posttype
    {
        use CCPW_Helper_Functions;

        public function __construct()
        {
            // Creating posttype for plugin settings panel
            add_action('init', array($this, 'ccpw_post_type'));

            if (is_admin()) {
                // Register meta boxes and custom columns for admin
                add_action('add_meta_boxes', array($this, 'register_ccpw_meta_box'));
                add_action('add_meta_boxes_ccpw', array($this, 'ccpw_add_meta_boxes'));
                add_filter('manage_ccpw_posts_columns', array($this, 'set_custom_edit_ccpw_columns'));
                add_action('manage_ccpw_posts_custom_column', array($this, 'custom_ccpw_column'), 10, 2);
                add_action('save_post', array($this, 'save_ccpw_shortcode'), 10, 3);
            }
            require_once CCPWF_DIR . 'admin/class-settings.php';
            // Integrating cmb2 metaboxes in post type

            add_action('cmb2_save_options-page_fields', array($this, 'Settings_callback'));
            
        }

        /**
         * Callback function for Settings options
         */
        public function Settings_callback()
        {
			// Get old and new API values from options
            $current_select = $this->ccpw_current_select_api();
			$old_api = get_option('ccpw_old_api');
            $new_api = $current_select;

            if ($new_api != $old_api) {
                $db = new ccpw_database();
                $db->drop_table();
                delete_transient('ccpw-saved-coindata');
                delete_option('ccpw_data_save');
                $db->create_table();
                $api = $current_select;
                
                $api_obj = new CCPW_api_data();
                if($api == 'coin_paprika'){
                    $data = $api_obj->ccpw_get_coin_paprika_data();
                }elseif($api == 'coin_marketcap'){
                    $data = $api_obj->ccpw_get_coin_marketcap_data();
                }elseif($api == 'coin_capapi'){
                    $data = $api_obj->ccpw_get_coin_cap_data();
                }else{
                    $data = $api_obj->ccpw_get_coin_gecko_data();
                }
                update_option('ccpw_old_api', $api);
            }
        }

        /**
         * Register Custom Post Type of Crypto Widget
         */
        public function ccpw_post_type()
        {
            $labels = array(
                'name' => _x('Cryptocurrency Widgets', 'Post Type General Name', 'cryptocurrency-price-ticker-widget'),
                'singular_name' => _x('Cryptocurrency Widget', 'Post Type Singular Name', 'cryptocurrency-price-ticker-widget'),
                'menu_name' => __('Crypto Widgets', 'cryptocurrency-price-ticker-widget'),
                'name_admin_bar' => __('Post Type', 'cryptocurrency-price-ticker-widget'),
                'archives' => __('Item Archives', 'cryptocurrency-price-ticker-widget'),
                'attributes' => __('Item Attributes', 'cryptocurrency-price-ticker-widget'),
                'parent_item_colon' => __('Parent Item:', 'cryptocurrency-price-ticker-widget'),
                'all_items' => __('All Shortcodes', 'cryptocurrency-price-ticker-widget'),
                'add_new_item' => __('Add New Shortcode', 'cryptocurrency-price-ticker-widget'),
                'add_new' => __('Add New', 'cryptocurrency-price-ticker-widget'),
                'new_item' => __('New Item', 'cryptocurrency-price-ticker-widget'),
                'edit_item' => __('Edit Item', 'cryptocurrency-price-ticker-widget'),
                'update_item' => __('Update Item', 'cryptocurrency-price-ticker-widget'),
                'view_item' => __('View Item', 'cryptocurrency-price-ticker-widget'),
                'view_items' => __('View Items', 'cryptocurrency-price-ticker-widget'),
                'search_items' => __('Search Item', 'cryptocurrency-price-ticker-widget'),
                'not_found' => __('Not found', 'cryptocurrency-price-ticker-widget'),
                'not_found_in_trash' => __('Not found in Trash', 'cryptocurrency-price-ticker-widget'),
                'featured_image' => __('Featured Image', 'cryptocurrency-price-ticker-widget'),
                'set_featured_image' => __('Set featured image', 'cryptocurrency-price-ticker-widget'),
                'remove_featured_image' => __('Remove featured image', 'cryptocurrency-price-ticker-widget'),
                'use_featured_image' => __('Use as featured image', 'cryptocurrency-price-ticker-widget'),
                'insert_into_item' => __('Insert into item', 'cryptocurrency-price-ticker-widget'),
                'uploaded_to_this_item' => __('Uploaded to this item', 'cryptocurrency-price-ticker-widget'),
                'items_list' => __('Items list', 'cryptocurrency-price-ticker-widget'),
                'items_list_navigation' => __('Items list navigation', 'cryptocurrency-price-ticker-widget'),
                'filter_items_list' => __('Filter items list', 'cryptocurrency-price-ticker-widget'),
            );
            $args = array(
                'label' => __('Cryptocurrency Widgets', 'cryptocurrency-price-ticker-widget'),
                'description' => __('Post Type Description', 'cryptocurrency-price-ticker-widget'),
                'labels' => $labels,
                'supports' => array('title'),
                'taxonomies' => array(''),
                'hierarchical' => false,
                'public' => false, // it's not public, it shouldn't have it's own permalink, and so on
                'show_ui' => true,
                'show_in_nav_menus' => true, // you shouldn't be able to add it to menus
                'menu_position' => 9,
                'show_in_admin_bar' => false,
                'show_in_menu' => false,
                'can_export' => true,
                'has_archive' => false, // it shouldn't have archive page
                'rewrite' => false, // it shouldn't have rewrite rules
                'exclude_from_search' => true,
                'publicly_queryable' => true,
                'menu_icon' => CCPWF_URL . '/assets/ccpw-icon.png',
                'capability_type' => 'page',
            );

            register_post_type('ccpw', $args);
        }

        /**
         * Register meta boxes for shortcode
         */
        public function register_ccpw_meta_box()
        {
            add_meta_box('ccpw-shortcode', 'Crypto Widget Shortcode', array($this, 'ccpw_p_shortcode_meta'), 'ccpw', 'side', 'high');
        }

        /**
         * Plugin Shortcode meta section
         */
        public function ccpw_p_shortcode_meta()
        {
            // Add shortcode meta box content...
            $id = get_the_ID();
            $dynamic_attr = '';
            esc_html_e('Copy & Paste this shortcode any in Page/Post.', 'cryptocurrency-price-ticker-widget');

            $element_type = get_post_meta($id, 'pp_type', true);
            $dynamic_attr .= "[ccpw id=\"{$id}\"";
            $dynamic_attr .= ']';
            ?>
			<input style="width:100%" onClick="this.select();" type="text" class="regular-small" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo esc_attr(htmlentities($dynamic_attr)); ?>" readonly/>
			<hr>
			<div style="display:flex;justify-content:space-between;">
				<a class="button button-secondary" target="_blank" href="https://cryptocurrencyplugins.com/demo/cryptocurrency-widgets-pro/?utm_source=ccw_plugin&utm_medium=inside&utm_campaign=demo&utm_content=copy_shortcode">View Pro Demos</a>
				<a class="button button-primary" target="_blank" href="https://cryptocurrencyplugins.com/wordpress-plugin/cryptocurrency-widgets-pro/?utm_source=ccw_plugin&utm_medium=inside&utm_campaign=get_pro&utm_content=copy_shortcode">Buy Pro</a>
			</div>
			<?php
}

        /**
         * Register meta boxes for Feedback
         */
        public function ccpw_add_meta_boxes($post)
        {
            add_meta_box(
                'ccpw-feedback-section',
                __('Information', 'cryptocurrency-price-ticker-widget'),
                array($this, 'ccpw_right_section'),
                'ccpw',
                'side',
                'low'
            );
        }

        /**
         * Admin notice for plugin feedback
         */
        public function ccpw_right_section($post, $callback)
        {
            global $post;
            $pro_add = '';
            $pro_add .=

            '<ul>
			<li><b>Q1. A website like coinmarketcap.com?</b><br/>
			Explore our <a href="https://cryptocurrencyplugins.com/coinmarketcap-clone-website/?utm_source=ccw_plugin&utm_medium=inside&utm_campaign=get_pro&utm_content=cmc_clone_widget_sidebar" target="_blank">coinmarketcap clone website creation service</a> and create a website similar to that.
			<hr></li>

			<li><b>Q2. Accept cryptocurrency payments?</b><br/>
			Install our <a href="https://paywithcryptocurrency.net/?utm_source=ccw_plugin&utm_medium=inside&utm_campaign=get_pro&utm_content=cpmw_widget_sidebar" target="_blank">WooCommerce plugin for MetaMask</a> & start accepting crypto payments in your store.
			<hr></li>

			<li><b>Q3. More cryptocurrency widgets?</b><br/>
			Check our <a href="https://cryptocurrencyplugins.com/wordpress-plugin/cryptocurrency-widgets-pro/?utm_source=ccw_plugin&utm_medium=inside&utm_campaign=get_pro&utm_content=widget_sidebar" target="_blank">Cryptocurrency Widgets Pro</a> plugin and add premium crypto widgets inside your website.
			<hr></li>

			<li><b>Q4. Enjoying our free plugin?</b><br/>
			If you really like our plugin, please leave a review on WP.org. Your review helps us keep improving the free plugin.
			<hr>
			<a style="width:100%;text-align:center;" href="https://wordpress.org/support/plugin/cryptocurrency-price-ticker-widget/reviews/#new-post" class="button button-primary" target="_blank">' . __('Submit Review', 'cryptocurrency-price-ticker-widget') . ' ★★★★★</a>
			</li>
		</ul>
        ';

            echo wp_kses_post($pro_add);

        }

        /**
         * Set Custom Column for Post Type
         */
        public function set_custom_edit_ccpw_columns($columns)
        {
            $columns['type'] = __('Widget Type', 'cryptocurrency-price-ticker-widget');
            $columns['shortcode'] = __('Shortcode', 'cryptocurrency-price-ticker-widget');
            return $columns;

        }

        /**
         * Custom column content for the custom post type
         */
        public function custom_ccpw_column($column, $post_id)
        {
            switch ($column) {
                case 'type':
                    $type = get_post_meta($post_id, 'type', true);
                    switch ($type) {
                        case 'ticker':
                            esc_html_e('Ticker', 'cryptocurrency-price-ticker-widget');
                            break;
                        case 'price-label':
                            esc_html_e('Price Label', 'cryptocurrency-price-ticker-widget');
                            break;
                        case 'multi-currency-tab':
                            esc_html_e('Multi Currency Tabs', 'cryptocurrency-price-ticker-widget');
                            break;
                        case 'table-widget':
                            esc_html_e('Table Widget', 'cryptocurrency-price-ticker-widget');
                            break;
                        default:
                            esc_html_e('List Widget', 'cryptocurrency-price-ticker-widget');
                    }
                    break;
                case 'shortcode':
                    echo '<code>[ccpw id="' . esc_html($post_id) . '"]</code>';
                    break;
                default:
                    esc_html_e('Not Matched', 'cryptocurrency-price-ticker-widget');
            }

        }

        /**
         * Save shortcode when a post is saved.
         */
        public function save_ccpw_shortcode($post_id, $post, $update)
        {
            // Autosave, do nothing
            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
                return;
            }
            // AJAX? Not used here
            if (defined('DOING_AJAX') && DOING_AJAX) {
                return;
            }
            // Check user permissions
            if (!current_user_can('edit_post', $post_id)) {
                return;
            }
            // Verify nonce for CSRF protection
            if (!isset($_POST['_wpnonce']) || !wp_verify_nonce( sanitize_text_field( wp_unslash($_POST['_wpnonce'])), 'update-post_' . $post_id)) {
                return;
            }
            // Return if it's a post revision
            if (false !== wp_is_post_revision($post_id)) {
                return;
            }
            /*
             * In production code, $slug should be set only once in the plugin,
             * preferably as a class property, rather than in each function that needs it.
             */
            $post_type = get_post_type($post_id);

            // If this isn't a 'ccpw' post, don't update it.
            if ('ccpw' != $post_type) {
                return;
            }
            // - Update the post's metadata.
            if (isset($_POST['ticker_position'])) {
                $ticker_position = sanitize_text_field(wp_unslash($_POST['ticker_position']));
                if (in_array($ticker_position, array('header', 'footer'), true)) {
                    update_option('ccpw-p-id', $post_id);
                    update_option('ccpw-shortcode', '[ccpw id=' . intval($post_id) . ']'); // Use intval to sanitize post_id
                }
            }

            delete_transient('ccpw-coins'); // Site Transient

        }

    }
    new CPTW_Posttype();
}
