<?php
/**
 * Dashboard widget: download stats from chesspodium.com (admin only).
 *
 * @package Chess_Podium
 */

if (!defined('ABSPATH')) {
    exit;
}

add_action('wp_dashboard_setup', function () {
    if (!current_user_can('manage_options')) {
        return;
    }
    // Only show on chesspodium.com (marketing site), not on sites that install the plugin
    $host = wp_parse_url(home_url(), PHP_URL_HOST);
    $allowed = ['chesspodium.com', 'www.chesspodium.com'];
    $show = $host && in_array(strtolower($host), $allowed, true);
    if (!$show && !apply_filters('chess_podium_show_download_stats_widget', false)) {
        return;
    }

    wp_add_dashboard_widget(
        'chess_podium_download_stats',
        __('Chess Podium – Download stats', 'chess-podium'),
        function () {
            if (function_exists('chess_podium_get_download_stats')) {
                $stats = chess_podium_get_download_stats();
            } else {
                $count = (int) get_option('chess_podium_site_download_count', 0);
                $stats = ['count' => $count, 'source' => 'site'];
            }

            $formatted = number_format_i18n($stats['count']);
            $source = ($stats['source'] ?? 'site') === 'override'
                ? __('manual override', 'chess-podium')
                : __('from chesspodium.com', 'chess-podium');

            echo '<p style="font-size:1.75rem;font-weight:600;margin:0 0 0.5rem;">' . esc_html($formatted) . '</p>';
            echo '<p class="description" style="margin:0;">' . esc_html__('downloads', 'chess-podium') . ' ' . esc_html($source) . '</p>';
        },
        null,
        null,
        'side',
        'high'
    );
}, 20);
