<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL -- Analytics are stored in plugin-owned custom tables.
/**
 * Performance Analytics Tab Content
 *
 * Comprehensive analytics dashboard for popup performance, subscriber metrics, and campaign analytics
 */
if (!defined('ABSPATH')) exit; // Exit if accessed directly
// Check if subscription extension is active
if (!function_exists('is_plugin_active')) {
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$instant_popup_builder_subscription_extension_active = function_exists('is_plugin_active') && is_plugin_active('instant-popup-subscription/instant-popup-subscription.php');
$instant_popup_builder_subscription_license_active = get_option('subscription_license_active') === 'yes';
// Get database connection
global $wpdb;
// Define table names
$instant_popup_builder_subscribers_table = $wpdb->prefix . 'instant_popup_subscriber';
$instant_popup_builder_escaped_subscribers_table = esc_sql($instant_popup_builder_subscribers_table);
$instant_popup_builder_campaigns_table = $wpdb->prefix . 'instant_popup_newsletter_campaigns';
$instant_popup_builder_escaped_campaigns_table = esc_sql($instant_popup_builder_campaigns_table);
$instant_popup_builder_popups_table = $wpdb->prefix . 'instant_popup_builder';
$instant_popup_builder_escaped_popups_table = esc_sql($instant_popup_builder_popups_table);
// Date range filter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameters used for filtering/display purposes only, values are sanitized
$instant_popup_builder_date_range = isset($_GET['date_range']) ? sanitize_text_field(wp_unslash($_GET['date_range'])) : '30';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameters used for filtering/display purposes only, values are sanitized
$instant_popup_builder_custom_start = isset($_GET['custom_start']) ? sanitize_text_field(wp_unslash($_GET['custom_start'])) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameters used for filtering/display purposes only, values are sanitized
$instant_popup_builder_custom_end = isset($_GET['custom_end']) ? sanitize_text_field(wp_unslash($_GET['custom_end'])) : '';
// Calculate date range
switch ($instant_popup_builder_date_range) {
    case '7':
        $instant_popup_builder_start_date = gmdate('Y-m-d', strtotime('-7 days'));
        $instant_popup_builder_end_date = gmdate('Y-m-d');
        break;
    case '30':
        $instant_popup_builder_start_date = gmdate('Y-m-d', strtotime('-30 days'));
        $instant_popup_builder_end_date = gmdate('Y-m-d');
        break;
    case '90':
        $instant_popup_builder_start_date = gmdate('Y-m-d', strtotime('-90 days'));
        $instant_popup_builder_end_date = gmdate('Y-m-d');
        break;
    case 'custom':
        $instant_popup_builder_start_date = $instant_popup_builder_custom_start ?: gmdate('Y-m-d', strtotime('-30 days'));
        $instant_popup_builder_end_date = $instant_popup_builder_custom_end ?: gmdate('Y-m-d');
        break;
    default:
        $instant_popup_builder_start_date = gmdate('Y-m-d', strtotime('-30 days'));
        $instant_popup_builder_end_date = gmdate('Y-m-d');
}
// Fetch analytics data
function instant_popup_builder_get_analytics_data($wpdb, $instant_popup_builder_subscribers_table, $instant_popup_builder_campaigns_table, $instant_popup_builder_popups_table, $start_date, $end_date) {
    // Escape table names for safe use in SQL queries
    $instant_popup_builder_escaped_subscribers_table = esc_sql($instant_popup_builder_subscribers_table);
    $instant_popup_builder_escaped_campaigns_table = esc_sql($instant_popup_builder_campaigns_table);
    $instant_popup_builder_escaped_popups_table = esc_sql($instant_popup_builder_popups_table);

    $instant_popup_builder_data = [];
    // Check if tables exist before querying
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $instant_popup_builder_tables_exist = [
        'subscribers' => $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_subscribers_table)),
        'campaigns' => $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_campaigns_table)),
        'popups' => $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_popups_table))
    ];
    // Total subscribers
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $instant_popup_builder_data['total_subscribers'] = $instant_popup_builder_tables_exist['subscribers'] ?
        $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}`") : 0;
    // New subscribers in date range
    if ($instant_popup_builder_tables_exist['subscribers']) {
        // Use DATE() function with correct column name 'created'
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
        $instant_popup_builder_new_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE DATE(created) BETWEEN %s AND %s",
            $start_date, $end_date
        ));
        $instant_popup_builder_data['new_subscribers'] = $instant_popup_builder_new_count;
    } else {
        $instant_popup_builder_data['new_subscribers'] = 0;
    }
    // Active subscribers - try different status values
    if ($instant_popup_builder_tables_exist['subscribers']) {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
        $instant_popup_builder_active_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE status = 'active'");
        if ($instant_popup_builder_active_count == 0) {
            // Try alternative status values
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
            $instant_popup_builder_active_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE status = 'Active'");
        }
        if ($instant_popup_builder_active_count == 0) {
            // Try numeric status
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
            $instant_popup_builder_active_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE status = '1'");
        }
        if ($instant_popup_builder_active_count == 0) {
            // Try yes/no status
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
            $instant_popup_builder_active_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE status = 'yes'");
        }
        if ($instant_popup_builder_active_count == 0) {
            // If still 0, maybe all subscribers are active by default
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
            $instant_popup_builder_active_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}`");
        }
        $instant_popup_builder_data['active_subscribers'] = $instant_popup_builder_active_count;
    } else {
        $instant_popup_builder_data['active_subscribers'] = 0;
    }
    // Total campaigns
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $instant_popup_builder_data['total_campaigns'] = $instant_popup_builder_tables_exist['campaigns'] ?
        $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_campaigns_table}` WHERE status != 'deleted'") : 0;
    // Sent campaigns
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $instant_popup_builder_data['sent_campaigns'] = $instant_popup_builder_tables_exist['campaigns'] ?
        $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_campaigns_table}` WHERE sent_count > 0") : 0;
    // Total popups
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $instant_popup_builder_data['total_popups'] = $instant_popup_builder_tables_exist['popups'] ?
        $wpdb->get_var("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_popups_table}` WHERE type = 'subscription'") : 0;
    // Privacy agreed percentage
    if ($instant_popup_builder_tables_exist['subscribers'] && $instant_popup_builder_data['total_subscribers'] > 0) {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
        $instant_popup_builder_privacy_agreed = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE privacy = %s", 'yes'));
        // Prevent division by zero
        $total_subscribers = max($instant_popup_builder_data['total_subscribers'], 1);
        $instant_popup_builder_data['privacy_rate'] = round(($instant_popup_builder_privacy_agreed / $total_subscribers) * 100, 1);
    } else {
        $instant_popup_builder_data['privacy_rate'] = 0;
    }
    // Top performing popups
    $instant_popup_builder_data['top_popups'] = [];
    if ($instant_popup_builder_tables_exist['popups'] && $instant_popup_builder_tables_exist['subscribers']) {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
        $instant_popup_builder_data['top_popups'] = $wpdb->get_results($wpdb->prepare("
            SELECT p.title, p.id, COUNT(s.id) as subscriber_count
            FROM `{$instant_popup_builder_escaped_popups_table}` p
            LEFT JOIN `{$instant_popup_builder_escaped_subscribers_table}` s ON p.id = s.campaign
            WHERE p.type = 'subscription' AND (s.created IS NULL OR DATE(s.created) BETWEEN %s AND %s)
            GROUP BY p.id, p.title
            ORDER BY subscriber_count DESC
            LIMIT 5
        ", $start_date, $end_date), ARRAY_A);
    }
    // Daily subscriber growth
    $instant_popup_builder_data['daily_growth'] = [];
    if ($instant_popup_builder_tables_exist['subscribers']) {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
        $instant_popup_builder_data['daily_growth'] = $wpdb->get_results($wpdb->prepare("
            SELECT DATE(created) as date, COUNT(*) as count
            FROM `{$instant_popup_builder_escaped_subscribers_table}`
            WHERE DATE(created) BETWEEN %s AND %s
            GROUP BY DATE(created)
            ORDER BY date ASC
        ", $start_date, $end_date), ARRAY_A);
    }
    // Email campaign performance
    $instant_popup_builder_data['campaign_performance'] = [];
    if ($instant_popup_builder_tables_exist['campaigns']) {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
        $instant_popup_builder_data['campaign_performance'] = $wpdb->get_results("
            SELECT name, sent_count, open_count, click_count, created_at,
                   CASE
                       WHEN sent_count > 0 THEN ROUND((open_count / sent_count) * 100, 1)
                       ELSE 0
                   END as open_rate,
                   CASE
                       WHEN sent_count > 0 THEN ROUND((click_count / sent_count) * 100, 1)
                       ELSE 0
                   END as click_rate
            FROM `{$instant_popup_builder_escaped_campaigns_table}`
            WHERE status != 'deleted' AND sent_count > 0
            ORDER BY created_at DESC
            LIMIT 10
        ", ARRAY_A);
    }

    return $instant_popup_builder_data;
}

// Initialize analytics with default values
$instant_popup_builder_analytics = [
    'total_subscribers' => 0,
    'new_subscribers' => 0,
    'active_subscribers' => 0,
    'sent_campaigns' => 0,
    'total_campaigns' => 0,
    'total_popups' => 0,
    'privacy_rate' => 0,
    'daily_growth' => [],
    'top_popups' => [],
    'campaign_performance' => []
];

if ($instant_popup_builder_subscription_extension_active && $instant_popup_builder_subscription_license_active) {
    $instant_popup_builder_analytics_data = instant_popup_builder_get_analytics_data($wpdb, $instant_popup_builder_subscribers_table, $instant_popup_builder_campaigns_table, $instant_popup_builder_popups_table, $instant_popup_builder_start_date, $instant_popup_builder_end_date);
    // Merge with defaults to ensure all keys exist
    $instant_popup_builder_analytics = array_merge($instant_popup_builder_analytics, $instant_popup_builder_analytics_data);
}
// Check if tables exist
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
$instant_popup_builder_subscribers_table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_subscribers_table)) ? true : false;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
$instant_popup_builder_campaigns_table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_campaigns_table)) ? true : false;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
$instant_popup_builder_popups_table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_popups_table)) ? true : false;
// Calculate growth percentages
$instant_popup_builder_previous_period_start = gmdate('Y-m-d', strtotime($instant_popup_builder_start_date . ' -' . (strtotime($instant_popup_builder_end_date) - strtotime($instant_popup_builder_start_date)) . ' seconds'));
$instant_popup_builder_previous_subscribers = 0;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
if ($instant_popup_builder_subscription_extension_active && $instant_popup_builder_subscription_license_active && $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_subscribers_table))) {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $instant_popup_builder_previous_subscribers = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_subscribers_table}` WHERE DATE(created) BETWEEN %s AND %s",
        $instant_popup_builder_previous_period_start, $instant_popup_builder_start_date
    ));
}
$instant_popup_builder_new_subscribers_count = isset($instant_popup_builder_analytics['new_subscribers']) ? $instant_popup_builder_analytics['new_subscribers'] : 0;
$instant_popup_builder_growth_rate = $instant_popup_builder_previous_subscribers > 0 ?
    round((($instant_popup_builder_new_subscribers_count - $instant_popup_builder_previous_subscribers) / $instant_popup_builder_previous_subscribers) * 100, 1) :
    ($instant_popup_builder_new_subscribers_count > 0 ? 100 : 0);
?>
<div class="analytics-dashboard">
    <!-- Analytics Header -->
    <div class="analytics-header">
        <div class="header-content">
            <h3>Performance Analytics Dashboard</h3>
            <p>Comprehensive insights into your popup subscription performance and campaign metrics</p>
        </div>
    </div>
    <!-- Simple Date Range Display -->
    <div class="date-range-display">
        <span class="date-range-label">Showing data for:</span>
        <span class="date-range-value">
            <?php
            switch ($instant_popup_builder_date_range) {
                case '7':
                    echo 'Last 7 days';
                    break;
                case '30':
                    echo 'Last 30 days';
                    break;
                case '90':
                    echo 'Last 90 days';
                    break;
                case 'custom':
                    echo esc_html(gmdate('M j, Y', strtotime($instant_popup_builder_start_date))) . ' - ' . esc_html(gmdate('M j, Y', strtotime($instant_popup_builder_end_date)));
                    break;
                default:
                    echo 'Last 30 days';
            }
            ?>
        </span>
    </div>
    <!-- Key Metrics Cards -->
    <div class="metrics-grid">
        <div class="metric-card">
            <div class="metric-icon">
                <span class="dashicons dashicons-groups"></span>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($instant_popup_builder_analytics['total_subscribers']); ?></div>
                <div class="metric-label">Total Subscribers</div>
                <div class="metric-change <?php echo $instant_popup_builder_growth_rate >= 0 ? 'positive' : 'negative'; ?>">
                    <span class="dashicons dashicons-arrow-<?php echo $instant_popup_builder_growth_rate >= 0 ? 'up' : 'down'; ?>-alt"></span>
                    <?php echo esc_html(abs($instant_popup_builder_growth_rate)); ?>% vs previous period
                </div>
            </div>
        </div>
        <div class="metric-card">
            <div class="metric-icon">
                <span class="dashicons dashicons-plus-alt"></span>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($instant_popup_builder_analytics['new_subscribers']); ?></div>
                <div class="metric-label">New Subscribers</div>
                <div class="metric-change">
                    <span class="dashicons dashicons-calendar-alt"></span>
                    <?php echo $instant_popup_builder_date_range === 'custom' ? esc_html('Selected Period') : esc_html("Last $instant_popup_builder_date_range days"); ?>
                </div>
            </div>
        </div>
        <div class="metric-card">
            <div class="metric-icon">
                <span class="dashicons dashicons-yes-alt"></span>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($instant_popup_builder_analytics['active_subscribers']); ?></div>
                <div class="metric-label">Active Subscribers</div>
                <div class="metric-change">
                    <span class="dashicons dashicons-info"></span>
                    <?php
                    $instant_popup_builder_total_subs = max($instant_popup_builder_analytics['total_subscribers'], 1);
                    $instant_popup_builder_active_subs = max($instant_popup_builder_analytics['active_subscribers'], 0);
                    echo esc_html(round(($instant_popup_builder_active_subs / $instant_popup_builder_total_subs) * 100, 1));
                    ?>% of total
                </div>
            </div>
        </div>
        <div class="metric-card">
            <div class="metric-icon">
                <span class="dashicons dashicons-email-alt"></span>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($instant_popup_builder_analytics['sent_campaigns']); ?></div>
                <div class="metric-label">Campaigns Sent</div>
                <div class="metric-change">
                    <span class="dashicons dashicons-megaphone"></span>
                    <?php echo esc_html($instant_popup_builder_analytics['total_campaigns']); ?> total campaigns
                </div>
            </div>
        </div>
        <div class="metric-card">
            <div class="metric-icon">
                <span class="dashicons dashicons-admin-post"></span>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($instant_popup_builder_analytics['total_popups']); ?></div>
                <div class="metric-label">Active Popups</div>
                <div class="metric-change">
                    <span class="dashicons dashicons-visibility"></span>
                    Subscription type popups
                </div>
            </div>
        </div>
        <div class="metric-card">
            <div class="metric-icon">
                <span class="dashicons dashicons-privacy"></span>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo esc_html($instant_popup_builder_analytics['privacy_rate']); ?>%</div>
                <div class="metric-label">Privacy Compliance</div>
                <div class="metric-change">
                    <span class="dashicons dashicons-shield"></span>
                    Users agreed to privacy
                </div>
            </div>
        </div>
    </div>
    <!-- Charts Section -->
    <div class="charts-section">
        <div class="chart-container">
            <div class="chart-header">
                <h4><span class="dashicons dashicons-chart-line"></span> Subscriber Growth Trend</h4>
                <p>Daily subscriber acquisitions over the selected period</p>
            </div>
            <div class="chart-content">
                <canvas id="growthChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>
    <!-- Performance Tables -->
    <div class="performance-section">
        <div class="performance-grid">
            <!-- Top Performing Popups -->
            <div class="performance-table">
                <div class="table-header">
                    <h4><span class="dashicons dashicons-star-filled"></span> Top Performing Popups</h4>
                    <p>Popups with the most subscribers in the selected period</p>
                </div>
                <div class="table-content">
                    <?php if (!empty($instant_popup_builder_analytics['top_popups'])): ?>
                        <table class="wp-list-table widefat fixed striped">
                            <thead>
                                <tr>
                                    <th>Popup Title</th>
                                    <th>Subscribers</th>
                                    <th>Performance</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($instant_popup_builder_analytics['top_popups'] as $instant_popup_builder_index => $instant_popup_builder_popup): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo esc_html($instant_popup_builder_popup['title']); ?></strong>
                                            <div class="popup-id">ID: <?php echo esc_html($instant_popup_builder_popup['id']); ?></div>
                                        </td>
                                        <td>
                                            <span class="subscriber-count"><?php echo number_format($instant_popup_builder_popup['subscriber_count']); ?></span>
                                        </td>
                                        <td>
                                            <div class="performance-bar">
                                                <div class="performance-fill" data-width="<?php echo esc_attr($instant_popup_builder_index === 0 && $instant_popup_builder_popup['subscriber_count'] > 0 ? '100' : (($instant_popup_builder_popup['subscriber_count'] / max($instant_popup_builder_analytics['top_popups'][0]['subscriber_count'], 1)) * 100)); ?>"></div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="no-data">
                            <span class="dashicons dashicons-info"></span>
                            <p>No popup performance data available for the selected period.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <!-- Campaign Performance -->
            <div class="performance-table">
                <div class="table-header">
                    <h4><span class="dashicons dashicons-email-alt2"></span> Campaign Performance</h4>
                    <p>Recent email campaign metrics and engagement rates</p>
                </div>
                <div class="table-content">
                    <?php if (!empty($instant_popup_builder_analytics['campaign_performance'])): ?>
                        <table class="wp-list-table widefat fixed striped">
                            <thead>
                                <tr>
                                    <th>Campaign Name</th>
                                    <th>Sent</th>
                                    <th>Open Rate</th>
                                    <th>Click Rate</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($instant_popup_builder_analytics['campaign_performance'] as $instant_popup_builder_campaign): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo esc_html($instant_popup_builder_campaign['name']); ?></strong>
                                            <div class="campaign-date"><?php echo esc_html(gmdate('M d, Y', strtotime($instant_popup_builder_campaign['created_at']))); ?></div>
                                        </td>
                                        <td>
                                            <span class="sent-count"><?php echo number_format($instant_popup_builder_campaign['sent_count']); ?></span>
                                        </td>
                                        <td>
                                            <div class="rate-display">
                                                <span class="rate-value <?php echo $instant_popup_builder_campaign['open_rate'] >= 20 ? 'good' : ($instant_popup_builder_campaign['open_rate'] >= 10 ? 'average' : 'poor'); ?>">
                                                    <?php echo esc_html($instant_popup_builder_campaign['open_rate']); ?>%
                                                </span>
                                                <div class="rate-bar">
                                                    <div class="rate-fill" data-width="<?php echo esc_attr(min($instant_popup_builder_campaign['open_rate'], 100)); ?>"></div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="rate-display">
                                                <span class="rate-value <?php echo $instant_popup_builder_campaign['click_rate'] >= 5 ? 'good' : ($instant_popup_builder_campaign['click_rate'] >= 2 ? 'average' : 'poor'); ?>">
                                                    <?php echo esc_html($instant_popup_builder_campaign['click_rate']); ?>%
                                                </span>
                                                <div class="rate-bar">
                                                    <div class="rate-fill" data-width="<?php echo esc_attr(min($instant_popup_builder_campaign['click_rate'] * 10, 100)); ?>"></div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="no-data">
                            <span class="dashicons dashicons-info"></span>
                            <p>No campaign performance data available. Send some campaigns to see metrics here.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <!-- Export Section -->
    <div class="export-section">
        <div class="export-container">
            <h4><span class="dashicons dashicons-download"></span> Export Analytics Data</h4>
            <p>Download your analytics data for external analysis and reporting</p>
            <div class="export-buttons">
                <button type="button" class="button button-secondary" onclick="exportData('csv')">
                    <span class="dashicons dashicons-media-spreadsheet"></span>
                    Export as CSV
                </button>
                <button type="button" class="button button-secondary" onclick="exportData('pdf')">
                    <span class="dashicons dashicons-pdf"></span>
                    Export as PDF Report
                </button>
                <button type="button" class="button button-secondary" onclick="printReport()">
                    <span class="dashicons dashicons-printer"></span>
                    Print Report
                </button>
            </div>
        </div>
    </div>
</div>
<script>
// Initialize dynamic bar widths from data attributes
document.addEventListener('DOMContentLoaded', function() {
    // Set performance bar widths
    var performanceFills = document.querySelectorAll('.performance-fill[data-width]');
    performanceFills.forEach(function(fill) {
        var width = fill.getAttribute('data-width');
        if (width !== null) {
            fill.style.width = width + '%';
        }
    });

    // Set rate bar widths
    var rateFills = document.querySelectorAll('.rate-fill[data-width]');
    rateFills.forEach(function(fill) {
        var width = fill.getAttribute('data-width');
        if (width !== null) {
            fill.style.width = width + '%';
        }
    });

    // Chart.js implementation for growth chart
    // Prepare data for chart
    var dailyGrowthData = <?php echo json_encode($instant_popup_builder_analytics['daily_growth']); ?>;
    var chartLabels = [];
    var chartData = [];
    // Fill in missing dates with 0 values
    var startDate = new Date('<?php echo esc_js($instant_popup_builder_start_date); ?>');
    var endDate = new Date('<?php echo esc_js($instant_popup_builder_end_date); ?>');
    var currentDate = new Date(startDate);
    while (currentDate <= endDate) {
        var dateStr = currentDate.toISOString().split('T')[0];
        chartLabels.push(dateStr);
        var found = dailyGrowthData.find(function(item) {
            return item.date === dateStr;
        });
        chartData.push(found ? parseInt(found.count) : 0);
        currentDate.setDate(currentDate.getDate() + 1);
    }
    // Create chart if Chart.js is available
    if (typeof Chart !== 'undefined') {
        var ctx = document.getElementById('growthChart');
        if (ctx) {
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartLabels.map(function(date) {
                        return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                    }),
                    datasets: [{
                        label: 'New Subscribers',
                        data: chartData,
                        borderColor: '#2271b1',
                        backgroundColor: 'rgba(34, 113, 177, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#2271b1',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        pointHoverRadius: 7
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            },
                            grid: {
                                color: '#f0f0f0'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    elements: {
                        point: {
                            hoverBackgroundColor: '#1e5a8a'
                        }
                    }
                }
            });
        }
    } else {
        // Fallback if Chart.js is not loaded
        var chartContainer = document.getElementById('growthChart');
        if (chartContainer) {
            chartContainer.innerHTML = '<div class="chart-error-message">Chart.js library not loaded. Please ensure Chart.js is included.</div>';
        }
    }
});
// Date range display - no toggle needed for simple display
// Export functions
function exportData(format) {
    if (format === 'csv') {
        // Create CSV data
        var csvContent = "data:text/csv;charset=utf-8,";
        csvContent += "Metric,Value\n";
        csvContent += "Total Subscribers,<?php echo esc_js($instant_popup_builder_analytics['total_subscribers']); ?>\n";
        csvContent += "New Subscribers,<?php echo esc_js($instant_popup_builder_analytics['new_subscribers']); ?>\n";
        csvContent += "Active Subscribers,<?php echo esc_js($instant_popup_builder_analytics['active_subscribers']); ?>\n";
        csvContent += "Campaigns Sent,<?php echo esc_js($instant_popup_builder_analytics['sent_campaigns']); ?>\n";
        csvContent += "Privacy Compliance Rate,<?php echo esc_js($instant_popup_builder_analytics['privacy_rate']); ?>%\n";
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "analytics_data_<?php echo esc_js(gmdate('Y-m-d')); ?>.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } else if (format === 'pdf') {
        alert('PDF export functionality will be implemented in a future update.');
    }
}
function printReport() {
    window.print();
}
</script>
