<?php

/**
 * Provide a admin area view for the plugin dashboard
 *
 * This file is used to markup the admin-facing dashboard of the plugin.
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/admin/partials
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Check if user has premium access
$is_premium = function_exists('pinnerpress_is_premium') ? pinnerpress_is_premium() : false;

// Check if user can use premium features (includes trial users)
$can_use_premium_features = function_exists('pinnerpress_can_use_premium_features') ? pinnerpress_can_use_premium_features() : false;

// Set default date range for the chart
$default_end_date = current_time('Y-m-d');
$default_start_date = gmdate('Y-m-d', strtotime('-30 days', strtotime($default_end_date)));

$top_posts_event_type = 'pin_button_click';
$top_posts = $analytics->get_top_posts_by_event_type($default_start_date, $default_end_date, $top_posts_event_type, 5);
?>

<div class="wrap pinnerpress-admin pinnerpress-dashboard" data-server-date="<?php echo esc_attr($default_end_date); ?>">
    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
    
    <div class="pinnerpress-admin-header">
        <div class="pinnerpress-logo">
            <img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . 'images/pinnerpress-logo.png'); ?>" alt="<?php echo esc_attr__('PinnerPress Logo', 'pinnerpress'); ?>">
        </div>
                <div class="pinnerpress-header-content">
            <h2><?php esc_html_e('PinnerPress Dashboard', 'pinnerpress'); ?></h2>
            <p><?php esc_html_e('Track your Pinterest engagement and monitor your performance metrics.', 'pinnerpress'); ?></p>
        </div>
</div>

<?php
// Ensure event_types is properly set for JavaScript
if (!isset($event_types) || !is_array($event_types)) {
    $event_types = array();
}
?>

<style>
.pinnerpress-analytics-container {
    margin-top: 20px;
}

.pinnerpress-analytics-controls {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.pinnerpress-date-controls {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.pinnerpress-date-controls label {
    font-weight: 600;
    white-space: nowrap;
}

.pinnerpress-date-controls input[type="date"] {
    margin-right: 5px;
}

.pinnerpress-date-preset {
    margin-left: 5px;
}

.pinnerpress-analytics-chart-container {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    position: relative;
}

.pinnerpress-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
}

.pinnerpress-analytics-summary {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
}

.pinnerpress-totals-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-top: 15px;
}

.pinnerpress-total-item {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    text-align: center;
}

.pinnerpress-total-number {
    font-size: 24px;
    font-weight: 600;
                color: #E60023;
    display: block;
}

.pinnerpress-total-label {
    font-size: 14px;
    color: #646970;
    margin-top: 5px;
}

.pinnerpress-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.pinnerpress-top-posts-list ol.pinnerpress-ordered-list {
    list-style-type: decimal;
    margin-left: 20px;
    padding-left: 5px;
}

.pinnerpress-top-posts-list ol.pinnerpress-ordered-list li {
    margin-bottom: 8px;
    font-size: 14px;
}

.pinnerpress-top-posts-list .pinnerpress-count {
    color: #646970;
    font-size: 0.9em;
}

.pinnerpress-analytics-limitation {
    border-left: 4px solid #E60023;
    padding: 12px;
    background-color: #fef4f4;
    margin: 20px 0;
}

.pinnerpress-analytics-limitation h4 {
    margin-top: 0;
    color: #E60023;
}

.pinnerpress-analytics-limitation p {
    margin-bottom: 10px;
}

/* Upgrade Banner Styles */
.pinnerpress-upgrade-banner {
    background: linear-gradient(135deg, #E60023 0%, #c7001e 100%);
    color: white;
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(230, 0, 35, 0.2);
}

.pinnerpress-upgrade-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 15px;
}

.pinnerpress-upgrade-icon {
    font-size: 24px;
    margin-right: 10px;
}

.pinnerpress-upgrade-text {
    flex: 1;
    font-size: 16px;
    font-weight: 500;
}

.pinnerpress-upgrade-btn {
    background: white;
    color: #E60023;
    padding: 8px 16px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
    display: inline-block;
}

.pinnerpress-upgrade-btn:hover {
    background: #f8f9fa;
    color: #c7001e;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

@media (max-width: 768px) {
    .pinnerpress-upgrade-content {
        flex-direction: column;
        text-align: center;
    }

    .pinnerpress-upgrade-text {
        margin-bottom: 10px;
    }
}

/* PinnerPress Button Styling for Dashboard */
.pinnerpress-admin .button-primary {
    background-color: #E60023 !important;
    border-color: #E60023 !important;
    color: white !important;
    transition: all 0.3s ease;
}

.pinnerpress-admin .button-primary:hover {
    background-color: #c7001e !important;
    border-color: #c7001e !important;
}

.pinnerpress-admin .button-secondary {
    background-color: #fff !important;
    color: #E60023 !important;
    border: 1px solid #E60023 !important;
    transition: all 0.3s ease;
}

.pinnerpress-admin .button-secondary:hover {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

.pinnerpress-date-preset {
    background-color: #fff !important;
    color: #E60023 !important;
    border: 1px solid #E60023 !important;
    transition: all 0.3s ease;
}

.pinnerpress-date-preset:hover {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

.pinnerpress-date-preset.active {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

#pinnerpress-update-chart {
    background-color: #E60023 !important;
    border-color: #E60023 !important;
    color: white !important;
}

#pinnerpress-update-chart:hover {
    background-color: #c7001e !important;
    border-color: #c7001e !important;
}

.pinnerpress-analytics-limitation .button-primary {
    background-color: #E60023 !important;
    border-color: #E60023 !important;
    color: white !important;
}

.pinnerpress-analytics-limitation .button-primary:hover {
    background-color: #c7001e !important;
    border-color: #c7001e !important;
}

/* Free plan restrictions styling */
.pinnerpress-premium-disabled {
    background-color: #f9f9f9 !important;
    border-color: #ddd !important;
    color: #666 !important;
    cursor: not-allowed !important;
    opacity: 0.6;
}

.pinnerpress-premium-disabled:hover {
    background-color: #f9f9f9 !important;
    border-color: #ddd !important;
    color: #666 !important;
}

input:disabled {
    background-color: #f9f9f9 !important;
    color: #666 !important;
    cursor: not-allowed !important;
}
</style>


    
    <div class="pinnerpress-admin-content">
        <?php if (!$can_use_premium_features): ?>
            <?php 
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Function returns properly escaped HTML
            echo pinnerpress_get_upgrade_notification(); 
            ?>
        <?php endif; ?>
        
        <?php
        // Add method to get event colors (this would normally be in the admin class)
        if (!function_exists('pinnerpress_get_event_color')) {
            function pinnerpress_get_event_color($event_type) {
                $colors = array(
                    'pin_button_click' => '#FF6384', // Pink
                    'follow_button_click' => '#FFCE56', // Yellow
                    'image_banner_click' => '#4BC0C0', // Teal
                    // 'call_out_banner_click' => '#9966FF', // Purple
                    // 'block_editor_button_click' => '#FF9F40'  // Orange
                );
                
                return isset($colors[$event_type]) ? $colors[$event_type] : '#CCCCCC'; // Default to a light gray
            }
        }

        // Check if analytics is enabled
        $analytics_enabled = get_option('pinnerpress_analytics_enabled', '1') === '1';

        // Get analytics instance with error handling
        $analytics = null;
        $event_types = array();
        
        // Ensure event_types is always an array to prevent JavaScript errors
        if (!is_array($event_types)) {
            $event_types = array();
        }

        try {
            require_once plugin_dir_path(dirname(dirname(__FILE__))) . 'includes/class-pinnerpress-analytics.php';
            
            if (class_exists('PinnerPress_Analytics')) {
                $analytics = new PinnerPress_Analytics();
                
                // Check if analytics table exists, create it if it doesn't (with caching)
                global $wpdb;
                $table_name = $wpdb->prefix . 'pinnerpress_analytics';
                $cache_key = 'pinnerpress_table_exists_main_analytics';
                $table_exists = wp_cache_get($cache_key, 'pinnerpress');
                if ($table_exists === false) {
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe existence check wrapped with caching
                    $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
                    wp_cache_set($cache_key, $table_exists, 'pinnerpress', 300);
                }
                if (!$table_exists) {
                    $analytics->create_table();
                }
                
                $event_types = $analytics->get_event_types();
                
                // Filter event types for free users
                if (!$can_use_premium_features) {
                    $filtered_event_types = array();
                    foreach ($event_types as $event_type => $label) {
                        // Hide Follow Box, Call Out Banner, and Post Block Follow stats for free users
                        if (!in_array($event_type, array('follow_button_click', 'call_out_banner_click', 'block_editor_button_click'), true)) {
                            $filtered_event_types[$event_type] = $label;
                        }
                    }
                    $event_types = $filtered_event_types;
                    // Debug: Log the filtering
                } else {
                    // Debug: Log premium user
                }
            }
        } catch (Exception $e) {
            // Log the error but don't break the page
            $analytics_enabled = false;
        }
        ?>
        
        <?php if (!$analytics_enabled): ?>
            <div class="notice notice-warning">
                <p>
                    <?php 
                    printf(
                        /* translators: %s: Link to settings page */
                        esc_html__('Analytics is currently disabled. You can enable it in the %s.', 'pinnerpress'),
                        '<a href="' . esc_url(admin_url('admin.php?page=pinnerpress-settings&tab=general')) . '">' . esc_html__('General Settings', 'pinnerpress') . '</a>'
                    );
                    ?>
                </p>
            </div>
        <?php endif; ?>
        
        <?php if (empty($event_types)): ?>
            <div class="notice notice-error">
                <p>
                    <?php esc_html_e('Analytics system is not properly initialized.', 'pinnerpress'); ?>
                    <a href="<?php echo esc_url(wp_nonce_url(add_query_arg('pinnerpress_init_analytics', '1'), 'pinnerpress_init_analytics')); ?>" class="button button-secondary">
                        <?php esc_html_e('Initialize Analytics', 'pinnerpress'); ?>
                    </a>
                </p>
            </div>
        <?php endif; ?>
        
        <?php
        // Handle manual analytics initialization
        if (isset($_GET['pinnerpress_init_analytics']) && isset($_GET['_wpnonce']) && current_user_can('manage_options') && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'pinnerpress_init_analytics')) {
            try {
                if ($analytics) {
                    $analytics->create_table();
                    echo '<div class="notice notice-success"><p>' . esc_html__('Analytics system initialized successfully. Please refresh the page.', 'pinnerpress') . '</p></div>';
                }
            } catch (Exception $e) {
                echo '<div class="notice notice-error"><p>' . esc_html__('Failed to initialize analytics system: ', 'pinnerpress') . esc_html($e->getMessage()) . '</p></div>';
            }
        }
        ?>
        
        <div class="pinnerpress-analytics-container">
            <div class="pinnerpress-analytics-controls">
                <div class="pinnerpress-date-controls-row">
                    <div class="pinnerpress-date-inputs">
                        <label for="pinnerpress-start-date"><?php esc_html_e('Start Date:', 'pinnerpress'); ?></label>
                        <input type="date" id="pinnerpress-start-date" value="<?php echo esc_attr($default_start_date); ?>" disabled />
                        
                        <label for="pinnerpress-end-date"><?php esc_html_e('End Date:', 'pinnerpress'); ?></label>
                        <input type="date" id="pinnerpress-end-date" value="<?php echo esc_attr($default_end_date); ?>" disabled />
                    </div>
                    
                    <div class="pinnerpress-date-presets">
                        <button class="pinnerpress-date-preset" data-days="7"><?php esc_html_e('Last 7 Days', 'pinnerpress'); ?></button>
                        <button class="pinnerpress-date-preset active" data-days="30"><?php esc_html_e('Last 30 Days', 'pinnerpress'); ?></button>
                        <button class="pinnerpress-date-preset" data-days="90" <?php if (!$can_use_premium_features) echo 'disabled'; ?>><?php esc_html_e('Last 90 Days', 'pinnerpress'); ?></button>
                    </div>
                </div>
            </div>
            
            <div class="pinnerpress-analytics-chart-container">
                <canvas id="pinnerpress-analytics-chart" width="800" height="400"></canvas>
                <div id="pinnerpress-chart-loading" class="pinnerpress-loading" style="display: none;">
                    <span class="spinner is-active"></span>
                    <?php esc_html_e('Loading analytics data...', 'pinnerpress'); ?>
                </div>
            </div>
            
            <div class="pinnerpress-analytics-summary">
                <h3><?php esc_html_e('Summary', 'pinnerpress'); ?></h3>
                <div id="pinnerpress-analytics-totals" class="pinnerpress-totals-grid">
                    <!-- Totals will be populated by JavaScript -->
                </div>
            </div>
            
            <div class="pinnerpress-analytics-top-posts pinnerpress-card" style="margin-top: 20px;">
                <h3><?php esc_html_e('Top Performing Posts', 'pinnerpress'); ?></h3>
                <div class="pinnerpress-top-posts-controls" style="margin-bottom: 15px;">
                    <label for="pinnerpress-top-posts-event-type"><?php esc_html_e('Show top posts for event type:', 'pinnerpress'); ?></label>
                    <select id="pinnerpress-top-posts-event-type">
                        <?php if (!empty($event_types)): ?>
                            <?php foreach ($event_types as $event_type_val => $label): ?>
                                <option value="<?php echo esc_attr($event_type_val); ?>" <?php selected($event_type_val, 'pin_button_click'); // Default to pin_button_click ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div id="pinnerpress-analytics-top-posts-list" class="pinnerpress-top-posts-list">
                    <p class="pinnerpress-loading-text"><?php esc_html_e('Loading top posts data...', 'pinnerpress'); ?></p>
                    <!-- Top posts list will be populated by JavaScript -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Pass PHP variables to JavaScript
    var pinnerpressVars = {
        isPremium: <?php echo $can_use_premium_features ? 'true' : 'false'; ?>,
        upgradeUrl: '<?php echo esc_js(pinnerpress_get_upgrade_url()); ?>'
    };
</script>

<script>
jQuery(document).ready(function($) {
    // Chart.js will be loaded by the admin script
    let chart = null;
    
    // Ensure date inputs use the server date on load
    const serverDateStr = $('.pinnerpress-dashboard').data('server-date');
    if (serverDateStr) {
        const today = new Date(serverDateStr + 'T00:00:00');
        const start30 = new Date(today.getTime());
        start30.setDate(start30.getDate() - 29); // inclusive last 30 days
        const pad = n => String(n).padStart(2, '0');
        const startStr = `${start30.getFullYear()}-${pad(start30.getMonth() + 1)}-${pad(start30.getDate())}`;
        const endStr = `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`;
        $('#pinnerpress-start-date').val(startStr);
        $('#pinnerpress-end-date').val(endStr);
        // Activate 30-day preset visually
        $('.pinnerpress-date-preset').removeClass('active');
        $('.pinnerpress-date-preset[data-days="30"]').addClass('active');
    }
    
    // Event colors mapping
    const eventColors = {
        'pin_button_click': '#FF6384', // Pink
        'follow_button_click': '#FFCE56', // Yellow
        'image_banner_click': '#4BC0C0', // Teal
        'call_out_banner_click': '#9966FF', // Purple
        'block_editor_button_click': '#FF9F40'  // Orange
    };
    
    // Initialize chart
    function initChart() {
        const ctx = document.getElementById('pinnerpress-analytics-chart').getContext('2d');
        chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: []
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        display: true,
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    title: {
                        display: true,
                        text: '<?php echo esc_js(__('PinnerPress Analytics', 'pinnerpress')); ?>',
                        font: {
                            size: 16
                        }
                    }
                }
            }
        });
    }
    
    // Load analytics data
    function loadAnalyticsData() {
        const startDate = $('#pinnerpress-start-date').val();
        const endDate = $('#pinnerpress-end-date').val();
        const selectedEvents = [];
        
        // Show all event types since there are no checkboxes
        const eventTypes = <?php echo wp_json_encode(isset($event_types) ? $event_types : array()); ?> || {};
        for (const eventType in eventTypes) {
            selectedEvents.push(eventType);
        }
        
        $('#pinnerpress-chart-loading').show();
        
        $.post(ajaxurl, {
            action: 'pinnerpress_get_analytics_data',
            nonce: '<?php echo esc_js(wp_create_nonce('pinnerpress_analytics_nonce')); ?>',
            start_date: startDate,
            end_date: endDate,
            event_types: selectedEvents
        }, function(response) {
            $('#pinnerpress-chart-loading').hide();
            
            if (response.success) {
                // Filter data for free users
                if (typeof pinnerpressFilterChartData === 'function') {
                    response.data = pinnerpressFilterChartData(response.data);
                }
                updateChart(response.data);
                updateTotals(response.data.totals);
            } else {
                if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.error('Failed to load analytics data:', response.data); }
            }
        });
    }
    
    // Update chart with new data
    function updateChart(data) {
        if (!chart) return;

        if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('Chart Data Received:', data); }

        // Process data for Chart.js
        const dates = [];
        const datasets = {};

        // Get all unique dates
        data.daily_data.forEach(item => {
            if (!dates.includes(item.date)) {
                dates.push(item.date);
            }
        });

        // Sort dates
        dates.sort();

        if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('Dates found:', dates); console.log('Daily data items:', data.daily_data.length); }
        
        // Get unique event types from the actual data (after filtering)
        const availableEventTypes = {};
        data.daily_data.forEach(item => {
            if (!availableEventTypes[item.event_type]) {
                availableEventTypes[item.event_type] = true;
            }
        });

        // Initialize datasets only for available event types
        const allEventTypes = <?php echo wp_json_encode(isset($event_types) ? $event_types : array()); ?> || {};

        for (const eventType in availableEventTypes) {
            if (allEventTypes[eventType]) {
                const label = allEventTypes[eventType];
                const color = eventColors[eventType] || '#CCCCCC';

                if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('Event Type:', eventType, 'Label:', label, 'Color:', color); }

                datasets[eventType] = {
                    label: label,
                    data: new Array(dates.length).fill(0),
                    borderColor: color,
                    backgroundColor: color + '20',
                    tension: 0.1
                };
            }
        }
        
        // Fill in the data
        data.daily_data.forEach(item => {
            const dateIndex = dates.indexOf(item.date);
            if (dateIndex !== -1 && datasets[item.event_type]) {
                datasets[item.event_type].data[dateIndex] = parseInt(item.count);
            }
        });
        
        // Update chart
        chart.data.labels = dates;
        chart.data.datasets = Object.values(datasets);
        chart.update();

        if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('Chart updated with', Object.keys(datasets).length, 'datasets and', dates.length, 'dates'); }

        // If no data, show a message
        if (Object.keys(datasets).length === 0) {
            if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.log('No datasets to display - showing empty chart'); }
            // Create a minimal dataset to show the chart structure
            const emptyDataset = {
                label: 'No Data Available',
                data: new Array(dates.length).fill(0),
                borderColor: '#CCCCCC',
                backgroundColor: '#CCCCCC20',
                tension: 0.1,
                pointRadius: 0,
                pointHoverRadius: 0
            };
            chart.data.datasets = [emptyDataset];
            chart.update();
        }
    }
    
    // Update totals display
    function updateTotals(totals) {
        let html = '';
        
        totals.forEach(item => {
            const eventTypes = <?php echo wp_json_encode(isset($event_types) ? $event_types : array()); ?> || {};
            const label = eventTypes[item.event_type] || item.event_type;
            
            html += '<div class="pinnerpress-total-item">';
            html += '<span class="pinnerpress-total-number">' + item.total + '</span>';
            html += '<div class="pinnerpress-total-label">' + label + '</div>';
            html += '</div>';
        });
        
        $('#pinnerpress-analytics-totals').html(html);
    }
    
    function loadTopPostsData() {
        const startDate = $('#pinnerpress-start-date').val();
        const endDate = $('#pinnerpress-end-date').val();
        const eventType = $('#pinnerpress-top-posts-event-type').val(); // Get selected event type

        $('#pinnerpress-analytics-top-posts-list .pinnerpress-loading-text').show();

        $.post(ajaxurl, {
            action: 'pinnerpress_get_top_posts',
            nonce: '<?php echo esc_js(wp_create_nonce("pinnerpress_analytics_nonce")); ?>',
            start_date: startDate,
            end_date: endDate,
            event_type: eventType,
            limit: 10
        }, function(response) {
            $('#pinnerpress-analytics-top-posts-list .pinnerpress-loading-text').hide();
            if (response.success && response.data) {
                updateTopPostsList(response.data);
            } else {
                $('#pinnerpress-analytics-top-posts-list').html('<p><?php esc_html_e("Could not load top posts data.", 'pinnerpress'); ?></p>');
                if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.error('Failed to load top posts data:', response.data); }
            }
        }).fail(function() {
            $('#pinnerpress-analytics-top-posts-list .pinnerpress-loading-text').hide();
            $('#pinnerpress-analytics-top-posts-list').html('<p><?php esc_html_e("Error loading top posts data.", 'pinnerpress'); ?></p>');
        });
    }

    function updateTopPostsList(posts) {
        let html;
        if (posts.length === 0) {
            html = '<p><?php esc_html_e("No data for the selected event type and date range.", 'pinnerpress'); ?></p>';
        } else {
            html = '<table class="wp-list-table widefat fixed striped pinnerpress-top-posts-table">';
            html += '<thead>';
            html += '<tr>';
            html += '<th class="column-rank" style="width: 60px;"><?php echo esc_js(__("Rank", 'pinnerpress')); ?></th>';
            html += '<th class="column-preview" style="width: 80px;"><?php echo esc_js(__("Preview", 'pinnerpress')); ?></th>';
            html += '<th class="column-title"><?php echo esc_js(__("Post Title", 'pinnerpress')); ?></th>';
            html += '<th class="column-clicks" style="width: 80px;"><?php echo esc_js(__("Clicks", 'pinnerpress')); ?></th>';
            html += '<th class="column-actions" style="width: 120px;"><?php echo esc_js(__("Actions", 'pinnerpress')); ?></th>';
            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';
            
            posts.forEach((post, index) => {
                const postTitle = post.post_title || '<?php echo esc_js( __( "(No Title)", 'pinnerpress' ) ); ?>';
                const count = post.event_count;
                const rank = index + 1;
                
                // Link to image analytics page with post ID parameter
                const imageAnalyticsUrl = '<?php echo esc_js(admin_url('admin.php?page=pinnerpress-image-analytics')); ?>&post_id=' + post.post_id;
                const postUrl = '<?php echo esc_js(admin_url('post.php?action=edit')); ?>&post=' + post.post_id;
                
                // Get featured image if available
                const featuredImage = post.featured_image || {};
                const imageUrl = featuredImage.url || '';
                const hasImage = featuredImage.has_image || false;
                
                html += '<tr>';
                html += '<td class="column-rank">#' + rank + '</td>';
                html += '<td class="column-preview">';
                if (hasImage && imageUrl) {
                    html += '<img src="' + imageUrl + '" alt="' + postTitle + '" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">';
                } else {
                    html += '<div class="no-image" style="width: 50px; height: 50px; background: #f1f1f1; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #666;">No Image</div>';
                }
                html += '</td>';
                html += '<td class="column-title"><a href="' + postUrl + '">' + postTitle + '</a></td>';
                html += '<td class="column-clicks">' + count + '</td>';
                html += '<td class="column-actions">';
                html += '<a href="' + imageAnalyticsUrl + '" class="button button-small"><?php echo esc_js(__("View Analytics", 'pinnerpress')); ?></a>';
                html += '</td>';
                html += '</tr>';
            });
            
            html += '</tbody>';
            html += '</table>';
        }
        $('#pinnerpress-analytics-top-posts-list').html(html);
    }
    
    // Event handlers
    $('#pinnerpress-update-chart').on('click', function() {
        loadAnalyticsData(); // This already exists
        loadTopPostsData(); // Add call to load top posts
    });
    
    $('#pinnerpress-top-posts-event-type').on('change', function() {
        loadTopPostsData(); // Reload top posts when event type selection changes
    });
    
    // Initialize charts and analytics only if everything is available
    if (typeof Chart !== 'undefined' && <?php echo !empty($event_types) ? 'true' : 'false'; ?>) {
        initChart();
        loadAnalyticsData();
        loadTopPostsData(); // Initial load for top posts
    } else {
        if (typeof Chart === 'undefined') {
            if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.error('Chart.js not loaded'); }
        }
        if (<?php echo empty($event_types) ? 'true' : 'false'; ?>) {
            if (new URLSearchParams(window.location.search).get('pinnerpress_debug') === '1') { console.error('No event types available for analytics'); }
        }
    }
    
    // Enforce free user limitations
    <?php if (!$can_use_premium_features): ?>
    function enforceFreeUserLimitations() {
        // Set the date range to last 7 days relative to server date
        const serverDateStrLocal = $('.pinnerpress-dashboard').data('server-date');
        if (serverDateStrLocal) {
            const today = new Date(serverDateStrLocal + 'T00:00:00');
            const sevenDaysAgo = new Date(today.getTime());
            sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 6); // inclusive 7 days
            $('#pinnerpress-start-date').val(
                sevenDaysAgo.getFullYear() + '-' + String(sevenDaysAgo.getMonth() + 1).padStart(2, '0') + '-' + String(sevenDaysAgo.getDate()).padStart(2, '0')
            );
            $('#pinnerpress-end-date').val(
                today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
            );
        }

        // Disable date inputs and update chart button to prevent manual changes
        $('#pinnerpress-start-date, #pinnerpress-end-date').prop('disabled', true)
            .attr('title', 'Upgrade to Premium to customize date ranges')
            .css({
                'background-color': '#f9f9f9',
                'cursor': 'not-allowed',
                'color': '#666'
            });

        // Also disable the update chart button since dates can't be changed
        $('#pinnerpress-update-chart').prop('disabled', true)
            .attr('title', 'Upgrade to Premium to customize date ranges')
            .css({
                'background-color': '#f9f9f9',
                'border-color': '#ddd',
                'color': '#666',
                'cursor': 'not-allowed'
            });

        // Ensure 30 and 90 day buttons are disabled and styled properly
        $('.pinnerpress-date-preset[data-days="30"], .pinnerpress-date-preset[data-days="90"])'
            .prop('disabled', true)
            .addClass('pinnerpress-premium-disabled')
            .css({
                'background-color': '#f9f9f9',
                'border-color': '#ddd',
                'color': '#666',
                'cursor': 'not-allowed'
            });
    }

    // Call enforcement immediately
    enforceFreeUserLimitations();

    // Prevent any date range changes for free users
    $('#pinnerpress-start-date, #pinnerpress-end-date').on('input change', function(e) {
        e.preventDefault();
        enforceFreeUserLimitations();
        return false;
    });

    // Override the update chart button click for free users
    $('#pinnerpress-update-chart').off('click').on('click', function(e) {
        e.preventDefault();
        enforceFreeUserLimitations();
        loadAnalyticsData();
        loadTopPostsData();
        return false;
    });
    <?php endif; ?>
});
</script>

<!-- DEBUG TEST: If you see this, PHP is working -->
<div style="background: red; color: white; padding: 10px; margin: 20px 0;">
    🔧 DEBUG SECTION TEST - This should be visible at the bottom of the page
</div>

<!-- Debug Section for Analytics Troubleshooting -->
<?php if (current_user_can('manage_options')): ?>
<div style="margin-top: 40px; padding: 20px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 5px;">
    <h2>🔧 Analytics Debug Information</h2>
    <p><em>This section helps troubleshoot analytics issues. Only visible to administrators.</em></p>
    
    <?php
    // Get the analytics table name
    global $wpdb;
    $analytics_table = $wpdb->prefix . 'pinnerpress_analytics';
    $post_analytics_table = $wpdb->prefix . 'pinnerpress_post_analytics';
    ?>
    
    <h3>📊 Table Status</h3>
    <?php
    // Add caching around table existence checks
    $cache_key_tables = 'pinnerpress_tables_exist_main';
    $tables_exist = wp_cache_get($cache_key_tables, 'pinnerpress');
    if ($tables_exist === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-only existence check with caching
        $tables_exist = (strpos($analytics_table, $wpdb->prefix) === 0) ? $wpdb->get_results($wpdb->prepare('SHOW TABLES LIKE %s', $analytics_table)) : array();
        wp_cache_set($cache_key_tables, $tables_exist, 'pinnerpress', 300);
    }
    echo "<p><strong>Main analytics table:</strong> " . (empty($tables_exist) ? "❌ Missing" : "✅ Exists") . "</p>";
    
    $cache_key_post_tables = 'pinnerpress_tables_exist_post';
    $post_tables_exist = wp_cache_get($cache_key_post_tables, 'pinnerpress');
    if ($post_tables_exist === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-only existence check with caching
        $post_tables_exist = (strpos($post_analytics_table, $wpdb->prefix) === 0) ? $wpdb->get_results($wpdb->prepare('SHOW TABLES LIKE %s', $post_analytics_table)) : array();
        wp_cache_set($cache_key_post_tables, $post_tables_exist, 'pinnerpress', 300);
    }
    echo "<p><strong>Post analytics table:</strong> " . (empty($post_tables_exist) ? "❌ Missing" : "✅ Exists") . "</p>";
    ?>
    
    <?php if (!empty($tables_exist)): ?>
        <h3>📈 Recent Events (Last 10)</h3>
        <?php
        // Cache recent events as they're for admin debug display only
        $cache_key_recent = 'pinnerpress_recent_events_debug';
        $recent_events = wp_cache_get($cache_key_recent, 'pinnerpress');
        if ($recent_events === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Admin-only debug query; identifier sanitized via prefix check and esc_sql
            $recent_events = (strpos($analytics_table, $wpdb->prefix) === 0) ? $wpdb->get_results("SELECT * FROM `" . esc_sql($analytics_table) . "` ORDER BY created_at DESC LIMIT 10") : array();
            wp_cache_set($cache_key_recent, $recent_events, 'pinnerpress', 120);
        }
        
        if (empty($recent_events)) {
            echo "<p><strong>⚠️ No events found</strong> - This means no clicks are being tracked.</p>";
        } else {
            echo "<table style='width: 100%; border-collapse: collapse; font-size: 12px;'>";
            echo "<tr style='background: #333; color: white;'><th style='padding: 5px; border: 1px solid #ccc;'>Event Type</th><th style='padding: 5px; border: 1px solid #ccc;'>Post ID</th><th style='padding: 5px; border: 1px solid #ccc;'>Created At</th></tr>";
            foreach ($recent_events as $event) {
                $highlight = ($event->event_type === 'call_out_banner_click') ? 'background-color: #ffffcc;' : '';
                echo "<tr" . ($highlight ? " style='" . esc_attr($highlight) . "'" : '') . ">";
                echo "<td style='padding: 5px; border: 1px solid #ccc;'><strong>" . esc_html($event->event_type) . "</strong></td>";
                echo "<td style='padding: 5px; border: 1px solid #ccc;'>" . esc_html($event->post_id) . "</td>";
                echo "<td style='padding: 5px; border: 1px solid #ccc;'>" . esc_html($event->created_at) . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        }
        ?>
        
        <h3>📊 Event Counts</h3>
        <?php
        // Cache event counts as well
        $cache_key_counts = 'pinnerpress_event_counts_debug';
        $event_counts = wp_cache_get($cache_key_counts, 'pinnerpress');
        if ($event_counts === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Admin-only debug query; identifier sanitized via prefix check and esc_sql
            $event_counts = (strpos($analytics_table, $wpdb->prefix) === 0) ? $wpdb->get_results("SELECT event_type, COUNT(*) as count FROM `" . esc_sql($analytics_table) . "` GROUP BY event_type ORDER BY count DESC") : array();
            wp_cache_set($cache_key_counts, $event_counts, 'pinnerpress', 120);
        }
        
        if (!empty($event_counts)) {
            echo "<table style='width: 100%; border-collapse: collapse;'>";
            echo "<tr style='background: #333; color: white;'><th style='padding: 8px; border: 1px solid #ccc;'>Event Type</th><th style='padding: 8px; border: 1px solid #ccc;'>Total Count</th></tr>";
            foreach ($event_counts as $count) {
                $highlight = ($count->event_type === 'call_out_banner_click') ? 'background-color: #ffffcc;' : '';
                echo "<tr" . ($highlight ? " style='" . esc_attr($highlight) . "'" : '') . ">";
                echo "<td style='padding: 8px; border: 1px solid #ccc;'><strong>" . esc_html($count->event_type) . "</strong></td>";
                echo "<td style='padding: 8px; border: 1px solid #ccc;'>" . esc_html($count->count) . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        }
        ?>
    <?php endif; ?>
    
    <h3>⚙️ Settings Status</h3>
    <table style="width: 100%; border-collapse: collapse;">
        <tr style="background: #333; color: white;">
            <th style="padding: 8px; border: 1px solid #ccc;">Setting</th>
            <th style="padding: 8px; border: 1px solid #ccc;">Value</th>
            <th style="padding: 8px; border: 1px solid #ccc;">Impact</th>
        </tr>
        <tr>
            <td style="padding: 8px; border: 1px solid #ccc;">Analytics enabled</td>
            <td style="padding: 8px; border: 1px solid #ccc;"><strong><?php echo esc_html(get_option('pinnerpress_analytics_enabled', 'not set')); ?></strong></td>
            <td style="padding: 8px; border: 1px solid #ccc;"><?php echo (get_option('pinnerpress_analytics_enabled', '1') === '1') ? '✅ Events will be tracked' : '❌ Events will NOT be tracked'; ?></td>
        </tr>
        <tr style="background-color: #ffffcc;">
            <td style="padding: 8px; border: 1px solid #ccc;"><strong>Ignore logged in users</strong></td>
            <td style="padding: 8px; border: 1px solid #ccc;"><strong><?php echo esc_html(get_option('pinnerpress_analytics_ignore_logged_in', 'not set')); ?></strong></td>
            <td style="padding: 8px; border: 1px solid #ccc;"><?php echo (get_option('pinnerpress_analytics_ignore_logged_in', '0') === '1') ? '❌ Your clicks will NOT be tracked' : '✅ All users tracked'; ?></td>
        </tr>
    </table>
    
    <h3>👤 Your Status</h3>
    <p><strong>Logged in:</strong> <?php echo is_user_logged_in() ? "YES" : "NO"; ?></p>
    <?php if (is_user_logged_in()): ?>
        <?php $current_user = wp_get_current_user(); ?>
        <p><strong>User ID:</strong> <?php echo esc_html($current_user->ID); ?></p>
        <p><strong>Role:</strong> <?php echo esc_html(implode(', ', $current_user->roles)); ?></p>
        <p><strong>Will your clicks be tracked?</strong> 
            <?php 
            $ignore_logged_in = get_option('pinnerpress_analytics_ignore_logged_in', '0') === '1';
            echo $ignore_logged_in ? "❌ <strong>NO</strong> - logged-in users are ignored" : "✅ <strong>YES</strong>"; 
            ?>
        </p>
    <?php endif; ?>
    
    <?php if (is_user_logged_in() && get_option('pinnerpress_analytics_ignore_logged_in', '0') === '1'): ?>
        <div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin-top: 15px;">
            <h4>⚠️ This is likely why you're not seeing clicks!</h4>
            <p>The analytics is set to <strong>ignore logged-in users</strong>, and you are currently logged in. This means your clicks on call out banner buttons won't be tracked.</p>
            <p><strong>To test:</strong></p>
            <ul>
                <li>Visit your site in an <strong>incognito/private browser window</strong> (not logged in)</li>
                <li>Or temporarily disable "<strong>Ignore logged in users</strong>" in the PinnerPress Settings → General tab</li>
            </ul>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>

