<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://example.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/public
 */
if (!class_exists('PinnerPress_Public')) {
class PinnerPress_Public {

    /**
     * The ID of this plugin.
     *
     * @since    0.1.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    0.1.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Cached plugin options loaded in a single batch.
     *
     * @since    1.3.2
     * @access   private
     * @var      array|null    $cached_options    All pinnerpress_* options.
     */
    private $cached_options = null;

    /**
     * Cached category exclusion results to avoid repeated DB lookups.
     *
     * @since    1.3.2
     * @access   private
     * @var      array    $cached_category_exclusions    Feature => bool map.
     */
    private $cached_category_exclusions = array();

    /**
     * Initialize the class and set its properties.
     *
     * @since    0.1.0
     * @param      string    $plugin_name       The name of the plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version) {

        $this->plugin_name = $plugin_name;
        $this->version = $version;
        
        // Add filter to insert call out banner in content
        add_filter('the_content', array($this, 'insert_call_out_banner'));
        
        // Add action to insert Pinterest meta tag
        add_action('wp_head', array($this, 'insert_pinterest_meta_tag'));
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    0.1.0
     */
    public function enqueue_styles() {
        // Enqueue styles on pages where content might be displayed
        if (!is_singular() && !is_home() && !is_archive() && !is_search()) {
            return;
        }

        $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
        wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/pinnerpress-public' . $suffix . '.css', array(), $this->version, 'all');

        // Load CSS asynchronously since pin buttons are injected by JS after page load
        add_filter('style_loader_tag', array($this, 'async_css_loader'), 10, 4);
    }

    /**
     * Make PinnerPress CSS non-render-blocking by loading it asynchronously.
     * Uses media="print" with onload swap to "all" — safe because pin buttons
     * are injected by JS after page load, so no FOUC risk.
     */
    public function async_css_loader($html, $handle, $href, $media) {
        if ($handle !== $this->plugin_name) {
            return $html;
        }
        return str_replace(
            "media='all'",
            "media='print' onload=\"this.media='all'\"",
            $html
        );
    }

    /**
     * Add defer attribute to PinnerPress JS to prevent parser-blocking.
     */
    public function defer_js_loader($tag, $handle, $src) {
        if ($handle !== $this->plugin_name) {
            return $tag;
        }
        return str_replace(' src=', ' defer src=', $tag);
    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    0.1.0
     */
    public function enqueue_scripts() {
        // Enqueue scripts on pages where content might be displayed
        if (!is_singular() && !is_home() && !is_archive() && !is_search()) {
            return;
        }
        
        $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
        wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/pinnerpress-public' . $suffix . '.js', array('jquery'), $this->version, true);

        // Add defer attribute to prevent parser-blocking on slow servers
        add_filter('script_loader_tag', array($this, 'defer_js_loader'), 10, 3);

        // Check for debug parameter via filter to avoid direct $_GET usage in production
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only; sanitized via filter
        $debug_enabled = (bool) apply_filters('pinnerpress_debug_enabled', ( isset($_GET['pinnerpress_debug']) && sanitize_text_field(wp_unslash($_GET['pinnerpress_debug'])) === '1' ));
        
        // Enqueue debugging script if needed
        if ( (bool) apply_filters('pinnerpress_load_debug_assets', WP_DEBUG ) ) {
            wp_enqueue_script($this->plugin_name . '-debug', plugin_dir_url(__FILE__) . 'js/pinnerpress-block-debugging.js', array('jquery', $this->plugin_name), $this->version, true);
        }

        // Check premium feature availability once
        $can_customize_pin = $this->is_feature_on('pin_button_customization');
        $can_follow_box    = $this->is_feature_on('follow_box');
        $can_image_banner  = $this->is_feature_on('image_banner');
        $can_call_out      = $this->is_feature_on('call_out_banners');

        // Load header/profile images with fallback (single lookup each)
        $header_img  = $this->get_opt('header_image', '');
        $profile_img = $this->get_opt('profile_image', '');

        // Custom selector settings with fallback to old option names
        $custom_sel_enabled = $this->get_opt('custom_selectors_enabled', '');
        if ($custom_sel_enabled === '') {
            $custom_sel_enabled = $this->get_opt('pin_button_custom_selectors_enabled', '0');
        }
        $custom_sel = $this->get_opt('custom_selectors', '');
        if ($custom_sel === '') {
            $custom_sel = $this->get_opt('pin_button_custom_selectors', '');
        }
        $custom_sel_find = $this->get_opt('find_images_in_selectors', '');
        if ($custom_sel_find === '') {
            $custom_sel_find = $this->get_opt('pin_button_find_images_in_selectors', '0');
        }

        // Banner custom selectors with fallback
        $banner_sel_enabled = $this->get_opt('custom_selectors_enabled', '');
        if ($banner_sel_enabled === '') {
            $banner_sel_enabled = $this->get_opt('banner_custom_selectors_enabled', '0');
        }
        $banner_sel = $this->get_opt('custom_selectors', '');
        if ($banner_sel === '') {
            $banner_sel = $this->get_opt('banner_custom_selectors', '');
        }
        $banner_sel_find = $this->get_opt('find_images_in_selectors', '');
        if ($banner_sel_find === '') {
            $banner_sel_find = $this->get_opt('banner_find_images_in_selectors', '0');
        }

        // Localize the script with settings data (all options loaded in one batch query)
        wp_localize_script($this->plugin_name, 'pinnerpress_data', array(
            // Debug settings
            'debug_enabled' => $debug_enabled,
            'debug_mode' => 'verbose',
            
            // Pin button settings (with premium restrictions)
            'pin_button_status' => $this->get_opt('pin_button_status', 'on'),
            'position' => $can_customize_pin ? $this->get_opt('hover_button_position', 'top-right') : 'top-right',
            'shape' => $can_customize_pin ? $this->get_opt('hover_button_shape', 'rectangular') : 'rectangular',
            'size' => $can_customize_pin ? $this->get_opt('hover_button_size', 'medium') : 'medium',
            'color' => $can_customize_pin ? $this->get_opt('hover_button_color', '#E60023') : '#E60023',
            'text_color' => $can_customize_pin ? $this->get_opt('hover_button_text_color', '#FFFFFF') : '#FFFFFF',
            'image_shadow' => $can_customize_pin ? $this->get_opt('image_shadow', '0') : '0',
            'custom_button_text' => $can_customize_pin ? $this->get_opt('custom_button_text', '') : '',
            'default_text' => __('Pin It', 'pinnerpress'),
            'button_style' => $can_customize_pin ? $this->get_opt('hover_button_style', 'default') : 'default',
            'minimum_image_size' => $this->get_opt('minimum_image_size', '250'),
            'exclude_gallery_minimum' => $this->get_opt('exclude_gallery_minimum', '0'),
            'size_filter_pin_buttons' => $this->get_opt('size_filter_pin_buttons', '1'),
            'size_filter_image_banners' => $this->get_opt('size_filter_image_banners', '1'),

            // Custom selector settings (unified from Filters tab, with fallback to old settings)
            'pin_button_custom_selectors_enabled' => $custom_sel_enabled,
            'pin_button_custom_selectors' => $custom_sel,
            'pin_button_find_images_in_selectors' => $custom_sel_find,

            // Follow box settings (premium feature)
            'follow_box_status' => $can_follow_box ? $this->get_opt('follow_box_status', 'off') : 'off',
            'pinterest_username' => $this->get_validated_pinterest_url($this->get_opt('pinterest_url', '')),
            'display_name' => $this->get_opt('pinterest_display_name', 'PinnerPress'),
            'account_description' => $this->get_opt('account_description', __('Follow us on Pinterest for more inspiration!', 'pinnerpress')),
            'follow_button_bg_color' => $this->get_opt('follow_button_bg_color', '#E60023'),
            'follow_button_text_color' => $this->get_opt('follow_button_text_color', '#FFFFFF'),
            'follow_box_display_pin_click' => $this->get_opt('follow_box_display_pin_click', '1'),
            'follow_box_display_page_load' => $this->get_opt('follow_box_display_page_load', '0'),
            'follow_box_allow_dismiss' => $this->get_opt('follow_box_allow_dismiss', '0'),
            'header_image' => !empty($header_img) ? $header_img : esc_url(plugin_dir_url(__FILE__) . 'images/follow-box/default-pinterest-profile-header-image.png'),
            'profile_image' => !empty($profile_img) ? $profile_img : esc_url(plugin_dir_url(__FILE__) . 'images/follow-box/default-pinterest-profile-images.png'),
            
            // Banner settings (premium feature)
            'banner_status' => $can_image_banner ? $this->get_opt('banner_status', 'off') : 'off',
            'banner_bg_color' => $this->get_opt('banner_bg_color', 'rgba(255, 255, 255, 0.5)'),
            'banner_text_color' => $this->get_opt('banner_text_color', '#BD081C'),
            'banner_text' => $this->get_opt('banner_text', __('Pin this', 'pinnerpress')),
            'banner_opacity' => $this->get_opt('banner_opacity', '50'),

            // Custom selector settings for Image Banner (unified from Filters tab, with fallback to old settings)
            'banner_custom_selectors_enabled' => $banner_sel_enabled,
            'banner_custom_selectors' => $banner_sel,
            'banner_find_images_in_selectors' => $banner_sel_find,

            // Call Out Banner settings (premium feature)
            'call_out_status' => $can_call_out ? $this->get_opt('call_out_status', 'off') : 'off',
            'call_out_position' => $this->get_opt('call_out_position', 'bottom'),
            'call_out_display_posts' => $this->get_opt('call_out_display_posts', '1'),
            'call_out_display_pages' => $this->get_opt('call_out_display_pages', '0'),
            'call_out_style' => $this->get_opt('call_out_style', 'classic'),
            'call_out_bg_color' => $this->get_opt('call_out_bg_color', '#E60023'),
            'call_out_border_color' => $this->get_opt('call_out_border_color', '#E60023'),
            'call_out_text_color' => $this->get_opt('call_out_text_color', '#FFFFFF'),
            'call_out_title' => $this->get_opt('call_out_title', __('Follow us on Pinterest', 'pinnerpress')),
            'call_out_description' => $this->get_opt('call_out_description', __('Get more inspiration and ideas by following our Pinterest boards.', 'pinnerpress')),
            'call_out_button_text' => $this->get_opt('call_out_button_text', __('Follow', 'pinnerpress')),
            'call_out_button_bg_color' => $this->get_opt('call_out_button_bg_color', '#FFFFFF'),
            'call_out_button_text_color' => $this->get_opt('call_out_button_text_color', '#E60023'),
            'call_out_show_icon' => $this->get_opt('call_out_show_icon', '1'),
            'call_out_logo' => $this->get_opt('call_out_logo', 'pinterest'),
            
            // Per-post override settings (only available on singular pages)
            'post_disable_pin_buttons' => is_singular() ? get_post_meta(get_the_ID(), '_pinnerpress_disable_pin_buttons', true) : '0',
            'post_disable_image_banners' => is_singular() ? get_post_meta(get_the_ID(), '_pinnerpress_disable_image_banners', true) : '0',
            'post_disable_follow_box' => is_singular() ? get_post_meta(get_the_ID(), '_pinnerpress_disable_follow_box', true) : '0',

            // Category exclusions (disabled if in excluded categories)
            'category_disable_pin_button' => $this->is_post_in_excluded_categories('pin_button') ? '1' : '0',
            'category_disable_follow_box' => $this->is_post_in_excluded_categories('follow_box') ? '1' : '0',
            'category_disable_banner' => $this->is_post_in_excluded_categories('banner') ? '1' : '0',
            'category_disable_call_out' => $this->is_post_in_excluded_categories('call_out') ? '1' : '0',
            
            // Analytics settings
            'analytics_enabled' => $this->get_opt('analytics_enabled', '1'),
            'analytics_nonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
            'ajaxurl' => admin_url('admin-ajax.php'),
            'post_id' => is_singular() ? get_the_ID() : null,
            
            // Debug information
            'debug_follow_box_status_raw' => $this->get_opt('follow_box_status'),
            'debug_time' => current_time('mysql'),
            'debug_version' => $this->version
        ));
    }

    /**
     * Get a plugin option from the cached batch.
     * Loads all pinnerpress_* options in one query on first call.
     *
     * @since    1.3.2
     * @param    string    $key        Option name (without pinnerpress_ prefix).
     * @param    mixed     $default    Default value if option not set.
     * @return   mixed                 Option value.
     */
    private function get_opt($key, $default = '') {
        if ($this->cached_options === null) {
            $this->load_all_options();
        }
        $full_key = 'pinnerpress_' . $key;
        return isset($this->cached_options[$full_key]) ? $this->cached_options[$full_key] : $default;
    }

    /**
     * Load all pinnerpress_* options in a single DB query.
     * WordPress autoloads options marked autoload=yes into the alloptions cache,
     * but options registered without autoload still cause individual queries.
     * This method loads everything in one shot.
     *
     * @since    1.3.2
     * @access   private
     */
    private function load_all_options() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Batch-loading all plugin options in one query to replace 69+ individual get_option() calls
        $results = $wpdb->get_results(
            "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE 'pinnerpress_%'",
            OBJECT
        );
        $this->cached_options = array();
        if ($results) {
            foreach ($results as $row) {
                $this->cached_options[$row->option_name] = $row->option_value;
            }
        }
    }

    /**
     * Check if a premium feature is enabled (cached wrapper).
     *
     * @since    1.3.2
     * @param    string    $feature    Feature name.
     * @return   bool                  True if feature is enabled.
     */
    private function is_feature_on($feature) {
        return function_exists('pinnerpress_is_feature_enabled') && pinnerpress_is_feature_enabled($feature);
    }

    /**
     * Emit debug messages without using error_log so production builds remain clean.
     * Integrators can hook 'pinnerpress_debug_log' to route messages to their logger.
     */
    private function pinnerpress_debug_log($message) {
        do_action('pinnerpress_debug_log', $message);
    }

    /**
     * Check if current post is in excluded categories for a feature
     *
     * @since    0.1.0
     * @access   private
     * @param    string    $feature    The feature to check (e.g. 'pin_button', 'follow_box', 'banner', 'call_out')
     * @return   boolean               True if post is in excluded categories, false otherwise
     */
    private function is_post_in_excluded_categories($feature) {
        // Return cached result if available (called 4x per page for different features)
        // Cache key includes post ID so archive pages with multiple posts get correct results
        $post_id = get_the_ID();
        $cache_key = $feature . '_' . $post_id;
        if (isset($this->cached_category_exclusions[$cache_key])) {
            return $this->cached_category_exclusions[$cache_key];
        }

        if (!is_singular('post')) {
            $this->cached_category_exclusions[$cache_key] = false;
            return false;
        }

        // Map feature names to the filter option names (use get_opt for batch-loaded options)
        $filter_option_map = array(
            'pin_button' => 'category_filter_pin_buttons',
            'banner' => 'category_filter_image_banners',
            'follow_box' => 'category_filter_follow_boxes',
            'call_out' => 'category_filter_call_out_banners'
        );

        // Debug logging
        $debug = (bool) apply_filters('pinnerpress_public_debug_logging', false);

        if ($debug) {
            $this->pinnerpress_debug_log("=== PinnerPress Category Filter Debug for feature: {$feature} ===");
        }

        // Check if category filtering is enabled for this feature
        $filter_key = isset($filter_option_map[$feature]) ? $filter_option_map[$feature] : '';
        $filter_value = $filter_key ? $this->get_opt($filter_key, 1) : 1;

        if ($debug) {
            $this->pinnerpress_debug_log("Filter option: pinnerpress_{$filter_key}");
            $this->pinnerpress_debug_log("Filter value from DB: " . wp_json_encode($filter_value));
            $this->pinnerpress_debug_log("Filter enabled (1=yes, 0=no): " . ($filter_value == 1 ? 'YES' : 'NO'));
        }

        if ($filter_key && $filter_value != 1) {
            // Category filtering is disabled for this feature
            if ($debug) {
                $this->pinnerpress_debug_log("Category filtering is DISABLED for {$feature} - returning false (allow feature)");
            }
            $this->cached_category_exclusions[$cache_key] = false;
            return false;
        }

        // Get the unified excluded categories list (from batch-loaded options)
        $excluded_categories = $this->get_opt('excluded_categories', array());
        // Option values from batch load are strings; unserialize if needed
        if (is_string($excluded_categories)) {
            $excluded_categories = maybe_unserialize($excluded_categories);
        }

        if ($debug) {
            $this->pinnerpress_debug_log("Excluded categories: " . wp_json_encode($excluded_categories));
        }

        if (empty($excluded_categories) || !is_array($excluded_categories)) {
            if ($debug) {
                $this->pinnerpress_debug_log("No excluded categories - returning false (allow feature)");
            }
            $this->cached_category_exclusions[$cache_key] = false;
            return false;
        }

        $post_categories = wp_get_post_categories(get_the_ID());

        if ($debug) {
            $this->pinnerpress_debug_log("Post categories: " . wp_json_encode($post_categories));
        }

        // Check if any of the post's categories are in the excluded list
        foreach ($post_categories as $cat_id) {
            if (in_array($cat_id, $excluded_categories)) {
                if ($debug) {
                    $this->pinnerpress_debug_log("Post category {$cat_id} is in excluded list - returning true (BLOCK feature)");
                }
                $this->cached_category_exclusions[$cache_key] = true;
                return true;
            }
        }

        if ($debug) {
            $this->pinnerpress_debug_log("Post categories not in excluded list - returning false (allow feature)");
        }
        $this->cached_category_exclusions[$cache_key] = false;
        return false;
    }

    /**
     * Insert Call Out Banner into post/page content
     *
     * @since    0.1.0
     * @param    string    $content    The post content
     * @return   string                The modified content with banner
     */
    public function insert_call_out_banner($content) {
        // Check if call out banners feature is available
        if (function_exists('pinnerpress_is_feature_enabled') && !pinnerpress_is_feature_enabled('call_out_banners')) {
            return $content;
        }
        
        // Check if call out banner is enabled (use batch-loaded options)
        if ($this->get_opt('call_out_status', 'off') !== 'on') {
            return $content;
        }
        
        // Check if call out banners are disabled for this specific post
        if (is_singular() && get_post_meta(get_the_ID(), '_pinnerpress_disable_call_out_banners', true) === '1') {
            return $content;
        }

        // Check if post is in excluded categories
        if ($this->is_post_in_excluded_categories('call_out')) {
            return $content;
        }
        
        // Check if we should display on this post type
        $post_type = get_post_type();
        if ($post_type === 'post' && $this->get_opt('call_out_display_posts', '1') !== '1') {
            return $content;
        }
        if ($post_type === 'page' && $this->get_opt('call_out_display_pages', '0') !== '1') {
            return $content;
        }
        
        // Only show on single posts, not on homepage or archive pages
        if (!is_single() || is_home() || is_front_page()) {
            return $content;
        }
        
        // Get banner position (use batch-loaded options)
        $position = $this->get_opt('call_out_position', 'bottom');
        
        // Get all required settings for the banner (from batch-loaded options)
        $bg_color = $this->get_opt('call_out_bg_color', '#E60023');
        $text_color = $this->get_opt('call_out_text_color', '#FFFFFF');
        $title = $this->get_opt('call_out_title', __('Follow us on Pinterest', 'pinnerpress'));
        $button_text = $this->get_opt('call_out_button_text', __('Follow', 'pinnerpress'));
        $button_bg_color = $this->get_opt('call_out_button_bg_color', '#FFFFFF');
        $button_text_color = $this->get_opt('call_out_button_text_color', '#E60023');
        $logo = $this->get_opt('call_out_logo', 'pinterest');
        
        // Get current post permalink and title for Pinterest sharing
        $permalink = urlencode(get_permalink());
        $post_title = urlencode(get_the_title());
        
        // Get featured image if available
        $media = '';
        if (has_post_thumbnail()) {
            $featured_img_url = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
            if ($featured_img_url) {
                $media = urlencode($featured_img_url[0]);
            }
        }
        
        // Create Pinterest pin URL
        $pin_url = "https://www.pinterest.com/pin/create/button/?url={$permalink}&description={$post_title}";
        if (!empty($media)) {
            $pin_url .= "&media={$media}";
        }
        
        // Generate the banner HTML
        $banner_html = '<div class="pinnerpress-call-out-banner" style="background-color: ' . esc_attr($bg_color) . '; color: ' . esc_attr($text_color) . '; padding: 15px 25px; border-radius: 6px; display: flex; align-items: center; justify-content: space-between; text-align: center; flex-wrap: nowrap; margin: 30px 0;">';
        
        // Add logo on left (if enabled)
        if ($logo === 'pinterest') {
            $banner_html .= '<div class="pinnerpress-logo" style="display: flex; align-items: center; justify-content: flex-start; margin-right: 15px; width: auto; min-width: 38px; flex-shrink: 0;">';
            $banner_html .= '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width: 38px; height: 38px; fill: ' . esc_attr($text_color) . ';">';
            $banner_html .= '<path d="M12 0C5.373 0 0 5.373 0 12c0 4.99 3.657 9.132 8.48 10.099-.118-.859-.224-2.178.045-3.116.244-.834 1.577-5.313 1.577-5.313s-.402-.803-.402-1.986c0-1.863 1.08-3.254 2.42-3.254 1.142 0 1.693.859 1.693 1.89 0 1.151-.733 2.87-1.11 4.467-.318 1.322.672 2.401 1.99 2.401 2.388 0 4.224-2.516 4.224-6.14 0-3.204-2.303-5.442-5.581-5.442-3.803 0-6.037 2.849-6.037 5.794 0 1.148.438 2.382 1.054 3.049.117.13.134.244.099.377-.109.427-.354 1.35-.398 1.539-.062.248-.2.302-.461.182-1.723-.796-2.797-3.294-2.797-5.301 0-4.33 3.141-8.306 9.067-8.306 4.754 0 8.442 3.384 8.442 7.917 0 4.715-2.969 8.502-7.085 8.502-1.381 0-2.681-.712-3.123-1.557l-.847 3.216c-.306 1.156-1.14 2.6-1.699 3.487C9.19 23.414 10.573 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"></path>';
            $banner_html .= '</svg>';
            $banner_html .= '</div>';
        } elseif ($logo === 'profile') {
            // Get profile image URL
            $profile_image = get_option('pinnerpress_profile_image', '');
            
            // If no custom profile image is set, use the default one
            if (empty($profile_image)) {
                $profile_image = esc_url(plugin_dir_url(__FILE__) . 'images/follow-box/default-pinterest-profile-images.png');
            }
            
            $banner_html .= '<div class="pinnerpress-logo" style="display: flex; align-items: center; justify-content: flex-start; margin-right: 15px; width: auto; min-width: 38px; flex-shrink: 0;">';
            $banner_html .= '<img src="' . esc_url($profile_image) . '" alt="Profile" style="width: 38px; height: 38px; border-radius: 50%;" />';
            $banner_html .= '</div>';
        }
        
        // Replace h3 with span for the title
        $banner_html .= '<span style="color: ' . esc_attr($text_color) . ' !important; font-weight: 600; margin: 0; font-size: 24px !important; text-align: center; flex: 1; display: flex; justify-content: center; align-items: center;">' . esc_html($title) . '</span>';
        
        // Get the Pinterest profile URL
        $pinterest_profile_url = $this->get_validated_pinterest_url(get_option('pinnerpress_pinterest_url', ''));
        
        // Add button on right (pill shaped)
        $banner_html .= '<a href="' . esc_url($pinterest_profile_url) . '" target="_blank" class="pinnerpress-call-out-button" data-pinnerpress-track="call_out_banner_click" style="display: inline-block; background-color: ' . esc_attr($button_bg_color) . ' !important; padding: 8px 15px; text-decoration: none !important; border-radius: 50px; font-weight: 700; white-space: nowrap; margin-left: 15px; min-width: 90px; text-align: center; flex-shrink: 0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); font-size: 16px; line-height: 1.4;">';
        $banner_html .= '<span style="color: ' . esc_attr($button_text_color) . ' !important;">' . esc_html($button_text) . '</span>';
        $banner_html .= '</a>';
        
        $banner_html .= '</div>';
        
        // Add responsive styles for mobile
        $banner_html .= '<style>
            @media (max-width: 768px) {
                .pinnerpress-call-out-banner {
                    flex-direction: column;
                    padding: 20px;
                    align-items: center;
                }
                /* Target the title span specifically for its mobile margin */
                .pinnerpress-call-out-banner > span:not(.pinnerpress-button-text-span) { 
                    margin: 10px 0 10px 0 !important; /* Reduced bottom margin, or set to 0 if no extra margin needed */
                    text-align: center;
                    display: block;
                    width: 100%;
                }
                .pinnerpress-call-out-button {
                    width: 100%;
                    max-width: 200px;
                    margin: 0 auto 5px !important; /* Adjusted button margin */
                    padding: 6px 12px !important; /* Reduced padding for mobile */
                }
                .pinnerpress-call-out-button span.pinnerpress-button-text-span {
                    margin: 0 !important; /* Ensure no extra margin on button text */
                    padding: 0 !important; /* Ensure no extra padding on button text */
                }
                .pinnerpress-logo {
                    margin: 0 auto 10px !important;
                }
            }
        </style>';
        
        // Insert the banner at the appropriate position
        if ($position === 'top') {
            return $banner_html . $content;
        } elseif ($position === 'bottom') {
            return $content . $banner_html;
        } elseif ($position === 'both') {
            return $banner_html . $content . $banner_html;
        }
        
        // Default to bottom if something went wrong
        return $content . $banner_html;
    }

    /**
     * Get validated and correctly formatted Pinterest URL
     *
     * @since    0.1.0
     * @param    string    $url    The Pinterest URL to validate and format
     * @return   string             The validated Pinterest URL
     */
    private function get_validated_pinterest_url($url) {
        // Trim whitespace
        $url = trim($url);
        
        // If empty, return empty string
        if (empty($url)) {
            return '';
        }
        
        // Check if it's already a full Pinterest URL
        if (preg_match('~^https?://(?:www\.)?pinterest\.[a-z\.]{2,}/[\w\-\.]+/?.*$~i', $url)) {
            // Already a full Pinterest URL, just ensure https
            return preg_replace('~^http://~i', 'https://', $url);
        }
        
        // If URL doesn't contain pinterest domain, it's likely just a username
        if (!empty($url) && strpos($url, 'pinterest') === false) {
            // Assume it's a username and construct the URL
            return 'https://www.pinterest.com/' . $url;
        }
        
        // Check if URL has protocol
        if (!preg_match('~^(?:f|ht)tps?://~i', $url)) {
            $url = 'https://' . $url;
        }
        
        // If URL is not in the expected format but contains pinterest domain
        // Extract username and rebuild the URL
        if (preg_match('~pinterest\.[a-z\.]{2,}/([^/?&#]+)~i', $url, $matches)) {
            if (!empty($matches[1])) {
                return 'https://www.pinterest.com/' . $matches[1];
            }
        }
        
        // If we can't extract or validate, return the URL with https:// protocol
        return preg_replace('~^(?:f|ht)tp://~i', 'https://', $url);
    }

    /**
     * Insert Pinterest rich pin meta tag into head
     *
     * @since    0.1.0
     */
    public function insert_pinterest_meta_tag() {
        // Check if rich pins feature is available for this user
        if (!function_exists('pinnerpress_is_feature_enabled') || !pinnerpress_is_feature_enabled('disable_rich_pins')) {
            return;
        }
        
        // Only add the meta tag if the disable rich pins option is enabled
        if (get_option('pinnerpress_disable_rich_pins') === 'on') {
            echo '<meta name="pinterest-rich-pin" content="false" />';
        }
    }

} }
