<?php

/**
 * The image analytics overlay functionality of the plugin.
 *
 * @link       https://pinnerpress.com
 * @since      1.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */

/**
 * The image analytics overlay functionality of the plugin.
 *
 * Handles the admin bar toggle and display of image analytics overlays on posts.
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */
if (!class_exists('PinnerPress_Image_Analytics_Overlay')) {
class PinnerPress_Image_Analytics_Overlay {

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

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

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.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 admin bar menu item
        add_action('admin_bar_menu', array($this, 'add_admin_bar_toggle'), 100);
        
        // Handle AJAX toggle
        add_action('wp_ajax_pinnerpress_toggle_image_analytics', array($this, 'handle_toggle_ajax'));
        
        // Enqueue frontend scripts and styles when enabled
        add_action('wp_enqueue_scripts', array($this, 'enqueue_overlay_assets'));
        
        // Add inline data for analytics
        add_action('wp_footer', array($this, 'add_analytics_data'));
    }

    /**
     * Add toggle to admin bar when viewing posts.
     *
     * @since    1.1.0
     * @param    WP_Admin_Bar    $admin_bar    The admin bar object.
     */
    public function add_admin_bar_toggle($admin_bar) {
        // Only show on single posts for admins
        // WordPress doesn't provide body_class in PHP, but is_singular('post') 
        // ensures we're on a single post which typically has the single-post body class
        if (!is_singular('post') || !current_user_can('manage_options')) {
            return;
        }

        // Get current toggle state
        $is_enabled = $this->get_toggle_state();
        
        // Add main menu item
        $admin_bar->add_node(array(
            'id'    => 'pinnerpress-image-analytics',
            'title' => '<span class="ab-icon dashicons dashicons-chart-pie"></span><span class="ab-label">' . 
                      ($is_enabled ? __('PinnerPress Analytics: ON', 'pinnerpress') : __('PinnerPress Analytics: OFF', 'pinnerpress')) . '</span>',
            'href'  => '#',
            'meta'  => array(
                'class' => 'pinnerpress-analytics-toggle' . ($is_enabled ? ' enabled' : ''),
                'title' => __('Toggle image analytics overlay', 'pinnerpress')
            )
        ));
    }

    /**
     * Get the current toggle state for the user.
     *
     * @since    1.1.0
     * @return   bool    Whether analytics overlay is enabled.
     */
    private function get_toggle_state() {
        $user_id = get_current_user_id();
        return get_user_meta($user_id, 'pinnerpress_image_analytics_enabled', true) === '1';
    }

    /**
     * Handle AJAX request to toggle analytics state.
     *
     * @since    1.1.0
     */
    public function handle_toggle_ajax() {
        // Check nonce for security
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'pinnerpress_toggle_analytics')) {
            wp_die('Security check failed');
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }

        $user_id = get_current_user_id();
        $current_state = $this->get_toggle_state();
        $new_state = $current_state ? '0' : '1';
        
        update_user_meta($user_id, 'pinnerpress_image_analytics_enabled', $new_state);
        
        wp_send_json_success(array(
            'enabled' => $new_state === '1',
            'message' => $new_state === '1' ? __('Analytics overlay enabled', 'pinnerpress') : __('Analytics overlay disabled', 'pinnerpress')
        ));
    }

    /**
     * Enqueue overlay assets when analytics is enabled.
     *
     * @since    1.1.0
     */
    public function enqueue_overlay_assets() {
        // Debug output
        if (is_singular('post') && current_user_can('manage_options')) {

        }
        
        // Only on single posts for admins with analytics enabled
        if (!is_singular('post') || !current_user_can('manage_options') || !$this->get_toggle_state()) {
            return;
        }

        

        // Enqueue overlay styles
        wp_enqueue_style(
            'pinnerpress-analytics-overlay',
            plugin_dir_url(dirname(__FILE__)) . 'public/css/pinnerpress-analytics-overlay.css',
            array(),
            $this->version
        );

        // Enqueue overlay script
        wp_enqueue_script(
            'pinnerpress-analytics-overlay',
            plugin_dir_url(dirname(__FILE__)) . 'public/js/pinnerpress-analytics-overlay.js',
            array('jquery'),
            $this->version,
            true
        );

        // Add localization
        wp_localize_script('pinnerpress-analytics-overlay', 'pinnerpressAnalyticsOverlay', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
            'postId' => get_the_ID(),
            'toggleNonce' => wp_create_nonce('pinnerpress_toggle_analytics'),
            'siteUrl' => site_url(),
            'debug' => true, // Add debug flag
            'pinButtonPosition' => get_option('pinnerpress_hover_button_position', 'top-left'), // Add pin button position
            'i18n' => array(
                'totalClicks' => __('Total Clicks', 'pinnerpress'),
                'pinButton' => __('Pin Button', 'pinnerpress'),
                'imageBanner' => __('Image Banner', 'pinnerpress'),
                'noData' => __('No analytics data', 'pinnerpress'),
                'loading' => __('Loading analytics...', 'pinnerpress'),
                'error' => __('Error loading analytics', 'pinnerpress')
            )
        ));
    }

    /**
     * Add analytics data to the page.
     *
     * @since    1.1.0
     */
    public function add_analytics_data() {
        // Show toggle script on all single posts for admins
        if (!is_singular('post') || !current_user_can('manage_options')) {
            return;
        }

        // Only show debug message when analytics is enabled
        if ($this->get_toggle_state()) {
            ?>
            <div id="pinnerpress-analytics-debug" style="position: fixed; bottom: 10px; left: 10px; background: #000; color: #fff; padding: 10px; border-radius: 5px; z-index: 99999; font-size: 12px;">
                PinnerPress Analytics: Overlay Active
            </div>
            <?php
        }

        // Always add the toggle script for admins on single posts
        ?>
        <!-- PinnerPress Analytics Toggle Script -->
        <script>
        (function($) {
            if (typeof jQuery === 'undefined') {
                if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.error('PinnerPress Analytics: jQuery is not loaded'); }
                return;
            }
            
            $(document).ready(function() {
                if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('PinnerPress Analytics: Toggle script loaded'); }
                
                // Need to create localization data for toggle if main script isn't loaded
                if (typeof pinnerpressAnalyticsOverlay === 'undefined') {
                    window.pinnerpressAnalyticsOverlay = {
                        ajaxurl: '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
                        toggleNonce: '<?php echo esc_js(wp_create_nonce('pinnerpress_toggle_analytics')); ?>'
                    };
                }
            
            // Handle admin bar toggle click
            $('#wp-admin-bar-pinnerpress-image-analytics a').on('click', function(e) {
                e.preventDefault();
                
                var $toggle = $(this).parent();
                var isEnabled = $toggle.hasClass('enabled');
                
                if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('PinnerPress Analytics: Toggle clicked, current state:', isEnabled ? 'ON' : 'OFF'); }
                
                // Send AJAX request to toggle state
                $.post(pinnerpressAnalyticsOverlay.ajaxurl, {
                    action: 'pinnerpress_toggle_image_analytics',
                    nonce: pinnerpressAnalyticsOverlay.toggleNonce
                }, function(response) {
                    if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('PinnerPress Analytics: Toggle response', response); }
                    if (response.success) {
                        // Reload page to apply changes
                        location.reload();
                    }
                }).fail(function(xhr, status, error) {
                    if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.error('PinnerPress Analytics: Toggle failed', status, error); }
                });
            });
            
            // Hide debug message after 5 seconds if it exists
            if ($('#pinnerpress-analytics-debug').length) {
                setTimeout(function() {
                    $('#pinnerpress-analytics-debug').fadeOut();
                }, 5000);
            }
        });
        })(jQuery);
        </script>
        <?php
    }
} }
